mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 22:33:08 +00:00
Merge main into feat/textures-map-art-and-shading
This commit is contained in:
+98
-2
@@ -94,6 +94,50 @@ impl Intent {
|
||||
}
|
||||
}
|
||||
|
||||
/// A color management policy (Edit → Color Settings): what opening a document does with a profile
|
||||
/// it is tagged with that is not the working space of its model.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Policy {
|
||||
/// The document loses the profile; its color numbers stay as they are.
|
||||
Off,
|
||||
/// The document keeps the profile.
|
||||
#[default]
|
||||
PreserveEmbedded,
|
||||
/// The colors are converted from the profile into the working space, which keeps their
|
||||
/// appearance, and the document loses the profile.
|
||||
Convert,
|
||||
/// CMYK only: the document loses the profile; its color numbers stay as they are.
|
||||
PreserveNumbers,
|
||||
}
|
||||
|
||||
impl Policy {
|
||||
/// The RGB policies, in menu order.
|
||||
pub const RGB: [Policy; 3] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert];
|
||||
/// The CMYK policies, in menu order.
|
||||
pub const CMYK: [Policy; 4] = [Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers];
|
||||
/// Parse an id of [`Policy::id`].
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Policy::Off, Policy::PreserveEmbedded, Policy::Convert, Policy::PreserveNumbers].into_iter().find(|p| p.id() == s)
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "off",
|
||||
Policy::PreserveEmbedded => "preserveEmbedded",
|
||||
Policy::Convert => "convert",
|
||||
Policy::PreserveNumbers => "preserveNumbers",
|
||||
}
|
||||
}
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Policy::Off => "Off",
|
||||
Policy::PreserveEmbedded => "Preserve Embedded Profiles",
|
||||
Policy::Convert => "Convert to Working Space",
|
||||
Policy::PreserveNumbers => "Preserve Numbers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProfileKind {
|
||||
@@ -134,11 +178,25 @@ pub struct ColorSettings {
|
||||
pub intent: Intent,
|
||||
/// Black-point compensation.
|
||||
pub bpc: bool,
|
||||
/// The color management policy for RGB profiles (one of [`Policy::RGB`]). Settings saved
|
||||
/// without one take the default.
|
||||
#[serde(default)]
|
||||
pub rgb_policy: Policy,
|
||||
/// The color management policy for CMYK profiles. Settings saved without one take the default.
|
||||
#[serde(default)]
|
||||
pub cmyk_policy: Policy,
|
||||
}
|
||||
|
||||
impl Default for ColorSettings {
|
||||
fn default() -> Self {
|
||||
Self { rgb: SRGB.into(), cmyk: GENERIC_CMYK.into(), intent: Intent::RelativeColorimetric, bpc: true }
|
||||
Self {
|
||||
rgb: SRGB.into(),
|
||||
cmyk: GENERIC_CMYK.into(),
|
||||
intent: Intent::RelativeColorimetric,
|
||||
bpc: true,
|
||||
rgb_policy: Policy::default(),
|
||||
cmyk_policy: Policy::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,6 +576,41 @@ impl Cms {
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
|
||||
/// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s
|
||||
/// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to
|
||||
/// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded
|
||||
/// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's
|
||||
/// black-point compensation; CMYK goes through Lab when either space is built in. Grey and
|
||||
/// Lab colours stay as they are.
|
||||
pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let icc = |s: &RgbSpace| match s {
|
||||
RgbSpace::Icc(p) => Some(p.clone()),
|
||||
RgbSpace::Srgb => builtin_rgb_cache(SRGB),
|
||||
};
|
||||
let [r, g, b] = icc(&self.rgb)
|
||||
.zip(icc(&dest.rgb))
|
||||
.and_then(|(s, d)| s.to_rgb_of(&d, &[r, g, b], intent, self.settings.bpc))
|
||||
.unwrap_or_else(|| dest.srgb_to_rgb(self.rgb_to_srgb([r, g, b])));
|
||||
Color::Rgb { r, g, b }
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
let inks = [c, m, y, k].map(|v| v.clamp(0.0, 1.0));
|
||||
let direct = match (&self.cmyk, &dest.cmyk) {
|
||||
(CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc),
|
||||
_ => None,
|
||||
};
|
||||
let [c, m, y, k] = match direct.as_deref() {
|
||||
Some(&[c, m, y, k]) => [c, m, y, k],
|
||||
_ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent),
|
||||
};
|
||||
Color::Cmyk { c, m, y, k }
|
||||
}
|
||||
Color::Gray { .. } | Color::Lab { .. } => *c,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (ΔE2000) the best CMYK reproduction of `c` is from `c` (0 for CMYK/grey colours).
|
||||
pub fn gamut_error(&self, c: &Color) -> f32 {
|
||||
match c {
|
||||
@@ -966,8 +1059,11 @@ pub fn working_settings() -> ColorSettings {
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
/// leaving both unchanged, if a profile is unknown or the RGB policy is Preserve Numbers).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
if !Policy::RGB.contains(&settings.rgb_policy) {
|
||||
return Err(CmsError::Unsupported(format!("the RGB policy can't be {}", settings.rgb_policy.id())));
|
||||
}
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
|
||||
@@ -34,6 +34,17 @@ type Xf = Option<Arc<TransformF32Executor>>;
|
||||
/// generation only lets the cache drop what reloads left behind.
|
||||
type DirectKey = (u64, u64, usize, bool);
|
||||
|
||||
/// The transforms of [`IccProfile::to_same_model_of`]: into ProPhoto RGB's primaries with linear
|
||||
/// tone curves, where black-point compensation is a linear remap, and from there into the
|
||||
/// destination.
|
||||
struct SameModel {
|
||||
into: Arc<TransformF32Executor>,
|
||||
out_of: Arc<TransformF32Executor>,
|
||||
/// The source's and the destination's black as luminance in the linear space (both 0 without
|
||||
/// compensation).
|
||||
black: [f32; 2],
|
||||
}
|
||||
|
||||
/// A parsed ICC profile plus lazily-built transforms to/from sRGB.
|
||||
pub struct IccProfile {
|
||||
pub name: String,
|
||||
@@ -49,6 +60,9 @@ pub struct IccProfile {
|
||||
/// Direct transforms into other RGB profiles ([`Self::to_rgb_of`]), by destination, intent
|
||||
/// and black-point compensation.
|
||||
direct: Mutex<Vec<(DirectKey, Option<Arc<Direct>>)>>,
|
||||
/// Transforms into other profiles of the same model ([`Self::to_same_model_of`]), keyed as
|
||||
/// [`Self::direct`] is.
|
||||
same_model: Mutex<Vec<(DirectKey, Option<Arc<SameModel>>)>>,
|
||||
}
|
||||
|
||||
/// A transform from one profile into an RGB profile without passing through sRGB: into the
|
||||
@@ -99,6 +113,7 @@ impl IccProfile {
|
||||
to_srgb: Default::default(),
|
||||
from_srgb: Default::default(),
|
||||
direct: Mutex::new(Vec::new()),
|
||||
same_model: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -264,6 +279,69 @@ impl IccProfile {
|
||||
Some(Direct { to_linear, to_dest: Some(to_dest), black })
|
||||
}
|
||||
|
||||
/// Device values of this profile → device values of `dest`, a profile of the same model,
|
||||
/// converted with `intent` through ProPhoto RGB rather than sRGB, so colours outside sRGB
|
||||
/// keep their place. With `bpc` (and an intent other than absolute), this profile's black
|
||||
/// maps onto the destination's black (black-point compensation). `None` when `dest` is of
|
||||
/// another model or no transform can be built.
|
||||
pub fn to_same_model_of(&self, dest: &IccProfile, v: &[f32], intent: Intent, bpc: bool) -> Option<Vec<f32>> {
|
||||
if dest.kind != self.kind || v.len() != self.channels() {
|
||||
return None;
|
||||
}
|
||||
let bpc = bpc && intent != Intent::AbsoluteColorimetric;
|
||||
let generation = profiles_generation();
|
||||
let key = (dest.id, generation, intent_index(intent), bpc);
|
||||
let t = {
|
||||
let mut cache = self.same_model.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.retain(|(k, _)| k.1 == generation);
|
||||
match cache.iter().find(|(k, _)| *k == key) {
|
||||
Some((_, t)) => t.clone(),
|
||||
None => {
|
||||
let t = self.build_same_model(dest, intent, bpc).map(Arc::new);
|
||||
cache.push((key, t.clone()));
|
||||
t
|
||||
}
|
||||
}
|
||||
}?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
t.into.transform(v, &mut lin).ok()?;
|
||||
let [from, to] = t.black;
|
||||
if from > 0.0 || to > 0.0 {
|
||||
lin = lin.map(|x| to + (x - from) * (1.0 - to) / (1.0 - from));
|
||||
}
|
||||
let lin = lin.map(|x| x.clamp(0.0, 1.0));
|
||||
let mut out = vec![0.0f32; dest.channels()];
|
||||
t.out_of.transform(&lin, &mut out).ok()?;
|
||||
Some(out.into_iter().map(|x| x.clamp(0.0, 1.0)).collect())
|
||||
}
|
||||
|
||||
fn build_same_model(&self, dest: &IccProfile, intent: Intent, bpc: bool) -> Option<SameModel> {
|
||||
let mut linear = rgb_space(super::PROPHOTO_RGB)?;
|
||||
for trc in [&mut linear.red_trc, &mut linear.green_trc, &mut linear.blue_trc] {
|
||||
*trc = Some(ToneReprCurve::Parametric(vec![1.0]));
|
||||
}
|
||||
linear.cicp = None;
|
||||
let into = self.profile.create_transform_f32(self.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
let out_of = linear.create_transform_f32(Layout::Rgb, &dest.profile, dest.layout(), Self::opts(intent)).ok()?;
|
||||
let black = if bpc {
|
||||
// Each profile's black: the darkest colour it reproduces, found as `build_direct`
|
||||
// finds it, as luminance in the linear space.
|
||||
let luminance = |p: &IccProfile, xf: &Arc<TransformF32Executor>| -> Option<f32> {
|
||||
let inks = p.from_srgb([0.0; 3], Intent::RelativeColorimetric)?;
|
||||
let mut lin = [0.0f32; 3];
|
||||
xf.transform(&inks, &mut lin).ok()?;
|
||||
let y = |c: &moxcms::Xyzd| c.y as f32;
|
||||
let lum = lin[0] * y(&linear.red_colorant) + lin[1] * y(&linear.green_colorant) + lin[2] * y(&linear.blue_colorant);
|
||||
Some(lum.clamp(0.0, 0.5))
|
||||
};
|
||||
let back = dest.profile.create_transform_f32(dest.layout(), &linear, Layout::Rgb, Self::opts(intent)).ok()?;
|
||||
[luminance(self, &into)?, luminance(dest, &back)?]
|
||||
} else {
|
||||
[0.0; 2]
|
||||
};
|
||||
Some(SameModel { into, out_of, black })
|
||||
}
|
||||
|
||||
/// Whether transforms can be built for this profile (checked at registration).
|
||||
pub fn usable(&self) -> bool {
|
||||
self.to_xf(Intent::RelativeColorimetric).is_some() && self.inverse_xf(Intent::RelativeColorimetric).is_some()
|
||||
|
||||
@@ -442,3 +442,39 @@ fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
let unknown = for_document(Some("no such profile"), Some(SRGB));
|
||||
assert_eq!(unknown.settings(), &working_settings(), "an unknown profile or one of the other model leaves the working space");
|
||||
}
|
||||
|
||||
/// The color management policies parse from their ids, Preserve Numbers is a CMYK policy only, and
|
||||
/// settings saved before the policies existed read with the default policy.
|
||||
#[test]
|
||||
fn policies_parse_and_default_in_saved_settings() {
|
||||
for p in Policy::CMYK {
|
||||
assert_eq!(Policy::parse(p.id()), Some(p));
|
||||
}
|
||||
assert_eq!(Policy::parse("bogus"), None);
|
||||
assert!(!Policy::RGB.contains(&Policy::PreserveNumbers));
|
||||
let old: ColorSettings =
|
||||
serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap();
|
||||
assert_eq!((old.rgb_policy, old.cmyk_policy), (Policy::PreserveEmbedded, Policy::PreserveEmbedded));
|
||||
let saved = serde_json::to_value(ColorSettings { cmyk_policy: Policy::PreserveNumbers, ..Default::default() }).unwrap();
|
||||
assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers")));
|
||||
}
|
||||
|
||||
/// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into
|
||||
/// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and
|
||||
/// Lab colors stay as they are.
|
||||
#[test]
|
||||
fn convert_into_keeps_the_appearance() {
|
||||
let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap();
|
||||
let working = cms();
|
||||
let rgb = Color::Rgb { r: 0.25, g: 0.4, b: 0.6 };
|
||||
let moved = wide.convert_into(&working, &rgb, Intent::RelativeColorimetric);
|
||||
assert_ne!(moved, rgb, "the numbers change");
|
||||
assert!(de(wide.display_rgb(&rgb), working.display_rgb(&moved)) < 1.0, "{rgb:?} → {moved:?}");
|
||||
let ink = Color::Cmyk { c: 0.2, m: 0.4, y: 0.6, k: 0.1 };
|
||||
let moved = wide.convert_into(&working, &ink, Intent::RelativeColorimetric);
|
||||
assert!(matches!(moved, Color::Cmyk { .. }) && moved != ink, "{ink:?} → {moved:?}");
|
||||
assert!(delta_e2000(wide.lab(&ink), working.lab(&moved)) < 3.0, "{ink:?} → {moved:?}");
|
||||
for c in [Color::Gray { k: 0.3 }, Color::Lab { l: 50.0, a: 10.0, b: -20.0 }] {
|
||||
assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,3 +274,55 @@ fn settings_built_before_a_reload_dont_leave_the_old_transform_to_the_new_ones()
|
||||
assert!(in_srgb.iter().zip(want).any(|(a, b)| (a - b).abs() > 0.05), "sRGB {in_srgb:?} vs ProPhoto {want:?}");
|
||||
assert!(in_prophoto.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {in_prophoto:?}, want {want:?}");
|
||||
}
|
||||
|
||||
/// A CMYK profile converts into another CMYK profile, ink for ink, and refuses a profile
|
||||
/// of another model or inks of the wrong count.
|
||||
#[test]
|
||||
fn cmyk_profiles_convert_into_each_other_directly() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let srgb = IccProfile::from_bytes(None, &icc_bytes(SRGB).unwrap()).unwrap();
|
||||
let inks = [0.2, 0.4, 0.6, 0.1];
|
||||
let out = generic.to_same_model_of(&device, &inks, Intent::RelativeColorimetric, false).unwrap();
|
||||
assert_eq!(out.len(), 4);
|
||||
assert!(out.iter().zip(inks).any(|(a, b)| (a - b).abs() > 0.01), "{out:?}");
|
||||
assert!(generic.to_same_model_of(&srgb, &inks, Intent::RelativeColorimetric, false).is_none());
|
||||
assert!(generic.to_same_model_of(&device, &inks[..3], Intent::RelativeColorimetric, false).is_none());
|
||||
}
|
||||
|
||||
/// With black-point compensation, a CMYK profile's darkest ink converts into an ink as dark as a
|
||||
/// darker profile's darkest ink, and a dark grey of a darker profile converts lighter into a
|
||||
/// profile whose black is lighter; absolute colorimetric never compensates.
|
||||
#[test]
|
||||
fn cmyk_to_cmyk_compensates_the_black_point() {
|
||||
let generic = IccProfile::from_bytes(Some("A".into()), &icc_bytes(GENERIC_CMYK).unwrap()).unwrap();
|
||||
let device = IccProfile::from_bytes(Some("B".into()), &icc_bytes(DEVICE_CMYK).unwrap()).unwrap();
|
||||
let rel = Intent::RelativeColorimetric;
|
||||
let lightness = |p: &IccProfile, inks: &[f32]| lab::srgb_to_lab(p.to_srgb(inks, rel).unwrap()).l;
|
||||
let black = |p: &IccProfile| p.from_srgb([0.0; 3], rel).unwrap();
|
||||
// Generic CMYK's black is a dark grey, the uncalibrated profile's is black.
|
||||
let (light, dark) = (lightness(&generic, &black(&generic)), lightness(&device, &black(&device)));
|
||||
assert!(light > dark + 5.0, "{light} vs {dark}");
|
||||
let into_device = |bpc| lightness(&device, &generic.to_same_model_of(&device, &black(&generic), rel, bpc).unwrap());
|
||||
let (on, off) = (into_device(true), into_device(false));
|
||||
assert!((on - dark).abs() < 1.5 && off > dark + 5.0, "with {on}, without {off}, the black {dark}");
|
||||
let grey = device.from_srgb([0.2; 3], rel).unwrap();
|
||||
let into_generic = |bpc| lightness(&generic, &device.to_same_model_of(&generic, &grey, rel, bpc).unwrap());
|
||||
let (on, off) = (into_generic(true), into_generic(false));
|
||||
assert!(on > off + 1.0, "with {on}, without {off}");
|
||||
for (from, to, inks) in [(&generic, &device, black(&generic)), (&device, &generic, grey)] {
|
||||
let abs = |bpc| from.to_same_model_of(to, &inks, Intent::AbsoluteColorimetric, bpc).unwrap();
|
||||
assert_eq!(abs(true), abs(false));
|
||||
}
|
||||
// Convert to Working Space (Cms::convert_into) compensates as Color Settings say.
|
||||
let device_name = register_icc(&icc_bytes(DEVICE_CMYK).unwrap(), Some("Test ICC Device CMYK".into())).unwrap().name;
|
||||
let rich = Color::Cmyk { c: 0.9, m: 0.8, y: 0.8, k: 1.0 };
|
||||
let convert = |bpc| {
|
||||
let dest = Cms::new(&ColorSettings { cmyk: device_name.clone(), bpc, ..ColorSettings::default() }).unwrap();
|
||||
icc_cmyk(bpc).convert_into(&dest, &rich, rel)
|
||||
};
|
||||
assert_ne!(convert(true), convert(false));
|
||||
// White is untouched.
|
||||
let white = generic.to_same_model_of(&device, &[0.0; 4], rel, true).unwrap();
|
||||
assert!(white.iter().all(|v| *v < 0.01), "{white:?}");
|
||||
}
|
||||
|
||||
@@ -525,8 +525,8 @@ fn planar<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -
|
||||
}
|
||||
|
||||
/// The samples of the `n` pixels of the TIFF `d` reads, `per` to a pixel (the number its color
|
||||
/// type has), pixel by pixel and 8 bits each (16-bit samples to their high byte), whether the file
|
||||
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// type has), pixel by pixel and 8 bits each (16-bit samples rounded to the nearest), whether the
|
||||
/// file stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// that many samples, which includes images whose planes together need more than the decoder's
|
||||
/// limit (256 MiB of samples), and, before any decoding, files with more than
|
||||
/// [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel, files whose samples aren't unsigned integers (a
|
||||
@@ -535,7 +535,7 @@ fn planar<R: std::io::Read + std::io::Seek>(d: &mut tiff::decoder::Decoder<R>) -
|
||||
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
Some(match read_samples_at_depth(d, n, per)? {
|
||||
Samples::Eight(v) => v,
|
||||
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
Samples::Sixteen(v) => v.iter().map(|&s| u8::try_from((u32::from(s) + 128) / 257).unwrap_or(u8::MAX)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+121
-63
@@ -504,7 +504,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// [`hit_test`] passing over the nodes `skip` names (and their contents), and with
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]).
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1055,9 +1055,17 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill),
|
||||
})
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => {
|
||||
NodeKind::Text(_) | NodeKind::PlacedDocument(_) => {
|
||||
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
|
||||
}
|
||||
// A symbol instance is hit within its bounds, and outside them where its art paints
|
||||
// ([`instance_art_hit`]).
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
|
||||
return Some(HitKind::Bounds);
|
||||
}
|
||||
instance_art_hit(n, p, opt, symbols)
|
||||
}
|
||||
// A blend or an envelope is hit within its bounds, and outside them where its evaluated
|
||||
// art paints: a blend's keys and steps on a spine can reach past the keys and the spine,
|
||||
// and the strokes of an envelope's distorted contents past its bounds.
|
||||
@@ -1211,64 +1219,94 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
|
||||
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
|
||||
if shaper_hides(n, i, None) {
|
||||
continue;
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole, outline) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
struct FindPart<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
/// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws
|
||||
/// them, and clipping paths are not picked by their outline.
|
||||
whole_instance: bool,
|
||||
}
|
||||
|
||||
impl FindPart<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> Option<HitKind> {
|
||||
self.art.place(n, whole).and_then(|n| hit_any(&n, self.p, opt, self.symbols))
|
||||
}
|
||||
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
|
||||
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
|
||||
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) {
|
||||
return None;
|
||||
}
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let clip = self.art.place_unclipped(first, whole)?;
|
||||
if !self.whole_instance
|
||||
&& self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& let Some(kind) = clip_outline(&clip, self.p, opt)
|
||||
{
|
||||
path.push(0);
|
||||
return Some(kind);
|
||||
}
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
// A Shaper group's original shapes are not drawn; symbol art has no isolation scope.
|
||||
if shaper_hides(n, i, None) {
|
||||
continue;
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if let Some(kind) = self.find(c, path, whole, outline) {
|
||||
return Some(kind);
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click at `p` hits of symbol instance `n`'s art where the canvas draws it (`None` in
|
||||
/// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a
|
||||
/// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a
|
||||
/// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past
|
||||
/// the 9-slice object limit ([`InstanceArt::of`]).
|
||||
fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
|
||||
if opt.outline || symbols.art(symbol).is_none() {
|
||||
return None;
|
||||
}
|
||||
let art = InstanceArt::of(symbols.document(), n)?;
|
||||
let opt = HitOptions { clip_outlines: false, ..opt };
|
||||
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
@@ -1435,7 +1473,8 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
|
||||
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
|
||||
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
|
||||
/// by their art ([`Node::geometric_bounds_with`]). The art of a clip group or of a layer with a
|
||||
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
|
||||
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
@@ -1573,14 +1612,33 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A box with no width or no height (an instance of a symbol that draws a straight
|
||||
// line) is touched where the marquee crosses it.
|
||||
_ => n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
|
||||
}),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art.
|
||||
NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
|
||||
/// a symbol that draws a straight line) is touched where the marquee crosses it.
|
||||
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
let crosses = (b.width() == 0.0 || b.height() == 0.0) && b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
b.intersect(r).area() > 0.0 || r.contains(b.origin()) || crosses
|
||||
})
|
||||
}
|
||||
/// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as
|
||||
/// it touches a group of that art? Only for art whose clipping paths have live geometry effects
|
||||
/// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach
|
||||
/// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
return false;
|
||||
}
|
||||
let Some(art) = InstanceArt::of(s.document(), n) else { return false };
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
|
||||
@@ -1852,6 +1852,115 @@ fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
|
||||
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
|
||||
}
|
||||
|
||||
/// A symbol instance whose art holds a clip group or a clipping layer with a live effect that moves
|
||||
/// its clipping path is clicked, and touched by a marquee, where the moved region shows the art past
|
||||
/// the art's box: inside a group, nested in another symbol's art, moved and scaled. In Outline view,
|
||||
/// below a layer whose Preview is off, where the art is hidden and where no region is left, only the
|
||||
/// box counts.
|
||||
#[test]
|
||||
fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
set_clip_region(moved_clip_region);
|
||||
// `effect` on the clipping path of a clip group (a clipping layer with `layer`), whose art is
|
||||
// shown when `shown`; `xf` places the instance, which with `nest` shows a symbol whose art holds
|
||||
// an instance of the clipped symbol. The instance is in a group: the group, the instance.
|
||||
let build = |effect: &str, xf: Affine, nest: bool, shown: bool, layer: bool| {
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, mut art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
|
||||
art.visible = shown;
|
||||
let mut clip = if layer {
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
*children = vec![Arc::new(mask), Arc::new(art)];
|
||||
}
|
||||
layer
|
||||
} else {
|
||||
Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)])
|
||||
};
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let mut symbol = "Clipped";
|
||||
if nest {
|
||||
let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: Affine::IDENTITY });
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(inner)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Outer".into(), art: Arc::new(root) });
|
||||
symbol = "Outer";
|
||||
}
|
||||
let (g, inst) = (d.alloc_id(), d.alloc_id());
|
||||
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: symbol.into(), xf });
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(instance)])).unwrap();
|
||||
(d, g, inst)
|
||||
};
|
||||
let opt = HitOptions::default();
|
||||
let outline = HitOptions { outline: true, ..opt };
|
||||
let at = |d: &Document, x: f64, y: f64, opt: HitOptions| hit_test(d, Point::new(x, y), opt).map(|h| h.leaf);
|
||||
// Across the art's top edge in the moved region, and past the art's right end.
|
||||
let (edge, past) = (Rect::new(140.0, -5.0, 160.0, 5.0), Rect::new(240.0, -5.0, 260.0, 5.0));
|
||||
for layer in [false, true] {
|
||||
let (d, g, inst) = build("test.move", Affine::IDENTITY, false, true, layer);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "in the moved region, layer {layer}");
|
||||
assert_eq!(hit_test(&d, Point::new(150.0, 50.0), opt).map(|h| h.top_object(None)), Some(g));
|
||||
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "in the box");
|
||||
assert_eq!(at(&d, 250.0, 50.0, opt), None, "past the art");
|
||||
assert_eq!(at(&d, 150.0, 150.0, opt), None, "below the art");
|
||||
assert_eq!(at(&d, 150.0, 50.0, outline), None, "Outline view draws the plain clipping path");
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
|
||||
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
|
||||
assert!(marquee(&d, past, None, false).is_empty());
|
||||
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
|
||||
}
|
||||
// Preview off for the layer the instance is on.
|
||||
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
|
||||
if let NodeKind::Layer { preview, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
|
||||
*preview = false;
|
||||
}
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), None, "Preview off");
|
||||
assert!(marquee(&d, edge, None, false).is_empty(), "Preview off");
|
||||
// Moved, scaled (the region moves 100 pt from the placed clipping path) and nested.
|
||||
let (d, _, inst) = build("test.move", Affine::translate((10.0, 20.0)), false, true, false);
|
||||
assert_eq!(at(&d, 160.0, 70.0, opt), Some(inst), "moved");
|
||||
let (d, _, inst) = build("test.move", Affine::scale(2.0), false, true, false);
|
||||
assert_eq!(at(&d, 250.0, 100.0, opt), Some(inst), "scaled");
|
||||
assert_eq!(at(&d, 350.0, 100.0, opt), None, "scaled, past the region");
|
||||
let (d, g, inst) = build("test.move", Affine::IDENTITY, true, true, false);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), Some(inst), "nested");
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "nested");
|
||||
// Hidden art, and an effect that leaves no region: clicks find only the box. The marquee still
|
||||
// touches the moved clipping path on the edge of its region, as in a clip group, unless no
|
||||
// region is left.
|
||||
for (effect, shown) in [("test.move", false), ("test.empty", true)] {
|
||||
let (d, g, inst) = build(effect, Affine::IDENTITY, false, shown, false);
|
||||
assert_eq!(at(&d, 150.0, 50.0, opt), None, "{effect}, shown {shown}");
|
||||
assert_eq!(at(&d, 50.0, 50.0, opt), Some(inst), "{effect}, shown {shown}: in the box");
|
||||
let touched: &[NodeId] = if shown { &[] } else { &[g] };
|
||||
assert_eq!(marquee(&d, edge, None, false), touched, "{effect}, shown {shown}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the stroke of a symbol's art where it paints past the instance's box selects the
|
||||
/// instance; past the stroke, and in Outline view, it does not.
|
||||
#[test]
|
||||
fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// A 20 pt stroke reaches 10 pt past the 0..100 square.
|
||||
let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0);
|
||||
let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look);
|
||||
let art = Node::group(d.alloc_id(), vec![Arc::new(square)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) });
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::IDENTITY;
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap();
|
||||
let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(108.0, HitOptions::default()), Some(inst), "on the stroke past the box");
|
||||
assert_eq!(at(50.0, HitOptions::default()), Some(inst), "in the box");
|
||||
assert_eq!(at(116.0, HitOptions::default()), None, "past the stroke");
|
||||
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
+34
-4
@@ -80,16 +80,22 @@ pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
|
||||
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
|
||||
pub type Link<'a> = Option<(&'a str, f32)>;
|
||||
|
||||
/// An ink amount clamped to 0..1; an amount that is not a finite number prints no ink.
|
||||
fn ink_amount(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate.
|
||||
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
|
||||
/// not a finite number prints no ink.
|
||||
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
|
||||
if let Some((REGISTRATION, tint)) = link {
|
||||
return Inks { cmyk: [tint.clamp(0.0, 1.0); 4], spot: None, registration: true };
|
||||
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
|
||||
}
|
||||
if let Some((name, tint)) = link
|
||||
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
|
||||
{
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), tint.clamp(0.0, 1.0))), registration: false };
|
||||
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
|
||||
}
|
||||
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
|
||||
}
|
||||
@@ -104,7 +110,7 @@ pub type StopPlates = Option<[f32; 4]>;
|
||||
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
|
||||
let mut ink = inks(doc, c, color, link, intent);
|
||||
if let (Some(p), Some(_)) = (plates, &ink.spot) {
|
||||
ink.cmyk = p.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
ink.cmyk = p.map(ink_amount);
|
||||
}
|
||||
ink
|
||||
}
|
||||
@@ -227,6 +233,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
|
||||
let d = gold_doc();
|
||||
let c = vectorcraft_color::cms::active();
|
||||
let look = Color::cmyk(0.25, 0.1, 0.8, 0.05);
|
||||
let ink = |link: Link| inks(&d, &c, &look, link, Intent::RelativeColorimetric);
|
||||
for t in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
|
||||
let spot = ink(Some(("Gold", t)));
|
||||
assert_eq!(spot, Inks { cmyk: [0.0; 4], spot: Some(("Gold".into(), 0.0)), registration: false }, "{t}");
|
||||
assert_eq!((spot.on_plate("Gold"), spot.on_plate("Cyan")), (0.0, 0.0), "{t}");
|
||||
let reg = ink(Some((REGISTRATION, t)));
|
||||
assert_eq!(reg, Inks { cmyk: [0.0; 4], spot: None, registration: true }, "{t}");
|
||||
assert_eq!((reg.on_plate("Gold"), reg.on_plate("Black")), (0.0, 0.0), "{t}");
|
||||
// A stop's process plates still print beside a spot tint that prints nothing.
|
||||
let stop = stop_inks(&d, &c, &look, Some(("Gold", t)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
|
||||
assert_eq!((stop.cmyk, stop.on_plate("Gold")), ([0.25, 0.0, 0.4, 0.0], 0.0), "{t}");
|
||||
}
|
||||
// Finite tints outside 0..1 are clamped.
|
||||
assert_eq!(ink(Some(("Gold", 2.0))).on_plate("Gold"), 1.0);
|
||||
assert_eq!(ink(Some(("Gold", -1.0))).on_plate("Gold"), 0.0);
|
||||
assert_eq!(ink(Some((REGISTRATION, 2.0))).cmyk, [1.0; 4]);
|
||||
assert_eq!(ink(Some((REGISTRATION, -1.0))).cmyk, [0.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_stops_pass_their_plates_and_freeform_points_are_visited() {
|
||||
let mut stop = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
|
||||
|
||||
@@ -128,7 +128,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
|
||||
@@ -105,8 +105,13 @@ impl Document {
|
||||
n += shared(&self.para_styles, &newer.para_styles, styles);
|
||||
n += shared(&self.composite_fonts, &newer.composite_fonts, |c| {
|
||||
let part = |p: &crate::CompositePart| p.font.capacity() + p.style.capacity();
|
||||
let custom = |f: &crate::CompositeFont| {
|
||||
vec_bytes(&f.custom) + f.custom.iter().map(|s| s.name.capacity() + s.characters.capacity() + part(&s.part)).sum::<usize>()
|
||||
};
|
||||
vec_bytes(c)
|
||||
+ c.iter().map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>()).sum::<usize>()
|
||||
+ c.iter()
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
|
||||
@@ -228,7 +228,11 @@ impl Node {
|
||||
/// grown by the farthest a stroke in the art can reach. For an instance placed through 9-slice
|
||||
/// guides, that box also holds the art box placed by each cell's map
|
||||
/// ([`crate::NineSliceMap::placement_bounds`]). An instance whose art holds an instance of a
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform.
|
||||
/// symbol with 9-slice guides at any depth is measured as its art placed by its transform. An
|
||||
/// instance whose art holds a clipping path with live geometry effects also takes in the region
|
||||
/// they give it ([`crate::hit::set_clip_region`]): moved with the instance when it only moves its
|
||||
/// art, otherwise placed by it and grown by as far as the region reaches past the art, times √2
|
||||
/// and the larger of 1 and the Frobenius norm of the transform's linear part.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
@@ -268,6 +272,30 @@ impl Node {
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
// The live geometry effects of the clipping paths in the art can draw it past its box.
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let Some((s, art, region)) = symbols.and_then(|s| {
|
||||
let a = s.art(symbol)?;
|
||||
Some((s, a, a.reshaped?))
|
||||
}) else {
|
||||
return self.visual(symbols);
|
||||
};
|
||||
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
|
||||
let placed = if moves_only(*xf) && map.is_none() {
|
||||
xf.transform_rect_bbox(region)
|
||||
} else {
|
||||
// An effect can reach a fixed distance past the art or a distance in proportion
|
||||
// to its size, as `SymbolBoxes::effects_reach` estimates it.
|
||||
let g = art.geometric;
|
||||
let all = region.union(g);
|
||||
let past = [g.x0 - region.x0, region.x1 - g.x1, g.y0 - region.y0, region.y1 - g.y1].into_iter().fold(0.0_f64, f64::max);
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let grow = past * std::f64::consts::SQRT_2 * (a * a + b * b + c * c + d * d).sqrt().max(1.0);
|
||||
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
|
||||
};
|
||||
let o = self.appearance.outset();
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,13 @@ pub struct Selection {
|
||||
/// it when no object is selected to align to it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_guide: Option<NodeId>,
|
||||
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
|
||||
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
|
||||
/// move the other selected points relative to it, and it stays in place. Never set with `key`
|
||||
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
|
||||
/// fewer than two points are selected.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub key_anchor: Option<(NodeId, AnchorRef)>,
|
||||
/// The new art on a locked artboard that this selection keeps editable
|
||||
/// ([`Document::new_art`]). Undo, Redo and a failed batch restore it with the selection, and
|
||||
/// the engine then sets the document's from it. Editing state, never saved.
|
||||
@@ -98,6 +105,7 @@ impl Selection {
|
||||
self.slices.clear();
|
||||
self.guides.clear();
|
||||
self.key_guide = None;
|
||||
self.key_anchor = None;
|
||||
self.symbol_part = None;
|
||||
self.on_path_member = None;
|
||||
}
|
||||
@@ -113,9 +121,15 @@ impl Selection {
|
||||
self.set([instance]);
|
||||
self.symbol_part = Some(SymbolPart { instance, path });
|
||||
}
|
||||
/// Is there a key for Align: an object or a guide?
|
||||
/// Is there a key for Align: an object, a guide or an anchor point?
|
||||
pub fn has_key(&self) -> bool {
|
||||
self.key.is_some() || self.key_guide.is_some()
|
||||
self.key.is_some() || self.key_guide.is_some() || self.key_anchor.is_some()
|
||||
}
|
||||
/// Where the key anchor ([`Self::key_anchor`]) is. `None` without one, or when the point is
|
||||
/// gone from its path.
|
||||
pub fn key_anchor_point(&self, doc: &Document) -> Option<vectorcraft_geom::Point> {
|
||||
let (id, (si, ai)) = self.key_anchor?;
|
||||
Some(doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.get(ai)?.p)
|
||||
}
|
||||
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.clear();
|
||||
@@ -143,6 +157,9 @@ impl Selection {
|
||||
if self.key == Some(id) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| k == id) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// [`Self::remove`] for each of `ids`, going through the selected objects once.
|
||||
pub fn remove_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
@@ -162,6 +179,9 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| ids.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| ids.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
|
||||
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
@@ -271,6 +291,40 @@ impl Selection {
|
||||
if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) {
|
||||
self.key_guide = None;
|
||||
}
|
||||
// A key anchor needs its point on its path and selected as an anchor point (not as a
|
||||
// selected segment's end), with another point selected too: another anchor, or a path
|
||||
// selected whole (Align and Distribute act on path points only). It takes the place of a
|
||||
// key object or key guide.
|
||||
let path_of = |o: &NodeId| found.get(o).and_then(|p| doc.node_at(p)).and_then(|n| n.path_data());
|
||||
let whole_path = |o: &NodeId| !self.anchors.contains_key(o) && path_of(o).is_some_and(|path| path.anchors().next().is_some());
|
||||
// Selected anchor points that are on their paths, counted up to two.
|
||||
let points = || {
|
||||
self.anchors
|
||||
.iter()
|
||||
.flat_map(|(o, set)| {
|
||||
let path = path_of(o);
|
||||
set.iter().filter(move |&&(si, ai)| path.is_some_and(|p| p.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())))
|
||||
})
|
||||
.take(2)
|
||||
.count()
|
||||
};
|
||||
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
|
||||
self.objects.contains(&id)
|
||||
&& !self.segments.contains_key(&id)
|
||||
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
|
||||
&& found
|
||||
.get(&id)
|
||||
.and_then(|p| doc.node_at(p))
|
||||
.and_then(|n| n.path_data())
|
||||
.is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len()))
|
||||
&& (points() >= 2 || self.objects.iter().any(whole_path))
|
||||
});
|
||||
if anchor_kept {
|
||||
self.key = None;
|
||||
self.key_guide = None;
|
||||
} else {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
// A selected part needs its instance selected alone, with no guides, its symbol dynamic
|
||||
// and the object still in the symbol's art as a path, compound path or type, where neither
|
||||
// it nor a group or layer around it is hidden, locked or a template.
|
||||
@@ -348,6 +402,9 @@ impl Selection {
|
||||
if self.key.is_some_and(|k| gone.contains(&k)) {
|
||||
self.key = None;
|
||||
}
|
||||
if self.key_anchor.is_some_and(|(k, _)| gone.contains(&k)) {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Target `id` (see [`Selection::target`]): a layer gets its visible, unlocked art selected
|
||||
/// (the art of its sublayers too), anything else is selected itself.
|
||||
|
||||
@@ -47,6 +47,11 @@ pub(crate) struct ArtBox {
|
||||
/// Whether the art holds an instance of a symbol with 9-slice guides, or of a symbol whose art
|
||||
/// holds one at any depth.
|
||||
pub(crate) sliced: bool,
|
||||
/// The box of the regions that the live geometry effects of the clipping paths in the art give
|
||||
/// them ([`crate::hit::set_clip_region`]), and of the instances in the art whose art has such
|
||||
/// regions, each measured by [`Node::reach_bounds_with`]. `None` when nothing in the art has
|
||||
/// one.
|
||||
pub(crate) reshaped: Option<Rect>,
|
||||
}
|
||||
|
||||
/// The art boxes of a document's symbols, which [`Node::geometric_bounds_with`],
|
||||
@@ -562,7 +567,18 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
|
||||
sliced |= symbols.doc.symbol_nine_slice(symbol).is_some() || symbols.art(symbol).is_some_and(|a| a.sliced);
|
||||
}
|
||||
});
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced })
|
||||
let mut reshaped = None;
|
||||
if effects {
|
||||
art.walk(&mut |n| {
|
||||
let b = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } if symbols.art(symbol).is_some_and(|a| a.reshaped.is_some()) => n.reach(Some(symbols)),
|
||||
_ if n.clips() => n.children().and_then(|c| c.first()).and_then(|c| crate::hit::reshaped_clip_box(c)),
|
||||
_ => None,
|
||||
};
|
||||
reshaped = vectorcraft_geom::union_opt(reshaped, b.filter(finite));
|
||||
});
|
||||
}
|
||||
Some(ArtBox { geometric, visual, reach, effects, brush, sliced, reshaped })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -22,8 +22,8 @@ pub use char_style::{
|
||||
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
CompositeParts,
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! Type › Composite Fonts…: a font made of other fonts, one for each class of character (the
|
||||
//! Kanji font is the base; kana, punctuation, symbols, Roman letters and numerals each take a font
|
||||
//! of their own, sized, raised and scaled against it). Type set in a composite font names it as its
|
||||
//! family; the layout sets each character in its class's font.
|
||||
//! of their own, sized, raised and scaled against it). Custom character sets give characters the
|
||||
//! user picks a font of their own too, ahead of their class; of two sets that list a character,
|
||||
//! the later one sets it. Type set in a composite font names it as its family; the layout sets each
|
||||
//! character in its set's or its class's font.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! Which characters fall in which class, the ranges and the defaults are VectorCraft's own.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
//! Which characters fall in which class, the ranges, the limits and the defaults are VectorCraft's
|
||||
//! own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -179,12 +184,76 @@ impl CompositeParts {
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom character set of a composite font: characters chosen by the user, set in a part of
|
||||
/// their own instead of their class's part.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CustomCharSet {
|
||||
/// The set's name, unique in its composite font in any case.
|
||||
pub name: String,
|
||||
/// The set's characters, each once, in the order they were added.
|
||||
#[serde(default)]
|
||||
pub characters: String,
|
||||
/// The font, style, size, baseline and scales its characters take.
|
||||
#[serde(flatten)]
|
||||
pub part: CompositePart,
|
||||
}
|
||||
|
||||
impl CustomCharSet {
|
||||
/// An empty set named `name`, its characters set in `part`.
|
||||
pub fn new(name: impl Into<String>, part: CompositePart) -> Self {
|
||||
Self { name: name.into(), characters: String::new(), part }
|
||||
}
|
||||
|
||||
/// Whether `c` can be in a custom character set: not a control character, and in the Basic
|
||||
/// Multilingual Plane (U+0000 to U+FFFF).
|
||||
pub fn takes(c: char) -> bool {
|
||||
!c.is_control() && (c as u32) <= 0xFFFF
|
||||
}
|
||||
|
||||
/// The character a Unicode code names: hexadecimal digits, optionally after `U+` or `0x`
|
||||
/// (`3042`, `U+3042`). `None` for anything else or a code [`Self::takes`] refuses.
|
||||
pub fn char_from_code(code: &str) -> Option<char> {
|
||||
let code = code.trim();
|
||||
let hex = ["U+", "u+", "0x", "0X"].iter().find_map(|p| code.strip_prefix(p)).unwrap_or(code);
|
||||
if hex.is_empty() || hex.len() > 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|&c| Self::takes(c))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a composite font sets a character: the part of one of its six classes, or the part of
|
||||
/// one of its custom character sets (an index into [`CompositeFont::custom`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum CompositeClass {
|
||||
Fixed(CharClass),
|
||||
Custom(usize),
|
||||
}
|
||||
|
||||
/// The custom character set each character of a composite font's sets falls in
|
||||
/// ([`CompositeFont::classes`]): the last set that lists it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CompositeClasses {
|
||||
custom: std::collections::HashMap<char, usize>,
|
||||
}
|
||||
|
||||
impl CompositeClasses {
|
||||
/// Where the composite font sets `c`: the last custom set that lists it, else its class.
|
||||
pub fn of(&self, c: char) -> CompositeClass {
|
||||
self.custom.get(&c).map_or(CompositeClass::Fixed(CharClass::of(c)), |&i| CompositeClass::Custom(i))
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite font (Type › Composite Fonts…), saved with the document. Its name is the family
|
||||
/// that type set in it names.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CompositeFont {
|
||||
pub name: String,
|
||||
pub parts: CompositeParts,
|
||||
/// Custom character sets, checked before the classes. A character two sets list is set in the
|
||||
/// later set's part.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub custom: Vec<CustomCharSet>,
|
||||
}
|
||||
|
||||
/// The size a part can take, in percent of the type's size.
|
||||
@@ -197,11 +266,40 @@ pub const COMPOSITE_SCALE: std::ops::RangeInclusive<f64> = 10.0..=400.0;
|
||||
pub const COMPOSITE_NAME_MAX: usize = 255;
|
||||
/// The most composite fonts a document or a file keeps.
|
||||
pub const COMPOSITE_FONTS_MAX: usize = 256;
|
||||
/// The most custom character sets a composite font keeps.
|
||||
pub const CUSTOM_SETS_MAX: usize = 64;
|
||||
/// The most characters a custom character set keeps.
|
||||
pub const CUSTOM_CHARS_MAX: usize = 8192;
|
||||
|
||||
impl CompositeFont {
|
||||
/// A composite font named `name` setting every class in `font` and `style`.
|
||||
pub fn new(name: impl Into<String>, font: impl Into<String>, style: impl Into<String>) -> Self {
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)) }
|
||||
Self { name: name.into(), parts: CompositeParts::all(CompositePart::new(font, style)), custom: Vec::new() }
|
||||
}
|
||||
|
||||
/// The part that sets the characters of `class`, `None` for a custom set the font doesn't have.
|
||||
pub fn part(&self, class: CompositeClass) -> Option<&CompositePart> {
|
||||
match class {
|
||||
CompositeClass::Fixed(c) => Some(self.parts.get(c)),
|
||||
CompositeClass::Custom(i) => self.custom.get(i).map(|s| &s.part),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where this font sets character `c`: the last custom set that lists it, else its class. For
|
||||
/// many characters, [`Self::classes`] looks each up faster.
|
||||
pub fn class_of(&self, c: char) -> CompositeClass {
|
||||
self.custom.iter().rposition(|s| s.characters.contains(c)).map_or(CompositeClass::Fixed(CharClass::of(c)), CompositeClass::Custom)
|
||||
}
|
||||
|
||||
/// The custom set each character of this font's sets falls in, to look up many characters.
|
||||
pub fn classes(&self) -> CompositeClasses {
|
||||
let mut custom = std::collections::HashMap::new();
|
||||
for (i, s) in self.custom.iter().enumerate() {
|
||||
for c in s.characters.chars() {
|
||||
custom.insert(c, i);
|
||||
}
|
||||
}
|
||||
CompositeClasses { custom }
|
||||
}
|
||||
|
||||
/// Do `a` and `b` name the same composite font: equal in any case?
|
||||
@@ -223,36 +321,50 @@ impl CompositeFont {
|
||||
}
|
||||
|
||||
/// Why this composite font can't be used, if it can't: a name [`Self::clean_name`] refuses, a
|
||||
/// part without a font, a value out of its range, or a scale or Scale at Center on a class
|
||||
/// that has none.
|
||||
/// part without a font, a value out of its range, a scale or Scale at Center on a class that
|
||||
/// has none, or a custom character set [`Self::check_custom`] refuses.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!("`{}` can't name a composite font", self.name));
|
||||
}
|
||||
for class in CharClass::ALL {
|
||||
let p = self.parts.get(class);
|
||||
let k = class.key();
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
check_part(self.parts.get(class), class.key(), class.scales(), class == CharClass::Kana)?;
|
||||
}
|
||||
self.check_custom()
|
||||
}
|
||||
|
||||
/// Why this font's custom character sets can't be used, if they can't: more than
|
||||
/// [`CUSTOM_SETS_MAX`], a name [`Self::clean_name`] refuses or two sets share (in any case), a
|
||||
/// character [`CustomCharSet::takes`] refuses or a set lists twice, more than
|
||||
/// [`CUSTOM_CHARS_MAX`] characters in a set, or a part [`Self::check`] would refuse. A set's
|
||||
/// characters can be scaled across and up; only kana are scaled at the center.
|
||||
pub fn check_custom(&self) -> Result<(), String> {
|
||||
if self.custom.len() > CUSTOM_SETS_MAX {
|
||||
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for s in &self.custom {
|
||||
let name = &s.name;
|
||||
if Self::clean_name(name).as_deref() != Some(name.as_str()) {
|
||||
return Err(format!("`{name}` can't name a character set"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
if !names.insert(name.to_lowercase()) {
|
||||
return Err(format!("two character sets are named `{name}`"));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (n, c) in s.characters.chars().enumerate() {
|
||||
if n == CUSTOM_CHARS_MAX {
|
||||
return Err(format!("`{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters"));
|
||||
}
|
||||
if v != 100.0 && !class.scales() {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
let code = c as u32;
|
||||
if !CustomCharSet::takes(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is a control character or past U+FFFF"));
|
||||
}
|
||||
if !seen.insert(c) {
|
||||
return Err(format!("`{name}`: U+{code:04X} is listed twice"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && class != CharClass::Kana {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
check_part(&s.part, name, true, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -264,9 +376,41 @@ impl CompositeFont {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
let mut kept: Vec<CompositeFont> =
|
||||
fonts.iter().filter(|f| f.check().is_ok() && names.insert(f.name.to_lowercase())).take(COMPOSITE_FONTS_MAX).cloned().collect();
|
||||
kept.retain(|f| CharClass::ALL.iter().all(|&c| !names.contains(&f.parts.get(c).font.to_lowercase())));
|
||||
kept.retain(|f| f.part_fonts().all(|font| !names.contains(&font.to_lowercase())));
|
||||
(kept.len() != fonts.len()).then_some(kept)
|
||||
}
|
||||
|
||||
/// The fonts of the parts, each class's then each custom set's.
|
||||
pub fn part_fonts(&self) -> impl Iterator<Item = &str> {
|
||||
CharClass::ALL.into_iter().map(|c| self.parts.get(c).font.as_str()).chain(self.custom.iter().map(|s| s.part.font.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why part `p` (of the class or set named `k`) can't be used, if it can't: no font, a value out
|
||||
/// of its range, a scale when `scales` is false, or Scale at Center when `center` is false.
|
||||
fn check_part(p: &CompositePart, k: &str, scales: bool, center: bool) -> Result<(), String> {
|
||||
if p.font.trim().is_empty() {
|
||||
return Err(format!("{k}: give a font"));
|
||||
}
|
||||
let within = |v: f64, r: &std::ops::RangeInclusive<f64>| v.is_finite() && r.contains(&v);
|
||||
if !within(p.size, &COMPOSITE_SIZE) {
|
||||
return Err(format!("{k}: size must be {} to {}%", COMPOSITE_SIZE.start(), COMPOSITE_SIZE.end()));
|
||||
}
|
||||
if !within(p.baseline, &COMPOSITE_BASELINE) {
|
||||
return Err(format!("{k}: baseline must be {} to {}%", COMPOSITE_BASELINE.start(), COMPOSITE_BASELINE.end()));
|
||||
}
|
||||
for v in [p.h_scale, p.v_scale] {
|
||||
if !within(v, &COMPOSITE_SCALE) {
|
||||
return Err(format!("{k}: scale must be {} to {}%", COMPOSITE_SCALE.start(), COMPOSITE_SCALE.end()));
|
||||
}
|
||||
if v != 100.0 && !scales {
|
||||
return Err(format!("{k}: only kana, roman and numerals can be scaled"));
|
||||
}
|
||||
}
|
||||
if p.scale_at_center && !center {
|
||||
return Err(format!("{k}: only kana can be scaled at the center"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -341,4 +485,81 @@ mod tests {
|
||||
spaced.name = " Mixed".into();
|
||||
assert!(spaced.check().is_err());
|
||||
}
|
||||
|
||||
/// A character a custom set lists falls in that set ahead of its class, the later of two sets
|
||||
/// that list it wins, and the quick lookup agrees with the one-character one.
|
||||
#[test]
|
||||
fn custom_sets_take_their_characters_before_the_classes() {
|
||||
let mut f = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let mut a = CustomCharSet::new("Marks", CompositePart::new("Source Sans 3", "Bold"));
|
||||
a.characters = "※A".into();
|
||||
let mut b = CustomCharSet::new("Letters", CompositePart::new("Inter", "Italic"));
|
||||
b.characters = "AB".into();
|
||||
f.custom = vec![a, b];
|
||||
let classes = f.classes();
|
||||
for (c, want) in [
|
||||
('※', CompositeClass::Custom(0)),
|
||||
('A', CompositeClass::Custom(1)),
|
||||
('B', CompositeClass::Custom(1)),
|
||||
('C', CompositeClass::Fixed(CharClass::Roman)),
|
||||
('漢', CompositeClass::Fixed(CharClass::Kanji)),
|
||||
] {
|
||||
assert_eq!(f.class_of(c), want, "{c:?}");
|
||||
assert_eq!(classes.of(c), want, "{c:?}");
|
||||
}
|
||||
assert_eq!(f.part(CompositeClass::Custom(0)).map(|p| p.style.as_str()), Some("Bold"));
|
||||
assert_eq!(f.part(CompositeClass::Custom(2)), None);
|
||||
assert_eq!(f.check(), Ok(()));
|
||||
// Read and written with the part's fields beside the set's name and characters.
|
||||
let json = serde_json::to_value(&f).unwrap();
|
||||
assert_eq!(json["custom"][1]["characters"], "AB");
|
||||
assert_eq!(json["custom"][1]["style"], "Italic");
|
||||
assert_eq!(serde_json::from_value::<CompositeFont>(json).unwrap(), f);
|
||||
// A font without sets is written as before.
|
||||
assert!(serde_json::to_value(CompositeFont::new("Plain", "Inter", "Regular")).unwrap().get("custom").is_none());
|
||||
}
|
||||
|
||||
/// Set names, characters and limits are checked; sets scale like Roman letters.
|
||||
#[test]
|
||||
fn custom_sets_check_their_names_and_characters() {
|
||||
let ok = CompositeFont::new("Mixed", "Inter", "Regular");
|
||||
let with = |sets: Vec<(&str, &str)>, edit: fn(&mut CompositePart)| {
|
||||
let mut f = ok.clone();
|
||||
for (name, chars) in sets {
|
||||
let mut s = CustomCharSet::new(name, CompositePart::new("Inter", "Regular"));
|
||||
s.characters = chars.into();
|
||||
edit(&mut s.part);
|
||||
f.custom.push(s);
|
||||
}
|
||||
f.check()
|
||||
};
|
||||
let none = |_: &mut CompositePart| {};
|
||||
assert_eq!(with(vec![("Empty", "")], none), Ok(()));
|
||||
assert_eq!(with(vec![("Wide", "AB")], |p| p.h_scale = 80.0), Ok(()));
|
||||
assert!(with(vec![("Wide", "AB")], |p| p.scale_at_center = true).is_err());
|
||||
assert!(with(vec![("Big", "A")], |p| p.size = 401.0).is_err());
|
||||
assert!(with(vec![("Same", "A"), ("same", "B")], none).unwrap_err().contains("two character sets"));
|
||||
assert!(with(vec![(" Pad", "A")], none).is_err());
|
||||
assert!(with(vec![("Twice", "ABA")], none).unwrap_err().contains("U+0041 is listed twice"));
|
||||
assert!(with(vec![("Tab", "A\t")], none).unwrap_err().contains("U+0009"));
|
||||
assert!(with(vec![("Astral", "𠀋")], none).unwrap_err().contains("U+2000B"));
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(CUSTOM_CHARS_MAX + 1).collect();
|
||||
let mut f = ok.clone();
|
||||
f.custom.push(CustomCharSet { name: "Many".into(), characters: many, part: CompositePart::new("Inter", "Regular") });
|
||||
assert!(f.check().unwrap_err().contains("at most"));
|
||||
let mut f = ok.clone();
|
||||
f.custom = (0..=CUSTOM_SETS_MAX).map(|i| CustomCharSet::new(format!("S{i}"), CompositePart::new("Inter", "Regular"))).collect();
|
||||
assert!(f.check().is_err());
|
||||
}
|
||||
|
||||
/// Codes are hexadecimal, with or without `U+` or `0x`, inside the Basic Multilingual Plane.
|
||||
#[test]
|
||||
fn custom_set_codes_name_characters() {
|
||||
assert_eq!(CustomCharSet::char_from_code("3042"), Some('あ'));
|
||||
assert_eq!(CustomCharSet::char_from_code(" U+203B "), Some('※'));
|
||||
assert_eq!(CustomCharSet::char_from_code("0x41"), Some('A'));
|
||||
for bad in ["", "U+", "zz", "20000B", "D800", "0009", "1F600", "1234567", "+41"] {
|
||||
assert_eq!(CustomCharSet::char_from_code(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,22 +210,22 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
CLASSIC_EXTRUDE,
|
||||
"Extrude & Bevel (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","drawHiddenFaces":false}),
|
||||
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
|
||||
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_REVOLVE,
|
||||
"Revolve (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
|
||||
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_ROTATE,
|
||||
"Rotate (Classic)…",
|
||||
&["Effect", "3D and Materials", "3D (Classic)"],
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000"}),
|
||||
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
|
||||
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
|
||||
),
|
||||
g(
|
||||
"convertToShape.rectangle",
|
||||
|
||||
+30
-45
@@ -742,45 +742,28 @@ fn item_art(id: NodeId, item: &AppearanceItem, shapes: &[(PathData, FillRule)],
|
||||
}
|
||||
|
||||
/// The members of a container that [`take_held_guides`] visits, by index, each with the same for
|
||||
/// its own members. A ruler guide's entry is empty; a container's is not.
|
||||
/// its own members. A ruler guide's entry is empty, whether its container is a layer or a group; a
|
||||
/// container's is not.
|
||||
#[derive(Default)]
|
||||
struct HeldGuides(Vec<(usize, HeldGuides)>);
|
||||
|
||||
/// The members of `n` holding or leading to the ruler guides of sublayers, found by looking at each
|
||||
/// member at every depth once: the ruler guides (`is_guide`) of `n` when it is a layer, each
|
||||
/// sublayer holding one directly or in its sublayers, and each member of another kind with such a
|
||||
/// sublayer among its members or its groups' members. With them, whether `n` is a layer holding a
|
||||
/// ruler guide directly or in its sublayers. The other members of a layer holding none are not
|
||||
/// looked into, unless the layer is the one whose sublayers are gathered (`top`).
|
||||
fn held_guides(n: &Node, top: bool, is_guide: &impl Fn(&Node) -> bool) -> (bool, HeldGuides) {
|
||||
let layer = n.is_layer();
|
||||
let (mut holds, mut held, mut other) = (false, vec![], vec![]);
|
||||
/// The members of `n` that are ruler guides (`is_guide`), and those holding one at any depth, in
|
||||
/// order. Every member at every depth is looked at once: a sublayer or group with no guide of its
|
||||
/// own is still looked into, and a guide directly in a group counts as one in a layer does. A
|
||||
/// member holding no guide gets no entry.
|
||||
fn held_guides(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> HeldGuides {
|
||||
let mut held = vec![];
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
if is_guide(c) {
|
||||
if layer {
|
||||
holds = true;
|
||||
held.push((i, HeldGuides::default()));
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
let (sub_holds, inner) = held_guides(c, false, is_guide);
|
||||
if sub_holds {
|
||||
holds = true;
|
||||
held.push((i, inner));
|
||||
}
|
||||
} else {
|
||||
other.push((i, c));
|
||||
held.push((i, HeldGuides::default()));
|
||||
continue;
|
||||
}
|
||||
let inner = held_guides(c, is_guide);
|
||||
if !inner.0.is_empty() {
|
||||
held.push((i, inner));
|
||||
}
|
||||
}
|
||||
if !layer || holds || top {
|
||||
for (i, c) in other {
|
||||
let (_, inner) = held_guides(c, false, is_guide);
|
||||
if !inner.0.is_empty() {
|
||||
held.push((i, inner));
|
||||
}
|
||||
}
|
||||
held.sort_unstable_by_key(|(i, _)| *i);
|
||||
}
|
||||
(layer && holds, HeldGuides(held))
|
||||
HeldGuides(held)
|
||||
}
|
||||
|
||||
/// Move the ruler guides of `n` and of its members that [`held_guides`] found (`held`) to `out`:
|
||||
@@ -818,15 +801,14 @@ fn take_held_guides(n: &mut Node, held: HeldGuides, out: &mut Vec<Arc<Node>>, hi
|
||||
out.append(&mut deeper);
|
||||
}
|
||||
|
||||
/// Move the ruler guides of the sublayers among the members of `n`, and among its groups'
|
||||
/// members, to `out`, in order: a sublayer's own guides, then those of its members. A guide taken
|
||||
/// from a hidden or locked sublayer, or from one inside such a sublayer or group, is hidden or
|
||||
/// locked itself. Each member at every depth is looked at once at most (`is_guide`), and only
|
||||
/// containers holding one are copied.
|
||||
/// Move the ruler guides of `n` and those held at any depth by the sublayers and groups among its
|
||||
/// members to `out`, in order: a container's own guides, then those of its members. A sublayer or
|
||||
/// group with no guide of its own still gives up those of its members. A guide taken from a hidden
|
||||
/// or locked sublayer or group, or from one inside such a container, is hidden or locked itself.
|
||||
/// Each member at every depth is looked at once (`is_guide`), and only containers holding a guide
|
||||
/// are copied.
|
||||
fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl Fn(&Node) -> bool) {
|
||||
let (_, mut held) = held_guides(n, true, is_guide);
|
||||
// The ruler guides of `n` itself stay where they are.
|
||||
held.0.retain(|(_, inner)| !inner.0.is_empty());
|
||||
let held = held_guides(n, is_guide);
|
||||
take_held_guides(n, held, out, false, false);
|
||||
}
|
||||
|
||||
@@ -850,12 +832,15 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
return None;
|
||||
}
|
||||
let mut m = n.clone();
|
||||
// A layer's ruler guides take no part: they go back above the evaluated art at the end.
|
||||
let mut guides = m.children_mut().map(|ch| ch.split_off(Node::guide_run_start(ch))).unwrap_or_default();
|
||||
// So do its sublayers' guides, which would otherwise go with the art the effects replace or
|
||||
// copy: they stay on this layer, hidden and locked as their sublayers were.
|
||||
if m.is_layer() && (pathfinder || !fx.is_empty()) {
|
||||
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
|
||||
// that replace or copy the art, so do its guides among the art and those in its sublayers and
|
||||
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
|
||||
// locked as their containers were.
|
||||
let mut guides = vec![];
|
||||
if pathfinder || !fx.is_empty() {
|
||||
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
|
||||
} else if let Some(ch) = m.children_mut() {
|
||||
guides = ch.split_off(Node::guide_run_start(ch));
|
||||
}
|
||||
if pathfinder {
|
||||
let hook = |c: &Node| crate::outline_object(doc, c);
|
||||
|
||||
@@ -1808,7 +1808,7 @@ fn a_sublayers_ruler_guide_in_a_hidden_or_locked_group_stays_hidden_or_locked()
|
||||
}
|
||||
|
||||
/// Gathering the ruler guides of nested sublayers, and of a sublayer inside nested groups, looks
|
||||
/// at each member at every depth once at most, and takes the same guides, in the same order and
|
||||
/// at each member at every depth once, and takes the same guides, in the same order and
|
||||
/// state, as a layer's effects keep.
|
||||
#[test]
|
||||
fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
@@ -1840,7 +1840,7 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
groups.locked = depth == 3;
|
||||
}
|
||||
let free = Arc::new(Node::group(NodeId(500), vec![sq(501, 0.0, Color::BLACK), sq(502, 5.0, Color::BLACK)]));
|
||||
// A sublayer with no guide: the art in its group is not looked at.
|
||||
// A sublayer with no guide, its group holding none either.
|
||||
let quiet = Node::group(NodeId(601), vec![sq(602, 0.0, Color::BLACK), sq(603, 5.0, Color::BLACK)]);
|
||||
let quiet = Arc::new(layer(600, vec![Arc::new(quiet)]));
|
||||
let mut root = layer(10, vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(chain), Arc::new(groups), free.clone(), quiet.clone(), guide(20)]);
|
||||
@@ -1858,15 +1858,16 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
};
|
||||
let mut taken = vec![];
|
||||
take_sublayer_guides(&mut m, &mut taken, &is_guide);
|
||||
assert_eq!(looked.get(), members(&root) - 2, "each member is looked at once, none in the quiet sublayer's group");
|
||||
assert_eq!(state(&taken), expected, "a sublayer's own guides, then its sublayers', each once");
|
||||
assert!(Arc::ptr_eq(&taken[0], &first_guide), "a guide with nothing to change is not copied");
|
||||
assert!(!Arc::ptr_eq(&taken[1], &second_guide), "a guide made hidden is copied");
|
||||
assert_eq!(looked.get(), members(&root), "each member is looked at once, those of guide-free containers included");
|
||||
assert_eq!(taken[0].id, NodeId(20), "the layer's own guide comes first");
|
||||
assert_eq!(state(&taken[1..]), expected, "a sublayer's own guides, then its sublayers', each once");
|
||||
assert!(Arc::ptr_eq(&taken[1], &first_guide), "a guide with nothing to change is not copied");
|
||||
assert!(!Arc::ptr_eq(&taken[2], &second_guide), "a guide made hidden is copied");
|
||||
assert!(second_guide.visible, "the guide as it was stays as it was");
|
||||
let ch = m.children().unwrap();
|
||||
assert_eq!(ch.len(), 5, "the layer's own guide is taken");
|
||||
assert!(Arc::ptr_eq(&ch[3], &free), "a member with no sublayer guide is not copied");
|
||||
assert!(Arc::ptr_eq(&ch[4], &quiet), "a sublayer with no guide is not copied");
|
||||
assert!(ch[5].is_ruler_guide(), "the layer's own guide stays where it is");
|
||||
let ids = |n: &Node| n.children().into_iter().flatten().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&ch[1]), [NodeId(102), NodeId(301)], "the sublayer's art stays, in order");
|
||||
assert_eq!(ids(&root.children().unwrap()[1]), [NodeId(102), NodeId(301), NodeId(201)], "the source keeps its guides");
|
||||
@@ -1892,6 +1893,140 @@ fn gathering_sublayer_ruler_guides_looks_at_each_member_once() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where each ruler guide in `n` is, at every depth, with its position, visibility and lock.
|
||||
fn ruler_guides_in(n: &Node, out: &mut Vec<(NodeId, NodeKind, bool, bool)>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_ruler_guide() {
|
||||
out.push((c.id, c.kind.clone(), c.visible, c.locked));
|
||||
}
|
||||
ruler_guides_in(c, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// A ruler guide in a layer inside a group inside a sublayer that holds no guide of its own, at
|
||||
/// any depth of that pattern, survives its layer's Pathfinder effect or Transform copies once, last
|
||||
/// in the layer, hidden or locked when any container on its way was.
|
||||
#[test]
|
||||
fn a_ruler_guide_below_a_guide_free_sublayer_and_a_group_survives_its_layers_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let layer = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
|
||||
let mut l = Node::layer(NodeId(id), "Sub", LayerColor::Preset(1));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
(l.visible, l.locked) = (!hidden, locked);
|
||||
Arc::new(l)
|
||||
};
|
||||
let group = |id, children: Vec<Arc<Node>>, (hidden, locked): (bool, bool)| {
|
||||
let mut g = Node::group(NodeId(id), children);
|
||||
(g.visible, g.locked) = (!hidden, locked);
|
||||
Arc::new(g)
|
||||
};
|
||||
let kind = NodeKind::RulerGuide { vertical: false, pos: 7.0, artboard: None };
|
||||
let states = [(false, false), (true, false), (false, true)];
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
for depth in 1..=3_u64 {
|
||||
for sub in states {
|
||||
for grp in states {
|
||||
for inner in states {
|
||||
// Layer 10 → sublayer → group → … → layer holding the guide, the pattern
|
||||
// repeated `depth` times; only the innermost layer holds a guide.
|
||||
let mut n = layer(900, vec![sq(901, 0.0, Color::BLACK), Arc::new(Node::new(NodeId(20), kind.clone()))], inner);
|
||||
for d in (0..depth).rev() {
|
||||
let (s, g) = if d == 0 { (sub, grp) } else { ((false, false), (false, false)) };
|
||||
n = group(700 + d, vec![sq(710 + d, 5.0, Color::BLACK), n], g);
|
||||
n = layer(800 + d, vec![n, sq(810 + d, 2.0, Color::BLACK)], s);
|
||||
}
|
||||
let mut root = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = root.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), n];
|
||||
}
|
||||
root.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
|
||||
let art = evaluate_container(None, &root).unwrap();
|
||||
let (hidden, locked) = (sub.0 || grp.0 || inner.0, sub.1 || grp.1 || inner.1);
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let case = format!("{effect}, depth {depth}, sublayer {sub:?}, group {grp:?}, layer {inner:?}");
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
|
||||
let last = art.children().and_then(|c| c.last()).unwrap();
|
||||
assert_eq!(last.id, NodeId(20), "{case}: last in the layer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A ruler guide directly in a group, in a layer or in a group with a Pathfinder effect or
|
||||
/// Transform copies, survives that effect once, last in the container, hidden or locked as its
|
||||
/// groups were. So does one among a group's art rather than after it.
|
||||
#[test]
|
||||
fn a_ruler_guide_in_a_group_survives_its_containers_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let kind = NodeKind::RulerGuide { vertical: true, pos: 4.0, artboard: None };
|
||||
let guide = || Arc::new(Node::new(NodeId(20), kind.clone()));
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
for (hidden, locked) in [(false, false), (true, false), (false, true)] {
|
||||
let mut inner = Node::group(NodeId(12), vec![sq(2, 5.0, Color::BLACK), guide(), sq(3, 8.0, Color::BLACK)]);
|
||||
(inner.visible, inner.locked) = (!hidden, locked);
|
||||
let outer = Arc::new(Node::group(NodeId(11), vec![Arc::new(inner)]));
|
||||
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer.clone()];
|
||||
}
|
||||
l.appearance.effects.push(fx.clone());
|
||||
let mut g = Node::group(NodeId(13), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), outer]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
for (what, n) in [("layer", l), ("group", g)] {
|
||||
let art = evaluate_container(None, &n).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let case = format!("{effect} on a {what}, hidden {hidden}, locked {locked}");
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), !hidden, locked)], "{case}: the guide, once, unchanged");
|
||||
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{case}: last");
|
||||
}
|
||||
}
|
||||
// A group's guide placed before its art.
|
||||
let mut g = Node::group(NodeId(13), vec![guide(), sq(1, 0.0, Color::BLACK), sq(2, 5.0, Color::BLACK)]);
|
||||
g.appearance.effects.push(Effect { id: effect.into(), params: params.clone(), visible: true });
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
assert_eq!(all, [(NodeId(20), kind.clone(), true, false)], "{effect}: a group's leading guide, once");
|
||||
assert_eq!(art.children().and_then(|c| c.last()).map(|c| c.id), Some(NodeId(20)), "{effect}: moved last");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ruler guides of a layer or group with a Pathfinder effect or Transform copies, one among
|
||||
/// its art and one after it, go after the evaluated art in the order they were in.
|
||||
#[test]
|
||||
fn a_containers_ruler_guides_keep_their_order_through_its_effects() {
|
||||
use vectorcraft_doc::LayerColor;
|
||||
let guide = |id| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: 3.0, artboard: None }));
|
||||
for (effect, params) in [("pathfinder.add", serde_json::json!({})), ("distort.transform", serde_json::json!({"moveH": 30, "copies": 2}))] {
|
||||
let members = || vec![sq(1, 0.0, Color::BLACK), guide(20), sq(2, 5.0, Color::BLACK), guide(21)];
|
||||
let fx = Effect { id: effect.into(), params: params.clone(), visible: true };
|
||||
let mut l = Node::layer(NodeId(10), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = members();
|
||||
}
|
||||
l.appearance.effects.push(fx.clone());
|
||||
let mut g = Node::group(NodeId(11), members());
|
||||
g.appearance.effects.push(fx);
|
||||
for (what, n) in [("layer", l), ("group", g)] {
|
||||
let art = evaluate_container(None, &n).unwrap();
|
||||
let mut all = vec![];
|
||||
ruler_guides_in(&art, &mut all);
|
||||
let ids = all.iter().map(|(id, ..)| *id).collect::<Vec<_>>();
|
||||
assert_eq!(ids, [NodeId(20), NodeId(21)], "{effect} on a {what}: the guides, in order");
|
||||
let ch = art.children().unwrap();
|
||||
let tail = ch[ch.len() - 2..].iter().map(|c| c.id).collect::<Vec<_>>();
|
||||
assert_eq!(tail, [NodeId(20), NodeId(21)], "{effect} on a {what}: last, in order");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's own Fill + Offset Path below its contents follows the outline of a clip group among
|
||||
/// its members, its clipping path, not the clipped art it hides outside that path (#7289).
|
||||
#[test]
|
||||
|
||||
@@ -23,7 +23,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 2] = ["cap", "lightBehind"];
|
||||
const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"];
|
||||
|
||||
/// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge,
|
||||
/// rotation and perspective, built unshaded, since the classic surfaces light its faces.
|
||||
@@ -118,6 +118,52 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Preserve Spot Colors, a fill linked to a spot swatch stays linked on every face: the
|
||||
/// highlight lowers its tint, and the shadow is black multiplied and overprinting over it.
|
||||
#[test]
|
||||
fn preserve_spot_colors_keeps_the_swatch_on_every_face() {
|
||||
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
|
||||
let spot = |params: Value| {
|
||||
let mut n = profile();
|
||||
*n.appearance = Appearance::basic(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 0.5 }, Paint::None, 0.0);
|
||||
n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, ¶ms).unwrap());
|
||||
crate::revolve_art(&n).unwrap()
|
||||
};
|
||||
let art = spot(json!({"preserveSpotColors": true}));
|
||||
let mut darkened = 0;
|
||||
for face in faces(&art) {
|
||||
let mut fills = face.appearance.items.iter().filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
});
|
||||
match fills.next().map(|f| &f.paint) {
|
||||
Some(Paint::Solid { color, swatch: Some(name), tint }) => {
|
||||
assert_eq!(name, "Ink");
|
||||
assert!(*tint > 0.0 && *tint <= 0.5, "{tint}");
|
||||
assert_eq!(*color, ink.tinted(*tint / 0.5), "the color is the swatch at the face's tint");
|
||||
}
|
||||
other => panic!("the face keeps its swatch: {other:?}"),
|
||||
}
|
||||
if let Some(shadow) = fills.next() {
|
||||
assert!(matches!(shadow.paint.color(), Some(Color::Gray { .. })), "{:?}", shadow.paint);
|
||||
assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true));
|
||||
darkened += 1;
|
||||
}
|
||||
}
|
||||
assert!(darkened > 0, "faces turned from the light are darkened");
|
||||
// Off, and with a custom shading color, the faces are process mixes again.
|
||||
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#336699"})] {
|
||||
let art = spot(params.clone());
|
||||
let linked = faces(&art)
|
||||
.iter()
|
||||
.filter(|f| {
|
||||
f.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if matches!(f.paint, Paint::Solid { swatch: Some(_), .. })))
|
||||
})
|
||||
.count();
|
||||
assert!(linked < faces(&art).len(), "{params}: shaded faces lose the swatch");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angle_offset_edge_and_cap_shape_the_surface() {
|
||||
let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap();
|
||||
@@ -207,6 +253,7 @@ mod tests {
|
||||
(json!({"rotationY": -181}), "`rotationY` must be between -180 and 180"),
|
||||
(json!({"blendSteps": 2.5}), "`blendSteps` must be a whole number"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"preserveSpotColors": "on"}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"surface": "glossy"}), "`surface` must be one of"),
|
||||
(json!({"shadingColor": "white"}), "`shadingColor` must be one of"),
|
||||
(json!({"shadingCustom": "red"}), "`shadingCustom` must be a #rrggbb color"),
|
||||
|
||||
@@ -102,7 +102,7 @@ const RANGES: [(&str, f64, f64, bool); 13] = [
|
||||
("blendSteps", 1.0, 256.0, true),
|
||||
];
|
||||
|
||||
const FLAGS: [&str; 4] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces"];
|
||||
const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"];
|
||||
|
||||
/// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of
|
||||
/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and
|
||||
@@ -127,7 +127,7 @@ const ROTATE_RANGES: [(&str, f64, f64, bool); 9] = [
|
||||
/// Check Rotate (Classic)'s parameters `p` (its defaults filled in) as [`validate`] checks Extrude &
|
||||
/// Bevel (Classic)'s, with `surface` No Shading or Diffuse only.
|
||||
pub fn validate_rotate(p: &Value) -> Result<(), String> {
|
||||
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind"])?;
|
||||
validate_classic(CLASSIC_ROTATE, p, &ROTATE_RANGES, &["lightBehind", "preserveSpotColors"])?;
|
||||
if p.get("surface").is_some_and(|v| !v.as_str().is_some_and(|s| ROTATE_SURFACES.contains(&s))) {
|
||||
return Err(format!("`surface` must be one of {}", ROTATE_SURFACES.join(", ")));
|
||||
}
|
||||
@@ -192,6 +192,35 @@ fn shaded(c: Color, tone: f64, spec: f64, shade: Option<Color>) -> Color {
|
||||
Color::rgb(r, g, b)
|
||||
}
|
||||
|
||||
/// Whether Preserve Spot Colors applies with parameters `p`: `preserveSpotColors` is on and the
|
||||
/// shading color is not Custom, which cannot keep a spot color.
|
||||
fn preserves_spot_colors(p: &Value) -> bool {
|
||||
flag(p, "preserveSpotColors", false) && text(p, "shadingColor", "black") != "custom"
|
||||
}
|
||||
|
||||
/// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower
|
||||
/// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where
|
||||
/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`,
|
||||
/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam
|
||||
/// stroke each layer draws around the face.
|
||||
fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option<Color>, seam: f64) -> Vec<AppearanceItem> {
|
||||
let Paint::Solid { color, swatch, tint } = paint else { return vec![] };
|
||||
let keep = (1.0 - spec).clamp(0.0, 1.0) as f32;
|
||||
let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep };
|
||||
let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))];
|
||||
if shade.is_some() && tone < 1.0 {
|
||||
let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32));
|
||||
let mut layer = FillLayer::new(black.clone());
|
||||
layer.blend = BlendMode::Multiply;
|
||||
layer.overprint = true;
|
||||
let mut edge = crate::lighting::seam_stroke(black, seam);
|
||||
edge.blend = BlendMode::Multiply;
|
||||
edge.overprint = true;
|
||||
items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]);
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
/// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on
|
||||
/// Wireframe, else the seam between faces.
|
||||
pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
@@ -200,12 +229,14 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 {
|
||||
|
||||
/// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child
|
||||
/// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by
|
||||
/// its tone and highlight. A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`]
|
||||
/// draws it). A gradient with transparent stops is shaded opaque and then masked by
|
||||
/// its own transparency, so the shading follows the gradient's coverage.
|
||||
pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node {
|
||||
let shading = classic_shading(p);
|
||||
let lights = lights(p);
|
||||
let shade = shading_color(p);
|
||||
let preserve = preserves_spot_colors(p);
|
||||
let wire = shading.surface == ClassicSurface::Wireframe;
|
||||
let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) };
|
||||
let paint = &paint;
|
||||
@@ -229,6 +260,10 @@ pub(crate) fn surface(n: &Node, facets: Vec<Facet>, source: &Paint, opacity: f32
|
||||
AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)),
|
||||
]
|
||||
}
|
||||
// Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch.
|
||||
Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => {
|
||||
linked_face(paint, tone, spec, shade, seam)
|
||||
}
|
||||
Some(c) => {
|
||||
let fill = Paint::solid(shaded(c, tone, spec, shade));
|
||||
vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Document, NodeId, StrokeLayer};
|
||||
use vectorcraft_doc::{Document, FillLayer, NodeId, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Shape};
|
||||
|
||||
use super::*;
|
||||
@@ -2015,6 +2015,62 @@ fn a_member_in_a_transparent_gradient_keeps_the_shared_face_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills of each face of `art`: the first is the face's paint, a second the shadow over it.
|
||||
fn face_fills(art: &Node) -> Vec<Vec<FillLayer>> {
|
||||
faces(art)
|
||||
.iter()
|
||||
.map(|f| {
|
||||
f.appearance
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(f.clone()),
|
||||
AppearanceItem::Stroke(_) => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_preserve_spot_colors_keeps_a_linked_fill_on_every_face() {
|
||||
let ink = Color::cmyk(0.0, 1.0, 0.0, 0.2);
|
||||
let art = |params: Value| {
|
||||
let mut n = classic(params);
|
||||
n.appearance.items = vec![AppearanceItem::Fill(FillLayer::new(Paint::Solid { color: ink, swatch: Some("Ink".into()), tint: 1.0 }))];
|
||||
solid_art(&n).unwrap()
|
||||
};
|
||||
let lit = json!({"preserveSpotColors": true, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
|
||||
let (mut highlighted, mut shaded) = (false, false);
|
||||
for layers in face_fills(&art(lit)) {
|
||||
let Paint::Solid { color, swatch: Some(name), tint } = &layers[0].paint else { panic!("the swatch is kept: {layers:?}") };
|
||||
assert_eq!(name, "Ink");
|
||||
assert_eq!(*color, ink.tinted(*tint), "the color is the swatch at the face's tint");
|
||||
highlighted |= *tint < 1.0;
|
||||
if let Some(shadow) = layers.get(1) {
|
||||
let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) };
|
||||
assert!(k > 0.0 && k <= 1.0, "{k}");
|
||||
assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0));
|
||||
shaded = true;
|
||||
}
|
||||
assert!(layers.len() <= 2, "{layers:?}");
|
||||
}
|
||||
assert!(highlighted && shaded, "the highlight lowers the tint and the shadow adds black");
|
||||
// No shading color: the highlight only, as tints of the swatch.
|
||||
for layers in face_fills(&art(json!({"preserveSpotColors": true, "shadingColor": "none"}))) {
|
||||
assert!(matches!(&layers[..], [f] if matches!(&f.paint, Paint::Solid { swatch: Some(_), .. })), "{layers:?}");
|
||||
}
|
||||
// Off, or with a custom shading color, shaded faces are process mixes, as before.
|
||||
for params in [json!({}), json!({"preserveSpotColors": true, "shadingColor": "custom", "shadingCustom": "#3366cc"})] {
|
||||
let unlinked = face_fills(&art(params.clone())).iter().filter(|l| matches!(l[0].paint, Paint::Solid { swatch: None, .. })).count();
|
||||
assert!(unlinked > 0, "{params}");
|
||||
}
|
||||
// An unlinked fill is shaded as it is with the option off.
|
||||
let off: Vec<[f32; 3]> = classic_faces(json!({})).iter().map(fill_rgb).collect();
|
||||
let on: Vec<[f32; 3]> = classic_faces(json!({"preserveSpotColors": true})).iter().map(fill_rgb).collect();
|
||||
assert_eq!(off, on);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_parameters_are_checked() {
|
||||
let n = classic(json!({}));
|
||||
@@ -2034,6 +2090,7 @@ fn classic_parameters_are_checked() {
|
||||
(json!({"highlightSize": "big"}), "`highlightSize` must be a number"),
|
||||
(json!({"cap": "yes"}), "`cap` must be true or false"),
|
||||
(json!({"drawHiddenFaces": 1}), "`drawHiddenFaces` must be true or false"),
|
||||
(json!({"preserveSpotColors": "yes"}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"bevel": "fancy"}), "bevel must be none or one of"),
|
||||
(json!({"twist": 10}), "unknown parameter `twist`"),
|
||||
(json!({"lights": []}), "lights must contain one to ten lights"),
|
||||
@@ -2110,6 +2167,7 @@ fn classic_rotate_parameters_are_checked() {
|
||||
(json!({"lightIntensity": 101}), "`lightIntensity` must be between 0 and 100 (got 101)"),
|
||||
(json!({"blendSteps": 0}), "`blendSteps` must be a whole number between 1 and 256 (got 0)"),
|
||||
(json!({"lightBehind": 1}), "`lightBehind` must be true or false"),
|
||||
(json!({"preserveSpotColors": null}), "`preserveSpotColors` must be true or false"),
|
||||
(json!({"highlightSize": 50}), "unknown parameter `highlightSize`"),
|
||||
(json!({"drawHiddenFaces": true}), "unknown parameter `drawHiddenFaces`"),
|
||||
(json!({"shadow": true}), "unknown parameter `shadow`"),
|
||||
|
||||
@@ -9,7 +9,7 @@ mod tests;
|
||||
mod text;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
use vectorcraft_pathops::addons as po;
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Simplify Anchors (Keep Shape)…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step; open ends stay, and locked and hidden paths are left out → {ids, before, after} anchor counts",
|
||||
"{tolerance?: 1..100 (20; higher removes more anchors and lets the outline move further from where it was, up to tolerance × 0.02 pt), protectCorners?: bool (false; anchors where the path turns by more than 30° stay), ids?: [id…] (default: the selection)} remove the anchors each path under the objects can do without, refitting the handles beside each so the outline keeps its shape, as one undo step when a path changes; open ends stay; from the selection, locked and hidden paths are left out, and named by `ids`, the paths of the objects, groups and layers it names are taken even when locked or hidden, but not those on a locked artboard; a changed path loses its selected anchors and segments → {ids, before, after} anchor counts",
|
||||
has_selection,
|
||||
simplify
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Deep Ungroup…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step; each object keeps the opacity of the groups it was in; locked and hidden groups stay whole, and locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
"{includeClipGroups?: bool (false: clipping groups, and the art inside them, stay as they are; true: they are ungrouped too and their clipping paths become plain paths), ids?: [id…] (default: the selection)} ungroup every level of the groups among the objects, as one undo step when a group goes; each object keeps the opacity of the groups it was in; from the selection, locked and hidden groups stay whole; named by `ids`, the groups it names and the groups in the groups and layers it names are ungrouped even when locked or hidden (a named layer stays), but not those on a locked artboard, and their objects become hidden or locked when a group was; locked and hidden objects stay locked or hidden and are not selected → {ids (the objects selected: those left, or with no group to take apart the selection as it was), ungrouped (groups)}",
|
||||
has_selection,
|
||||
deep_ungroup
|
||||
),
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rejoin Path Pieces…",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
"{gap?: pt 0..6 (0.1), ids?: [id…] (default: the selection)} weld the open paths under the objects whose ends lie within the gap of each other back into paths: an end joins one other end, the one the path turns least to go on into, pieces may run either way, and a chain whose ends meet closes; each path takes the place and paint of its topmost piece, as one undo step when a path is made; from the selection, locked and hidden paths are left out, and named by `ids`, they are taken, but not those on a locked artboard; only pieces alike in being hidden (by themselves or a group or layer above them) and in being locked join; locked and hidden paths made are not selected → {ids, joined (paths made), removed (pieces merged into them)}",
|
||||
has_selection,
|
||||
rejoin
|
||||
),
|
||||
@@ -91,9 +91,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included; locked and hidden
|
||||
/// paths, and those in locked or hidden groups, stay out.
|
||||
fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
/// Whether a request names its objects with `ids` (present and not null) rather than taking the
|
||||
/// selection.
|
||||
fn named(p: &Value) -> bool {
|
||||
p.get("ids").is_some_and(|v| !v.is_null())
|
||||
}
|
||||
|
||||
/// Keep the items of `items` whose object (`id`) a command acts on: when `named`, every one not on
|
||||
/// a locked artboard, locked and hidden ones (and ones in a locked or hidden group or layer)
|
||||
/// included; else only those that can be edited.
|
||||
fn retain_targets<T>(d: &Document, items: &mut Vec<T>, named: bool, id: impl Fn(&T) -> NodeId) {
|
||||
if named {
|
||||
let locks = d.locked_artboards();
|
||||
items.retain(|t| !locks.holds_id(id(t)));
|
||||
} else {
|
||||
let editable = d.editable();
|
||||
items.retain(|t| editable(id(t)));
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths (not guides) under `roots`, compound path members included, that a command acts on
|
||||
/// ([`retain_targets`]).
|
||||
fn paths_under(d: &Document, roots: &[NodeId], named: bool) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for n in roots.iter().filter_map(|id| d.node(*id)) {
|
||||
n.walk(&mut |c| {
|
||||
@@ -102,8 +121,7 @@ fn paths_under(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
});
|
||||
}
|
||||
let editable = d.editable();
|
||||
out.retain(|id| editable(*id));
|
||||
retain_targets(d, &mut out, named, |id| *id);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -116,7 +134,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let protect = switch_or(p, "protectCorners", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = paths_under(d, &roots);
|
||||
let ids = paths_under(d, &roots, named(p));
|
||||
let paths: Vec<(NodeId, &PathData)> = ids.iter().filter_map(|id| Some((*id, d.node(*id)?.path_data()?))).collect();
|
||||
let before: usize = paths.iter().map(|(_, p)| p.anchor_count()).sum();
|
||||
if before > MAX_ANCHORS {
|
||||
@@ -258,10 +276,11 @@ fn ungroupable(n: &Node, clips: bool) -> bool {
|
||||
}
|
||||
|
||||
/// `n` with every level of grouping Deep Ungroup takes apart removed, into `out`; `count` counts
|
||||
/// the groups. Members take on the opacity of the groups they were in, and a clipping path
|
||||
/// becomes a plain path. A locked or hidden group stays whole.
|
||||
fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || n.locked || !n.visible {
|
||||
/// the groups. Members take on the opacity of the groups they were in, are hidden when one of them
|
||||
/// was hidden and locked when one of them was locked, and a clipping path becomes a plain path. A
|
||||
/// locked or hidden group stays whole unless `named`.
|
||||
fn flatten(n: Node, clips: bool, named: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
if !ungroupable(&n, clips) || (!named && (n.locked || !n.visible)) {
|
||||
out.push(n);
|
||||
return;
|
||||
}
|
||||
@@ -276,26 +295,57 @@ fn flatten(n: Node, clips: bool, out: &mut Vec<Node>, count: &mut usize) {
|
||||
*clipping = false;
|
||||
}
|
||||
c.opacity *= n.opacity;
|
||||
flatten(c, clips, out, count);
|
||||
c.visible &= n.visible;
|
||||
c.locked |= n.locked;
|
||||
flatten(c, clips, named, out, count);
|
||||
}
|
||||
}
|
||||
|
||||
/// The outermost groups Deep Ungroup takes apart in layer `n`, its sublayers included, in paint
|
||||
/// order, leaving out those on a locked artboard.
|
||||
fn groups_in_layer(d: &Document, n: &Node, clips: bool, out: &mut Vec<NodeId>) {
|
||||
let locks = d.locked_artboards();
|
||||
fn visit(n: &Node, clips: bool, locks: &LockedArtboards, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
visit(c, clips, locks, out);
|
||||
} else if ungroupable(c, clips) && !locks.holds_id(c.id) {
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(n, clips, &locks, out);
|
||||
}
|
||||
|
||||
fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.cleanup.deepUngroup";
|
||||
let clips = switch_or(p, "includeClipGroups", false, C)?;
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let named = named(p);
|
||||
let mut roots = checked_ids_or_selection(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// Locked and hidden objects, and those in locked or hidden groups, stay as they are.
|
||||
let roots: Vec<NodeId> = {
|
||||
let editable = d.editable();
|
||||
roots.into_iter().filter(|id| editable(*id)).collect()
|
||||
};
|
||||
// From the selection, locked and hidden objects, and those in locked or hidden groups, stay as
|
||||
// they are; named, only those on a locked artboard do.
|
||||
retain_targets(d, &mut roots, named, |id| *id);
|
||||
// A named layer stays: the groups in it, and in its sublayers, are taken apart.
|
||||
let mut groups = vec![];
|
||||
for id in roots {
|
||||
match d.node(id) {
|
||||
Some(n) if named && n.is_layer() => {
|
||||
let at = groups.len();
|
||||
groups_in_layer(d, n, clips, &mut groups);
|
||||
if groups.len() == at {
|
||||
groups.push(id);
|
||||
}
|
||||
}
|
||||
_ => groups.push(id),
|
||||
}
|
||||
}
|
||||
let (mut items, mut selected, mut count) = (vec![], vec![], 0);
|
||||
for id in &roots {
|
||||
for id in &groups {
|
||||
match d.node(*id).filter(|n| ungroupable(n, clips)) {
|
||||
Some(n) => {
|
||||
let mut out = vec![];
|
||||
flatten(n.clone(), clips, &mut out, &mut count);
|
||||
flatten(n.clone(), clips, named, &mut out, &mut count);
|
||||
selected.extend(out.iter().map(|n| n.id));
|
||||
items.push((*id, out));
|
||||
}
|
||||
@@ -304,7 +354,7 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// With no group to take apart, the document, the selection and the undo history stay as they
|
||||
// are, and the reply lists the selection.
|
||||
if items.is_empty() {
|
||||
if count == 0 {
|
||||
selected = s.doc()?.selection.objects.to_vec();
|
||||
} else {
|
||||
selected = s.edit("Deep Ungroup", move |d, sel| {
|
||||
@@ -319,26 +369,39 @@ fn deep_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": selected.iter().map(|i| i.0).collect::<Vec<_>>(), "ungrouped": count }))
|
||||
}
|
||||
|
||||
/// One path Rejoin Path Pieces takes: its id, its subpath, and whether it and every group and layer
|
||||
/// above it are visible, and whether they are all unlocked.
|
||||
type Piece = (NodeId, SubPath, (bool, bool));
|
||||
|
||||
/// The open single-subpath paths under `roots` that Rejoin Path Pieces takes, in paint order
|
||||
/// (compound path members, clipping paths and guides stay out).
|
||||
fn pieces(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, SubPath)> {
|
||||
fn visit(n: &Node, out: &mut Vec<(NodeId, SubPath)>) {
|
||||
/// (compound path members, clipping paths and guides stay out; [`retain_targets`]).
|
||||
fn pieces(d: &Document, roots: &[NodeId], named: bool) -> Vec<Piece> {
|
||||
fn visit(n: &Node, above: (bool, bool), out: &mut Vec<Piece>) {
|
||||
let state = (above.0 && n.visible, above.1 && !n.locked);
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => {
|
||||
if let [sp] = path.subpaths.as_slice()
|
||||
&& !sp.closed
|
||||
{
|
||||
out.push((n.id, sp.clone()));
|
||||
out.push((n.id, sp.clone(), state));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, out)),
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| visit(c, state, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
roots.iter().filter_map(|id| d.node(*id)).for_each(|n| visit(n, &mut out));
|
||||
let editable = d.editable();
|
||||
out.retain(|(id, _)| editable(*id));
|
||||
for (id, n) in roots.iter().filter_map(|id| Some((*id, d.node(*id)?))) {
|
||||
// The groups and layers above the root, and their state.
|
||||
let above = d.ancestry(id).unwrap_or_default();
|
||||
let above = above.split_last().map_or(&[][..], |(_, up)| up);
|
||||
if above.last().and_then(|i| d.node(*i)).is_some_and(|parent| matches!(parent.kind, NodeKind::Compound { .. })) {
|
||||
continue;
|
||||
}
|
||||
let state = above.iter().filter_map(|i| d.node(*i)).fold((true, true), |(v, u), a| (v && a.visible, u && !a.locked));
|
||||
visit(n, state, &mut out);
|
||||
}
|
||||
retain_targets(d, &mut out, named, |piece| piece.0);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -349,18 +412,26 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`gap` must be from 0 to 6 pt"));
|
||||
}
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
let found = pieces(&s.doc()?.doc, &roots);
|
||||
let found = pieces(&s.doc()?.doc, &roots, named(p));
|
||||
if found.len() > MAX_OBJECTS {
|
||||
return Err(EngineError::Other("Rejoin Path Pieces: too many paths to rejoin at once".into()));
|
||||
}
|
||||
let subpaths: Vec<SubPath> = found.iter().map(|(_, sp)| sp.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
// Only pieces alike in being shown and in being unlocked join, so that a joined path neither
|
||||
// shows hidden art nor hides shown art, nor locks or unlocks a piece.
|
||||
let (mut kept, mut gone) = (vec![], vec![]);
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| found.get(m).map(|f| f.0)).collect();
|
||||
let Some(&top) = j.members.iter().max().and_then(|&m| found.get(m).map(|f| &f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
for state in [(true, true), (true, false), (false, true), (false, false)] {
|
||||
let part: Vec<&Piece> = found.iter().filter(|f| f.2 == state).collect();
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let subpaths: Vec<SubPath> = part.iter().map(|f| f.1.clone()).collect();
|
||||
// Each chain becomes its topmost piece (the last in paint order); the others go.
|
||||
for j in po::rejoin(&subpaths, gap) {
|
||||
let ids: Vec<NodeId> = j.members.iter().filter_map(|&m| part.get(m).map(|f| f.0)).collect();
|
||||
let Some(top) = j.members.iter().max().and_then(|&m| part.get(m).map(|f| f.0)) else { continue };
|
||||
gone.extend(ids.into_iter().filter(|id| *id != top));
|
||||
kept.push((top, j.path));
|
||||
}
|
||||
}
|
||||
if !kept.is_empty() {
|
||||
let ids: Vec<NodeId> = kept.iter().map(|k| k.0).collect();
|
||||
@@ -369,7 +440,9 @@ fn rejoin(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set_path(d, *id, PathData::single(sp.clone()));
|
||||
}
|
||||
d.remove_many(&gone)?;
|
||||
sel.set(ids);
|
||||
// Locked and hidden paths, and those in locked or hidden groups, are not selected.
|
||||
let editable = d.editable();
|
||||
sel.set(ids.into_iter().filter(|id| editable(*id)));
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind};
|
||||
use vectorcraft_doc::{Appearance, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, Rect};
|
||||
|
||||
use crate::Session;
|
||||
@@ -123,18 +123,100 @@ fn simplify_leaves_locked_and_hidden_paths_alone() {
|
||||
assert_eq!(r["before"], 16);
|
||||
assert!(anchors(&s, ids[0]) < 16);
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
// Named by `ids`, or in a locked group, a path stays too, with no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [ids[1].0, ids[2].0]})).unwrap();
|
||||
assert_eq!((anchors(&s, ids[1]), anchors(&s, ids[2])), (16, 16));
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// In a selected locked group, a path stays too, with no undo step.
|
||||
change(&mut s, ids[1], |n| n.locked = false);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!((r["before"].as_u64(), r["after"].as_u64()), (Some(0), Some(0)));
|
||||
assert_eq!(anchors(&s, ids[1]), 16);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// Named by `ids`, the locked group's paths, its hidden one included, are simplified.
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([ids[0].0, ids[1].0, ids[2].0]));
|
||||
assert!(anchors(&s, ids[1]) < 16 && anchors(&s, ids[2]) < 16);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// A path of 16 anchors at (`x`, `y`): an ellipse with anchors added twice.
|
||||
fn ellipse16(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
let e = id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap());
|
||||
select(s, &[e]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
e
|
||||
}
|
||||
|
||||
/// Simplify Anchors takes the locked and hidden paths `ids` names, those in the locked or hidden
|
||||
/// groups and layers it names (their locked and hidden members too) and a hidden compound path's
|
||||
/// member, as one undo step, without selecting them; from the selection it leaves them alone, and a
|
||||
/// path on a locked artboard stays even when named.
|
||||
#[test]
|
||||
fn simplify_named_locked_and_hidden_paths() {
|
||||
let mut s = session();
|
||||
let locked = ellipse16(&mut s, 10.0, 10.0);
|
||||
let hidden = ellipse16(&mut s, 70.0, 10.0);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| n.visible = false);
|
||||
// A locked group with a hidden member, and a hidden group with a locked member.
|
||||
let in_locked = ellipse16(&mut s, 130.0, 10.0);
|
||||
let locked_group = wrap(&mut s, in_locked, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, locked_group, |n| n.locked = true);
|
||||
change(&mut s, in_locked, |n| n.visible = false);
|
||||
let in_hidden = ellipse16(&mut s, 190.0, 10.0);
|
||||
let hidden_group = wrap(&mut s, in_hidden, |c| NodeKind::Group { children: c, clip: false });
|
||||
change(&mut s, hidden_group, |n| n.visible = false);
|
||||
change(&mut s, in_hidden, |n| n.locked = true);
|
||||
// A member of a hidden compound path.
|
||||
let member = ellipse16(&mut s, 250.0, 10.0);
|
||||
let compound = wrap(&mut s, member, |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
change(&mut s, compound, |n| n.visible = false);
|
||||
// A path in a locked layer, named itself.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let in_layer = ellipse16(&mut s, 10.0, 100.0);
|
||||
let on_board = ellipse16(&mut s, 10.0, 200.0);
|
||||
change(&mut s, layer, |n| n.locked = true);
|
||||
let all = [locked, hidden, in_locked, in_hidden, member, in_layer];
|
||||
select(&mut s, &[locked, hidden, locked_group, hidden_group, compound]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]), "from the selection, none is taken");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
select(&mut s, &[]);
|
||||
s.edit("Select Anchors", |_, sel| {
|
||||
sel.anchors.insert(locked, [(0, 1)].into());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0, hidden.0, locked_group.0, hidden_group.0, member.0, in_layer.0]})).unwrap();
|
||||
assert_eq!(r["ids"], json!(all.iter().map(|i| i.0).collect::<Vec<_>>()));
|
||||
assert_eq!(r["before"], 16 * 6);
|
||||
assert_eq!(r["after"].as_u64(), Some(all.iter().map(|id| anchors(&s, *id) as u64).sum::<u64>()));
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "nothing is selected, and the changed path's anchors are not");
|
||||
let n = node(&s, in_hidden).unwrap();
|
||||
assert!(n.locked && n.visible && !node(&s, hidden_group).unwrap().visible);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) == 16));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(all.iter().all(|id| anchors(&s, *id) < 16));
|
||||
// Nothing left to remove: no undo step.
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("addon.cleanup.simplify", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// On a locked artboard, a named path stays as it is.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.simplify", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ids"].clone(), anchors(&s, on_board), undo_steps(&s)), (json!([]), 16, steps));
|
||||
}
|
||||
|
||||
/// Each kind: what makes the issue in a fresh document (beside a clean rectangle).
|
||||
@@ -610,14 +692,15 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert!(!d.node(hidden).unwrap().visible && d.node(b).unwrap().visible);
|
||||
assert!(d.node(locked).unwrap().locked && d.node(e).unwrap().locked);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
// Named by `ids`, a locked group stays as it is, with no undo step.
|
||||
// Named by `ids`, a locked group is taken apart as one undo step; its member becomes locked
|
||||
// and is not selected.
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0]})).unwrap();
|
||||
assert_eq!(r["ungrouped"], 0);
|
||||
assert!(node(&s, locked).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(r["ungrouped"], 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, c).unwrap().locked);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
// With nothing ungrouped, the selection stays and the reply lists it.
|
||||
assert_eq!(r["ids"], json!([a.0]));
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
select(&mut s, &[a]);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [f.0]})).unwrap();
|
||||
@@ -625,6 +708,108 @@ fn deep_ungroup_keeps_hidden_art_hidden_and_locked_art_locked() {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [a]);
|
||||
}
|
||||
|
||||
/// Put `ids` inside a new container that `kind` makes of its members.
|
||||
fn wrap_all(s: &mut Session, ids: &[NodeId], kind: fn(Vec<std::sync::Arc<Node>>) -> NodeKind) -> NodeId {
|
||||
s.edit("t", |d, _| {
|
||||
let w = d.alloc_id();
|
||||
Ok(d.wrap(ids, |c| Node::new(w, kind(c)))?)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn plain_group(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Group { children: c, clip: false }
|
||||
}
|
||||
|
||||
fn sublayer(c: Vec<std::sync::Arc<Node>>) -> NodeKind {
|
||||
NodeKind::Layer { color: LayerColor::Preset(0), template: false, printable: true, children: c, clip: false, preview: true, dim_images: None }
|
||||
}
|
||||
|
||||
/// Named by `ids`, Deep Ungroup takes apart locked and hidden groups, those nested in a group it
|
||||
/// names and those in a layer it names (its sublayers included, the layer staying), as one undo
|
||||
/// step; their members become locked or hidden as the groups were, keep the groups' opacity and are
|
||||
/// not selected. From the selection those groups stay whole, as do a clipping group and a group on a
|
||||
/// locked artboard even when named.
|
||||
#[test]
|
||||
fn deep_ungroup_named_locked_and_hidden_groups() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0);
|
||||
let locked = wrap_all(&mut s, &[a], plain_group);
|
||||
let hidden = wrap_all(&mut s, &[b], plain_group);
|
||||
change(&mut s, locked, |n| n.locked = true);
|
||||
change(&mut s, hidden, |n| {
|
||||
n.visible = false;
|
||||
n.opacity = 0.5;
|
||||
});
|
||||
select(&mut s, &[locked, hidden]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, they stay whole");
|
||||
assert!(node(&s, locked).is_some() && node(&s, hidden).is_some());
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [locked.0, hidden.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(2), json!([])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, locked).is_none() && node(&s, hidden).is_none());
|
||||
let (na, nb) = (node(&s, a).unwrap(), node(&s, b).unwrap());
|
||||
assert!(na.locked && na.visible && !nb.visible && !nb.locked);
|
||||
assert_eq!(nb.opacity, 0.5);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_some() && !node(&s, a).unwrap().locked && node(&s, b).unwrap().visible);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, locked).is_none() && node(&s, a).unwrap().locked);
|
||||
// Locked and hidden groups nested in a named group that can be edited.
|
||||
let c = rect(&mut s, 70.0, 10.0, 20.0, 20.0);
|
||||
let e = rect(&mut s, 100.0, 10.0, 20.0, 20.0);
|
||||
let f = rect(&mut s, 130.0, 10.0, 20.0, 20.0);
|
||||
let inner_locked = wrap_all(&mut s, &[e], plain_group);
|
||||
let inner_hidden = wrap_all(&mut s, &[f], plain_group);
|
||||
change(&mut s, inner_locked, |n| n.locked = true);
|
||||
change(&mut s, inner_hidden, |n| n.visible = false);
|
||||
let outer = wrap_all(&mut s, &[c, inner_locked, inner_hidden], plain_group);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [outer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone()), (json!(3), json!([c.0])));
|
||||
assert!(node(&s, e).unwrap().locked && !node(&s, f).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [c]);
|
||||
// In a named layer and its sublayer; the layers and a clipping group stay.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let g = rect(&mut s, 10.0, 100.0, 20.0, 20.0);
|
||||
let h = rect(&mut s, 40.0, 100.0, 20.0, 20.0);
|
||||
let layer_locked = wrap_all(&mut s, &[g], plain_group);
|
||||
change(&mut s, layer_locked, |n| n.locked = true);
|
||||
let layer_hidden = wrap_all(&mut s, &[h], plain_group);
|
||||
change(&mut s, layer_hidden, |n| n.visible = false);
|
||||
let sub = wrap_all(&mut s, &[layer_hidden], sublayer);
|
||||
let clipped = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let clip = rect(&mut s, 95.0, 95.0, 30.0, 30.0);
|
||||
select(&mut s, &[clipped, clip]);
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let clip_group = s.doc().unwrap().selection.objects[0];
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [layer.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), undo_steps(&s)), (json!(2), steps + 1));
|
||||
assert!(node(&s, layer_locked).is_none() && node(&s, layer_hidden).is_none());
|
||||
assert!(node(&s, layer).is_some() && node(&s, clip_group).is_some());
|
||||
assert!(node(&s, g).unwrap().locked && !node(&s, h).unwrap().visible);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(h), Some(sub));
|
||||
// On a locked artboard, a named group stays whole, with the selection as it was.
|
||||
let k = rect(&mut s, 10.0, 200.0, 20.0, 20.0);
|
||||
let on_board = wrap_all(&mut s, &[k], plain_group);
|
||||
let off_board = rect(&mut s, 500.0, 10.0, 20.0, 20.0);
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[off_board]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.deepUngroup", &json!({"ids": [on_board.0]})).unwrap();
|
||||
assert_eq!((r["ungrouped"].clone(), r["ids"].clone(), undo_steps(&s)), (json!(0), json!([off_board.0]), steps));
|
||||
assert!(node(&s, on_board).is_some());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [off_board]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
let mut s = session();
|
||||
@@ -646,3 +831,74 @@ fn rejoin_joins_pieces_within_the_gap_only() {
|
||||
assert!(s.execute("addon.cleanup.rejoin", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Named by `ids`, Rejoin Path Pieces takes locked and hidden pieces (in a locked group or layer
|
||||
/// too) and joins only pieces alike in being hidden and in being locked, whichever is topmost, as one
|
||||
/// undo step; a locked or hidden path it makes is not selected. From the selection it takes only
|
||||
/// pieces that can be edited, and compound path members and pieces on a locked artboard stay out.
|
||||
#[test]
|
||||
fn rejoin_named_locked_and_hidden_pieces() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(10.0, 10.0), (50.0, 10.0)]);
|
||||
let b = line(&mut s, &[(50.05, 10.0), (90.0, 10.0)]);
|
||||
let g = wrap_all(&mut s, &[a, b], plain_group);
|
||||
change(&mut s, g, |n| n.locked = true);
|
||||
select(&mut s, &[g]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps), "from the selection, none is taken");
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([b.0])));
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the locked path is not selected");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_some() && anchors(&s, b) == 2);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).is_none() && anchors(&s, b) == 3);
|
||||
// A shown piece and two hidden ones, the hidden on top: only the hidden pair joins.
|
||||
let c = line(&mut s, &[(10.0, 40.0), (50.0, 40.0)]);
|
||||
let e = line(&mut s, &[(50.05, 40.0), (90.0, 40.0)]);
|
||||
let h = line(&mut s, &[(90.05, 40.0), (130.0, 40.0)]);
|
||||
change(&mut s, e, |n| n.visible = false);
|
||||
change(&mut s, h, |n| n.visible = false);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [c.0, e.0, h.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), r["ids"].clone()), (json!(1), json!(1), json!([h.0])));
|
||||
assert!(node(&s, e).is_none() && anchors(&s, c) == 2 && anchors(&s, h) == 3);
|
||||
assert!(!node(&s, h).unwrap().visible && node(&s, c).unwrap().visible);
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the hidden path is not selected");
|
||||
// An unlocked piece under a locked one, and a hidden piece under a shown one: none joins.
|
||||
let k = line(&mut s, &[(10.0, 70.0), (50.0, 70.0)]);
|
||||
let m = line(&mut s, &[(50.05, 70.0), (90.0, 70.0)]);
|
||||
let n = line(&mut s, &[(10.0, 100.0), (50.0, 100.0)]);
|
||||
let o = line(&mut s, &[(50.05, 100.0), (90.0, 100.0)]);
|
||||
change(&mut s, m, |x| x.locked = true);
|
||||
change(&mut s, n, |x| x.visible = false);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [k.0, m.0, n.0, o.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["removed"].clone(), undo_steps(&s)), (json!(0), json!(0), steps));
|
||||
assert!([k, m, n, o].iter().all(|id| anchors(&s, *id) == 2));
|
||||
// Named pieces in a locked layer join; members of a compound path stay out.
|
||||
let layer = id_of(&s.execute("layer.new", &json!({})).unwrap());
|
||||
let p = line(&mut s, &[(10.0, 130.0), (50.0, 130.0)]);
|
||||
let q = line(&mut s, &[(50.05, 130.0), (90.0, 130.0)]);
|
||||
let u = line(&mut s, &[(10.0, 160.0), (50.0, 160.0)]);
|
||||
let v = line(&mut s, &[(50.05, 160.0), (90.0, 160.0)]);
|
||||
wrap_all(&mut s, &[u, v], |c| NodeKind::Compound { children: c, rule: FillRule::NonZero });
|
||||
let w = line(&mut s, &[(10.0, 200.0), (50.0, 200.0)]);
|
||||
let x = line(&mut s, &[(50.05, 200.0), (90.0, 200.0)]);
|
||||
change(&mut s, layer, |l| l.locked = true);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [p.0, q.0, u.0, v.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), r["ids"].clone()), (json!(1), json!([q.0])));
|
||||
assert!(node(&s, p).is_none() && anchors(&s, u) == 2 && anchors(&s, v) == 2);
|
||||
// On a locked artboard, named pieces stay as they are.
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("addon.cleanup.rejoin", &json!({"ids": [w.0, x.0]})).unwrap();
|
||||
assert_eq!((r["joined"].clone(), undo_steps(&s)), (json!(0), steps));
|
||||
assert!(node(&s, w).is_some() && node(&s, x).is_some());
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
|
||||
@@ -22,6 +22,22 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]).
|
||||
const SEAM_FILLS_NAME: &str = "Seam Fills";
|
||||
|
||||
/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths
|
||||
/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto
|
||||
/// Grouping groups hold filled paths.)
|
||||
fn is_seam_fills(n: &Node) -> bool {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& m.appearance.fill_paint() == Paint::None
|
||||
&& m.appearance.stroke_paint() != Paint::None
|
||||
};
|
||||
matches!(n.kind, NodeKind::Group { clip: false, .. })
|
||||
&& (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only)))
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
@@ -393,11 +409,15 @@ fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
|
||||
/// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is,
|
||||
/// under every other group. Any other group among `items` (Auto Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
use vectorcraft_color::tint_percent;
|
||||
// The seam fills come first, under every path: kept there, they move under nothing.
|
||||
let mut items = items;
|
||||
let seams: Vec<Arc<Node>> = if items.first().is_some_and(|n| is_seam_fills(n)) { items.drain(..1).collect() } else { vec![] };
|
||||
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
|
||||
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
|
||||
// a color's `#rrggbb` or as "Gradients".
|
||||
@@ -517,14 +537,15 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(groups
|
||||
let groups: Vec<Arc<Node>> = groups
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let mut g = Node::group(d.alloc_id(), run.members);
|
||||
g.name = Some(run.name);
|
||||
Arc::new(g)
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
Ok(seams.into_iter().chain(groups).collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
|
||||
@@ -608,11 +629,13 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
|
||||
}
|
||||
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
|
||||
/// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam
|
||||
/// fills ([`seams_within`]).
|
||||
pub struct Traced {
|
||||
inputs: TraceInputs,
|
||||
raster: (u32, u32),
|
||||
res: tr::TraceResult,
|
||||
seams: Vec<tr::TracedPath>,
|
||||
}
|
||||
|
||||
impl Traced {
|
||||
@@ -636,7 +659,18 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64
|
||||
tr::TraceError::Cancelled => EngineError::Cancelled,
|
||||
e => EngineError::Other(e.to_string()),
|
||||
})?;
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res })
|
||||
let seams = seams_within(&res, params, MAX_TRACE_ANCHORS);
|
||||
Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams })
|
||||
}
|
||||
|
||||
/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam
|
||||
/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the
|
||||
/// paths, so a trace whose paths have more than half of `max` gets none.
|
||||
fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec<tr::TracedPath> {
|
||||
if res.anchor_count() > max / 2 {
|
||||
return vec![];
|
||||
}
|
||||
tr::seam_fills(&res.paths, params)
|
||||
}
|
||||
|
||||
/// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`]
|
||||
@@ -716,7 +750,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
s.note_journal("savedPreset", recorded);
|
||||
}
|
||||
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
|
||||
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
|
||||
let Traced { raster, res, seams: seam_fills, .. } = match s.trace_hand_off.take() {
|
||||
Some(traced) if traced.inputs == inputs => traced,
|
||||
_ => trace_now(&inputs, &trace, &|_, _| true)?,
|
||||
};
|
||||
@@ -729,6 +763,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -754,8 +795,38 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
hidden.visible = false;
|
||||
children.push(Arc::new(hidden));
|
||||
}
|
||||
let paint_of = |tp: &tr::TracedPath| {
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a group of their own under every path.
|
||||
let seams: Vec<Arc<Node>> = seam_fills
|
||||
.iter()
|
||||
.filter_map(|tp| {
|
||||
let width = tp.stroke?;
|
||||
let mut n = shape_node(d, tp.path.transformed(xf), None);
|
||||
n.appearance = Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint_of(tp), width * seam_unit)
|
||||
})],
|
||||
..Default::default()
|
||||
}
|
||||
.into();
|
||||
Some(Arc::new(n))
|
||||
})
|
||||
.collect();
|
||||
if !seams.is_empty() {
|
||||
let mut g = Node::group(d.alloc_id(), seams);
|
||||
g.name = Some(SEAM_FILLS_NAME.into());
|
||||
children.push(Arc::new(g));
|
||||
}
|
||||
let mut traced = Vec::with_capacity(res.paths.len());
|
||||
for tp in res.paths {
|
||||
let paint = paint_of(&tp);
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
// Shapes: a path the tracer found to be a shape is that live shape.
|
||||
@@ -764,10 +835,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
*path = shape.to_path();
|
||||
*live = Some(Box::new(shape));
|
||||
}
|
||||
let solid =
|
||||
by_color.get(&tp.color).map_or_else(|| Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])), |paint| (*paint).clone());
|
||||
// Gradients: a path the tracer found to be a linear gradient is filled with it.
|
||||
let paint = tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round corners, and ends round or square as the tracer found them.
|
||||
Some(width) => Appearance {
|
||||
@@ -1103,9 +1170,28 @@ mod color_group_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, trace_warnings};
|
||||
use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings};
|
||||
use vectorcraft_trace as tr;
|
||||
|
||||
#[test]
|
||||
fn seam_fills_count_against_the_anchor_limit() {
|
||||
// Two colors side by side, the edge between them anti-aliased: one seam fill along it.
|
||||
let img = tr::Raster::from_fn(24, 16, |x, _| {
|
||||
let share = (10.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let params = tr::TraceParams { mode: tr::Mode::Color, colors: 2, method: tr::Method::Abutting, ..tr::TraceParams::default() };
|
||||
let res = tr::trace(&img, ¶ms);
|
||||
let all = tr::seam_fills(&res.paths, ¶ms);
|
||||
assert!(!all.is_empty(), "{res:?}");
|
||||
let anchors = res.anchor_count();
|
||||
// Twice the paths' anchors leaves room for any seam fills.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors), all);
|
||||
// One anchor short of that: none.
|
||||
assert_eq!(seams_within(&res, ¶ms, 2 * anchors - 1), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_warnings_name_matched_colors_that_produce_no_paths() {
|
||||
let params = tr::TraceParams { keep_colors: vec!["#ff0000".into()], ..tr::TraceParams::default() };
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, ProofTarget};
|
||||
use vectorcraft_color::cms::{self, ColorSettings, Intent, Model, Policy, ProofTarget};
|
||||
use vectorcraft_color::recolor::Neutral;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::ColorMode;
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -163,12 +163,26 @@ fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
switch_or(p, key, false, cmd).map(Some)
|
||||
}
|
||||
|
||||
/// The policy `p` gives for `key`, one of `allowed`, or `None` when `p` leaves it out.
|
||||
fn policy_param(p: &Value, key: &str, allowed: &[Policy], cmd: &str) -> Result<Option<Policy>> {
|
||||
let Some(v) = text_param(p, key, cmd)? else { return Ok(None) };
|
||||
match Policy::parse(v).filter(|x| allowed.contains(x)) {
|
||||
Some(x) => Ok(Some(x)),
|
||||
None => {
|
||||
let ids: Vec<&str> = allowed.iter().map(Policy::id).collect();
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", ids.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_json(st: &ColorSettings) -> Value {
|
||||
json!({
|
||||
"rgb": st.rgb,
|
||||
"cmyk": st.cmyk,
|
||||
"intent": st.intent.id(),
|
||||
"bpc": st.bpc,
|
||||
"rgbPolicy": st.rgb_policy.id(),
|
||||
"cmykPolicy": st.cmyk_policy.id(),
|
||||
"profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -205,6 +219,12 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.intent = i;
|
||||
}
|
||||
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
|
||||
if let Some(v) = policy_param(p, "rgbPolicy", &Policy::RGB, C)? {
|
||||
st.rgb_policy = v;
|
||||
}
|
||||
if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? {
|
||||
st.cmyk_policy = v;
|
||||
}
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
// Saved for the next start when the app attached a settings file (#6335).
|
||||
@@ -530,7 +550,12 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
convert_colors(d, &mode_converter(mode, intent, grays))
|
||||
}
|
||||
|
||||
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
|
||||
/// the art changed, as [`set_color_mode`] counts them.
|
||||
fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) -> usize {
|
||||
for sw in d.swatches_iter_mut() {
|
||||
match &mut sw.paint {
|
||||
Paint::Solid { color, .. } => *color = conv(color),
|
||||
@@ -538,6 +563,11 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
for st in &mut g.gradient.stops {
|
||||
st.color = conv(&st.color);
|
||||
}
|
||||
if let Some(freeform) = &mut g.freeform {
|
||||
for point in &mut freeform.points {
|
||||
point.color = conv(&point.color);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -621,6 +651,102 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
in_art
|
||||
}
|
||||
|
||||
/// Apply the color management policies of Edit → Color Settings to `d`, a document being opened:
|
||||
/// each RGB or CMYK profile it is tagged with that is not the working space of its model is kept
|
||||
/// (Preserve Embedded Profiles), taken off with the color numbers kept (Off, Preserve Numbers), or
|
||||
/// taken off after the colors of that model were converted from it into the working space with the
|
||||
/// working intent (Convert to Working Space). A profile that is not available here is taken off
|
||||
/// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
let working = cms::working_settings();
|
||||
let (rgb, cmyk) = doc_profiles(d);
|
||||
let mut notes = Vec::new();
|
||||
// What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after
|
||||
// converting the colors from the profile it holds.
|
||||
let mut decide = |label: &str, tag: Option<String>, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option<Option<String>> {
|
||||
let tag = tag.filter(|t| t != working)?;
|
||||
let available = cms::profile(&tag).is_some_and(|p| p.kind == kind);
|
||||
match policy {
|
||||
Policy::PreserveEmbedded => None,
|
||||
Policy::Off | Policy::PreserveNumbers => {
|
||||
notes.push(format!(
|
||||
"the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}",
|
||||
policy.label()
|
||||
));
|
||||
Some(None)
|
||||
}
|
||||
Policy::Convert if available => {
|
||||
notes.push(format!(
|
||||
"the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”"
|
||||
));
|
||||
Some(Some(tag))
|
||||
}
|
||||
Policy::Convert => {
|
||||
notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted"));
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb);
|
||||
let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk);
|
||||
if rgb_do.is_none() && cmyk_do.is_none() {
|
||||
return (notes, false);
|
||||
}
|
||||
let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten());
|
||||
if from_rgb.is_some() || from_cmyk.is_some() {
|
||||
let source = cms::for_document(from_rgb.as_deref(), from_cmyk.as_deref());
|
||||
let dest = cms::working();
|
||||
let intent = working.intent;
|
||||
let (rgb_on, cmyk_on) = (from_rgb.is_some(), from_cmyk.is_some());
|
||||
let conv = |c: &Color| match c {
|
||||
Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent),
|
||||
Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent),
|
||||
_ => *c,
|
||||
};
|
||||
convert_colors(d, &conv);
|
||||
convert_setting_colors(d, &conv);
|
||||
}
|
||||
if rgb_do.is_some() {
|
||||
d.color_profiles.rgb = None;
|
||||
}
|
||||
if cmyk_do.is_some() {
|
||||
d.color_profiles.cmyk = None;
|
||||
}
|
||||
(notes, true)
|
||||
}
|
||||
|
||||
/// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each
|
||||
/// artboard's background, the transparency grid and simulated paper colors of Document Setup, and
|
||||
/// the fill and stroke of the character and paragraph styles.
|
||||
fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) {
|
||||
for c in d.artboards.iter_mut().filter_map(|a| a.color.as_mut()) {
|
||||
*c = conv(c);
|
||||
}
|
||||
for c in &mut d.setup.grid_colors {
|
||||
*c = conv(c);
|
||||
}
|
||||
// A tint of a global swatch is the converted swatch's color at its tint, which
|
||||
// [`convert_colors`] already gave it.
|
||||
let bases = global_bases(d);
|
||||
let mut f = |c: &Color, link: proof::Link| mode_color(c, link, &bases, conv);
|
||||
for styles in [&mut d.char_styles, &mut d.para_styles] {
|
||||
if !styles.iter().any(|s| s.attrs.contains_key("fill") || s.attrs.contains_key("stroke")) {
|
||||
continue;
|
||||
}
|
||||
for def in styles.iter_mut() {
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(value) = def.attrs.get_mut(key) else { continue };
|
||||
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { continue };
|
||||
map_paint_colors(&mut paint, &mut f);
|
||||
if let Ok(v) = serde_json::to_value(&paint) {
|
||||
*value = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`].
|
||||
fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) {
|
||||
proof::map_node_colors(n, f);
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! Type › Composite Fonts…: the document's composite fonts ([`vectorcraft_doc::CompositeFont`]),
|
||||
//! which set each class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals) in a
|
||||
//! font of its own. Type names a composite font as its family, and the font menus list them first.
|
||||
//! The font database holds the active document's composite fonts ([`sync`]); a file exported here
|
||||
//! carries them to another document.
|
||||
//! font of its own, and the characters of each custom character set in the set's font. Type names
|
||||
//! a composite font as its family, and the font menus list them first. The font database holds the
|
||||
//! active document's composite fonts ([`sync`]); a file exported here carries them to another
|
||||
//! document.
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts};
|
||||
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
use super::fileio::{read_file_head, write_file};
|
||||
@@ -26,6 +29,10 @@ const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
|
||||
/// The keys a custom character set may give: its name and characters, then its part's values
|
||||
/// (a set is never scaled at the center).
|
||||
const SET_KEYS: [&str; 8] = ["name", "characters", "font", "style", "size", "baseline", "hScale", "vScale"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -33,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}}]}",
|
||||
"{} the active document's composite fonts → {fonts: [{name, parts: {kanji, kana, punctuation, symbols, roman, numerals: {font, style, size: % of the type size, baseline: % of the type size (positive raises), hScale: %, vScale: %, scaleAtCenter?: bool}}, custom?: [{name, characters, font, style, size, baseline, hScale, vScale}]}]}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -42,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Composite Fonts…",
|
||||
["Type"],
|
||||
None,
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
"{fonts: [{name, parts: {kanji: {font, style?: \"Regular\", size?: % 10..400 = 100, baseline?: % -100..100 = 0}, kana?, punctuation?, symbols?, roman?, numerals?: {font, style?, size?, baseline?, hScale?, vScale?: % 10..400 = 100, scaleAtCenter?: bool = false}}, custom?: [{name, characters?: string = \"\", font?, style?, size?, baseline?, hScale?, vScale?}]}]} replace the active document's composite fonts (Type › Composite Fonts…'s OK), as one undo step, none when nothing changes. A composite font sets each class of character in its part's font: kanji (the base: ideographs, full-width letters and digits and anything no other class takes), kana (hiragana and katakana, both widths), punctuation (East Asian and full-width punctuation, quotes and dashes), symbols (arrows, math, shapes and other symbols), roman (half-width letters, their punctuation and spaces) and numerals (the digits 0 to 9); a part left out is the kanji part. size and baseline are percent of the type's size, hScale and vScale scale kana, roman and numerals only, and scaleAtCenter (kana only) scales them from the em box's center instead of the baseline. custom lists custom character sets: each sets the characters it lists in its own font, style, size, baseline and scales (values left out are the kanji part's), ahead of their class; a character two sets list is set by the later one. A set's name is trimmed and unique in the font in any case; its characters are each listed once, at most 8192, none a control character or past U+FFFF; at most 64 sets. Names are trimmed, unique in any case, at most 255 characters, and may not name an installed font; a part's font may not be a composite font; at most 256. Type set in a composite font names it as its family (text.setStyle {font: name}), and the font menus list composite fonts first. A font taken out stays named by its type, which then shows as missing → {fonts}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -51,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Composite Fonts",
|
||||
[],
|
||||
None,
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads; without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
"{path?: .vccomposite file, names?: [name] (default: all), fonts?: [{name, parts}] (as type.compositeFonts.set takes them)} write the active document's composite fonts (all, or those named, any case), or the fonts given, to a file type.compositeFonts.import reads (a file over 4 MB is refused); without path the file's text comes back as data → {path, count} | {data, count}",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -121,8 +128,8 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// copy of the Kanji part, and keys or values a part can't take refused.
|
||||
fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, "each font must be {name, parts}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name and parts")));
|
||||
if let Some(k) = o.keys().find(|k| !["name", "parts", "custom"].contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("unknown key `{k}`; a font takes name, parts and custom")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each font needs a name"))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
@@ -140,7 +147,17 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
serde_json::from_value(p.clone()).map(Some).map_err(|e| bad(c, format!("`{name}`: {}: {e}", class.key())))
|
||||
};
|
||||
let kanji = part(CharClass::Kanji)?.ok_or_else(|| bad(c, format!("`{name}`: give the kanji part")))?;
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji) };
|
||||
let custom = match o.get("custom") {
|
||||
None => Vec::new(),
|
||||
Some(Value::Array(sets)) => {
|
||||
if sets.len() > CUSTOM_SETS_MAX {
|
||||
return Err(bad(c, format!("`{name}`: a composite font keeps at most {CUSTOM_SETS_MAX} character sets")));
|
||||
}
|
||||
sets.iter().map(|s| parse_set(s, &name, &kanji, c)).collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(c, format!("`{name}`: custom must be a list of character sets"))),
|
||||
};
|
||||
let mut f = CompositeFont { name: name.clone(), parts: CompositeParts::all(kanji), custom };
|
||||
for class in CharClass::ALL.into_iter().skip(1) {
|
||||
if let Some(p) = part(class)? {
|
||||
*f.parts.get_mut(class) = p;
|
||||
@@ -150,6 +167,38 @@ fn parse_font(v: &Value, c: &str) -> Result<CompositeFont> {
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Custom character set `v` of composite font `font` from command parameters or a file: its name
|
||||
/// trimmed, the part values it leaves out those of `kanji`, and keys or values it can't take
|
||||
/// refused. [`CompositeFont::check`] checks its characters and values.
|
||||
fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<CustomCharSet> {
|
||||
let o = v.as_object().ok_or_else(|| bad(c, format!("`{font}`: each character set must be {{name, characters, font…}}")))?;
|
||||
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
|
||||
return Err(bad(c, format!("`{font}`: unknown key `{k}` in a character set")));
|
||||
}
|
||||
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, format!("`{font}`: each character set needs a name")))?;
|
||||
let name = CompositeFont::clean_name(raw)
|
||||
.ok_or_else(|| bad(c, format!("`{raw}` can't name a character set (1 to {COMPOSITE_NAME_MAX} characters, no control characters)")))?;
|
||||
let characters = match o.get("characters") {
|
||||
None => String::new(),
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(_) => return Err(bad(c, format!("`{font}`: `{name}`: characters must be a string"))),
|
||||
};
|
||||
// Checked here as well as by `check`, so a huge list is refused before it is copied again.
|
||||
if characters.chars().nth(CUSTOM_CHARS_MAX).is_some() {
|
||||
return Err(bad(c, format!("`{font}`: `{name}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters")));
|
||||
}
|
||||
let mut part = serde_json::to_value(kanji).map_err(|e| bad(c, e.to_string()))?;
|
||||
if let Some(p) = part.as_object_mut() {
|
||||
for k in &SET_KEYS[2..] {
|
||||
if let Some(given) = o.get(*k) {
|
||||
p.insert(k.to_string(), given.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let part: CompositePart = serde_json::from_value(part).map_err(|e| bad(c, format!("`{font}`: `{name}`: {e}")))?;
|
||||
Ok(CustomCharSet { name, characters, part })
|
||||
}
|
||||
|
||||
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
|
||||
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
|
||||
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
@@ -167,10 +216,10 @@ fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
for f in fonts {
|
||||
for class in CharClass::ALL {
|
||||
let font = &f.parts.get(class).font;
|
||||
let classes = CharClass::ALL.into_iter().map(|class| (class.key(), &f.parts.get(class).font));
|
||||
for (part, font) in classes.chain(f.custom.iter().map(|s| (s.name.as_str(), &s.part.font))) {
|
||||
if names.contains(&font.to_lowercase()) || db.composite_font(font).is_some() {
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, class.key())));
|
||||
return Err(bad(c, format!("`{}`: {} is set in `{font}`, a composite font", f.name, part)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +309,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut file = Map::new();
|
||||
file.insert("compositeFonts".into(), json!(fonts));
|
||||
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(C, e.to_string()))?;
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(bad(C, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
|
||||
}
|
||||
match path {
|
||||
Some(path) => {
|
||||
write_file(path, text.as_bytes())?;
|
||||
|
||||
@@ -856,3 +856,127 @@ fn composite_fonts_export_and_import() {
|
||||
assert!(s.execute("type.compositeFonts.export", &json!({"path": " "})).is_err());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `font(name)` with two custom character sets: "Marks" (x and A) in Inter at 150%, and "A only"
|
||||
/// (A) in Source Sans 3, which sets A since it comes later.
|
||||
fn font_with_sets(name: &str) -> Value {
|
||||
let mut v = font(name);
|
||||
v["custom"] = json!([
|
||||
{"name": " Marks ", "characters": "xA", "font": "Inter", "size": 150, "hScale": 90},
|
||||
{"name": "A only", "characters": "A"},
|
||||
]);
|
||||
v
|
||||
}
|
||||
|
||||
/// Custom character sets are set with the font as one undo step, take values they leave out from
|
||||
/// the Kanji part, set the characters they list ahead of their class (the later set winning), are
|
||||
/// saved with the document, and measure type again when they change.
|
||||
#[test]
|
||||
fn custom_character_sets_set_their_characters() {
|
||||
let mut s = session();
|
||||
let before = steps(&s);
|
||||
let r = s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(r["fonts"][0]["custom"][0]["name"], "Marks");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let f = s.doc().unwrap().doc.composite_fonts[0].clone();
|
||||
assert_eq!(f.custom.len(), 2);
|
||||
assert_eq!((f.custom[0].part.font.as_str(), f.custom[0].part.size, f.custom[0].part.h_scale), ("Inter", 150.0, 90.0));
|
||||
assert_eq!((f.custom[1].part.font.as_str(), f.custom[1].part.size), ("Source Sans 3", 100.0));
|
||||
// The same sets again change nothing.
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets")]})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
|
||||
assert_eq!(*back.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "xAB", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [id], "font": "CF Sets"})).unwrap();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let face = |family: &str| db.face(family, "Regular").unwrap().id();
|
||||
let lay = vectorcraft_text::layout(db, &text(&s, id));
|
||||
let fonts: Vec<u32> = lay.glyphs.iter().map(|g| g.font_id).collect();
|
||||
assert_eq!(fonts, [face("Inter"), face("Source Sans 3"), face("JetBrains Mono")]);
|
||||
// Taking x out of Marks sets it in its class's font again, measured in the same step.
|
||||
let wide = text(&s, id).cached_bounds.unwrap().width();
|
||||
let mut fewer = font_with_sets("CF Sets");
|
||||
fewer["custom"][0]["characters"] = json!("A");
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [fewer]})).unwrap();
|
||||
assert!(text(&s, id).cached_bounds.unwrap().width() < wide - 1.0);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!((text(&s, id).cached_bounds.unwrap().width() - wide).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Bad custom character sets are refused with an error and no undo step.
|
||||
#[test]
|
||||
fn bad_custom_character_sets_are_refused() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets Base")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let with = |f: &dyn Fn(&mut Value)| {
|
||||
let mut v = font_with_sets("CF Sets Refused");
|
||||
f(&mut v);
|
||||
json!({"fonts": [v]})
|
||||
};
|
||||
let many: String = (0x4E00u32..).filter_map(char::from_u32).take(8193).collect();
|
||||
let sets: Vec<Value> = (0..65).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
for bad in [
|
||||
with(&|v| v["custom"] = json!("Marks")),
|
||||
with(&|v| v["custom"] = Value::Null),
|
||||
with(&|v| v["custom"][0]["characters"] = Value::Null),
|
||||
with(&|v| v["custom"][0] = json!("Marks")),
|
||||
with(&|v| v["custom"][0]["name"] = json!(" ")),
|
||||
with(&|v| {
|
||||
v["custom"][0].as_object_mut().unwrap().remove("name");
|
||||
}),
|
||||
with(&|v| v["custom"][1]["name"] = json!("marks")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(["※"])),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("※※")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("A\n")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!("😀")),
|
||||
with(&|v| v["custom"][0]["characters"] = json!(many.clone())),
|
||||
with(&|v| v["custom"] = json!(sets.clone())),
|
||||
with(&|v| v["custom"][0]["size"] = json!(5)),
|
||||
with(&|v| v["custom"][0]["size"] = json!("50")),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(true)),
|
||||
with(&|v| v["custom"][0]["scaleAtCenter"] = json!(false)),
|
||||
with(&|v| v["custom"][0]["font"] = json!("")),
|
||||
with(&|v| v["custom"][0]["font"] = json!("CF Sets Base")),
|
||||
with(&|v| v["custom"][0]["width"] = json!(3)),
|
||||
] {
|
||||
let e = s.execute("type.compositeFonts.set", &bad);
|
||||
assert!(e.is_err(), "accepted {bad}");
|
||||
assert_eq!(names(&s), ["CF Sets Base"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
// A set without characters is kept: it sets nothing.
|
||||
let ok = with(&|v| v["custom"][0]["characters"] = json!(""));
|
||||
s.execute("type.compositeFonts.set", &ok).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.composite_fonts[0].custom[0].characters, "");
|
||||
}
|
||||
|
||||
/// Export writes the custom character sets and Import reads them back; a file whose set is bad is
|
||||
/// refused.
|
||||
#[test]
|
||||
fn custom_character_sets_export_and_import() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font_with_sets("CF Sets IO")]})).unwrap();
|
||||
let data = s.execute("type.compositeFonts.export", &json!({})).unwrap();
|
||||
let mut t = session();
|
||||
t.execute("type.compositeFonts.import", &json!({"data": data["data"]})).unwrap();
|
||||
assert_eq!(*t.doc().unwrap().doc.composite_fonts, *s.doc().unwrap().doc.composite_fonts);
|
||||
let text = data["data"].as_str().unwrap().replace("\"A only\"", "\"marks\"");
|
||||
let mut u = session();
|
||||
assert!(u.execute("type.compositeFonts.import", &json!({"data": text})).is_err());
|
||||
assert!(names(&u).is_empty());
|
||||
// Fonts whose file would be larger than Import reads are refused.
|
||||
let full: String = (0x4E00u32..).filter_map(char::from_u32).take(8192).collect();
|
||||
let sets: Vec<Value> = (0..64).map(|i| json!({"name": format!("S{i}"), "characters": full})).collect();
|
||||
let big: Vec<Value> = (0..3)
|
||||
.map(|i| {
|
||||
let mut f = font(&format!("CF Sets Big {i}"));
|
||||
f["custom"] = json!(sets);
|
||||
f
|
||||
})
|
||||
.collect();
|
||||
let e = s.execute("type.compositeFonts.export", &json!({"fonts": big})).unwrap_err();
|
||||
assert!(e.to_string().contains("4 MB"), "{e}");
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -660,6 +660,17 @@ pub struct ReadFile {
|
||||
path: Option<String>,
|
||||
/// What became of its linked files.
|
||||
links: Resolved,
|
||||
/// Whether the color management policies changed the document ([`apply_policies`]).
|
||||
policy_changed: bool,
|
||||
}
|
||||
|
||||
/// Edit › Color Settings: the color management policies keep, take off or convert from the
|
||||
/// profiles the document `loaded` holds is tagged with, and their notes go to its warnings →
|
||||
/// whether they changed the document.
|
||||
fn apply_policies(loaded: &mut Loaded) -> bool {
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies(&mut loaded.doc);
|
||||
loaded.warnings.extend(notes);
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -680,17 +691,35 @@ impl ReadFile {
|
||||
/// ([`super::importer`]).
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
|
||||
let opts = LoadOptions::from_params("document.open", p)?;
|
||||
let mut loaded = if opts.link_pages {
|
||||
linked_pages(name, bytes, path.as_deref(), &opts)?
|
||||
let (mut loaded, policy_changed) = if opts.link_pages {
|
||||
let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
|
||||
None => load_with(name, bytes, &opts)?,
|
||||
Some(plugin) => {
|
||||
let mut loaded = super::importer::load(name, bytes, &plugin, p)?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
(loaded, changed)
|
||||
}
|
||||
None => {
|
||||
// The color mode `p` asks for converts the colors after the policies did, through
|
||||
// the profiles the document keeps.
|
||||
let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?;
|
||||
let changed = apply_policies(&mut loaded);
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) {
|
||||
let doc = &mut loaded.doc;
|
||||
vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || {
|
||||
super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays);
|
||||
});
|
||||
}
|
||||
(loaded, changed)
|
||||
}
|
||||
}
|
||||
};
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut loaded.doc);
|
||||
Ok(ReadFile { loaded, opts, path, links })
|
||||
Ok(ReadFile { loaded, opts, path, links, policy_changed })
|
||||
}
|
||||
|
||||
/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents
|
||||
@@ -705,7 +734,7 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions
|
||||
/// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active
|
||||
/// document → `document.open`'s result.
|
||||
pub fn open_read(s: &mut Session, file: ReadFile) -> Result<Value> {
|
||||
open_loaded(s, file.loaded, file.links, file.path, &file.opts, false)
|
||||
open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)
|
||||
}
|
||||
|
||||
/// File → New from Template: any readable file (at `path`, if it is one: its links are looked for
|
||||
@@ -717,14 +746,24 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
|
||||
"only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first",
|
||||
));
|
||||
}
|
||||
let policy_changed = apply_policies(&mut loaded);
|
||||
let base = crate::cmd::links::LinkBase::file(path);
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
|
||||
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true)
|
||||
open_loaded(s, loaded, links, path.map(str::to_string), &LoadOptions::default(), true, policy_changed)
|
||||
}
|
||||
|
||||
/// Make a loaded file the new active document; `links` is what became of its linked files, and
|
||||
/// `opts` are the options it was read with.
|
||||
fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<String>, opts: &LoadOptions, as_template: bool) -> Result<Value> {
|
||||
/// Make a loaded file the new active document; `links` is what became of its linked files, `opts`
|
||||
/// are the options it was read with, and `policy_changed` says whether the color management
|
||||
/// policies changed it (it then opens with unsaved changes).
|
||||
fn open_loaded(
|
||||
s: &mut Session,
|
||||
loaded: Loaded,
|
||||
links: Resolved,
|
||||
path: Option<String>,
|
||||
opts: &LoadOptions,
|
||||
as_template: bool,
|
||||
policy_changed: bool,
|
||||
) -> Result<Value> {
|
||||
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } =
|
||||
loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
|
||||
@@ -765,6 +804,9 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
let converted = saves_back && converted && s.prefs.append_converted;
|
||||
let index = s.add_document(doc, path);
|
||||
let st = s.doc_mut()?;
|
||||
if policy_changed {
|
||||
st.mark_unsaved();
|
||||
}
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
st.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
|
||||
@@ -1239,14 +1239,23 @@ fn revert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let bytes = read_file(&path).map_err(|e| super::access::naming_in_error(e, &path))?;
|
||||
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &bytes)?.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs);
|
||||
doc.template = false;
|
||||
// The color management policies apply as when the file is opened.
|
||||
let (notes, policy_changed) = crate::cmd::colormgmt::apply_open_policies(&mut doc);
|
||||
// Back to the saved file: its recovery copy has nothing left to recover.
|
||||
let uid = s.doc()?.uid;
|
||||
crate::cmd::recovery::forget(s, uid);
|
||||
s.replace_document(index, doc);
|
||||
if policy_changed {
|
||||
s.doc_mut()?.mark_unsaved();
|
||||
}
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
s.doc_mut()?.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
Ok(json!({ "path": path }))
|
||||
let mut reply = json!({ "path": path });
|
||||
if !notes.is_empty() {
|
||||
reply["warnings"] = json!(notes);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
/// `file.formatOptions`: a writable format's options with the values Save would use.
|
||||
@@ -1345,7 +1354,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"New from Template…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+N"),
|
||||
"{path} or {name, dataBase64}: open a template (or any readable file) as a new untitled document → {index, title, format, warnings}",
|
||||
"{path} or {name, dataBase64}: open a template (or any readable file) as a new untitled document; the color management policies of edit.colorSettings apply as at document.open → {index, title, format, warnings (with the policies' notes)}",
|
||||
always,
|
||||
super::load::new_from_template
|
||||
),
|
||||
@@ -1354,7 +1363,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Revert",
|
||||
["File"],
|
||||
Some("F12"),
|
||||
"{confirmed?: bool (the app's own: it asks first, then runs the command with it)} discard the changes: reload the saved file into the same tab (history cleared; the tab keeps its place and view). Saved, modified documents only; if the file can't be read the document is left as it is → {path}. The app asks first (a confirm dialog) unless confirmed: true",
|
||||
"{confirmed?: bool (the app's own: it asks first, then runs the command with it)} discard the changes: reload the saved file into the same tab (history cleared; the tab keeps its place and view). Saved, modified documents only; if the file can't be read the document is left as it is → {path, warnings?: the notes of the color management policies of edit.colorSettings, which apply as at document.open}. The app asks first (a confirm dialog) unless confirmed: true",
|
||||
can_revert,
|
||||
revert
|
||||
),
|
||||
|
||||
@@ -202,6 +202,25 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque 16-bit CMYK TIFF's inks are rounded to the nearest 8-bit level, chunky and planar, and
|
||||
/// the stored image keeps its 16-bit samples.
|
||||
#[test]
|
||||
fn an_opaque_16_bit_cmyk_tiffs_inks_are_rounded_to_8_bits() {
|
||||
let c = vec![0u16, 200, 0x80FF, 0x8100, 65535, 32896];
|
||||
let m = vec![511u16, 65535, 0, 128, 129, 0];
|
||||
let none = vec![0u16; 6];
|
||||
let channels = [c, m, none.clone(), none];
|
||||
let want: Vec<u8> = [[0, 2, 0, 0], [1, 255, 0, 0], [128, 0, 0, 0], [128, 0, 0, 0], [255, 1, 0, 0], [128, 0, 0, 0]].concat();
|
||||
let chunky_bytes = hand_tiff(5, 16, &[], false, &channels);
|
||||
let chunky = raster_image(&chunky_bytes).unwrap();
|
||||
assert_eq!(chunky.blob.cmyk().map(|i| i.data), Some(want.clone()), "chunky: the inks");
|
||||
assert_eq!(*chunky.blob.bytes, chunky_bytes, "chunky: the file is stored as it is");
|
||||
let planar = raster_image(&hand_tiff(5, 16, &[], true, &channels)).unwrap();
|
||||
assert_eq!(planar.blob.cmyk().map(|i| i.data), Some(want), "planar: the inks");
|
||||
let stored = image::load_from_memory(&planar.blob.bytes).unwrap();
|
||||
assert_eq!(stored.color(), image::ColorType::Rgb16, "planar: the stored image keeps 16-bit samples");
|
||||
}
|
||||
|
||||
/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that
|
||||
/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two
|
||||
/// more samples than its ExtraSamples values count does too.
|
||||
|
||||
@@ -292,8 +292,22 @@ fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str>
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The key anchor ([`vectorcraft_doc::Selection::key_anchor`]) when Align and Distribute act on the
|
||||
/// selected anchor points and align to the key ([`align_to`]): the path and the point.
|
||||
fn key_anchor(s: &Session, p: &Value) -> Option<(NodeId, (usize, usize))> {
|
||||
(align_to(s, p) == Some("key")).then(|| s.doc().ok()?.selection.key_anchor).flatten()
|
||||
}
|
||||
|
||||
/// Where the key anchor of [`key_anchor`] is.
|
||||
fn key_anchor_point(s: &Session, p: &Value) -> Option<Point> {
|
||||
key_anchor(s, p)?;
|
||||
let st = s.doc().ok()?;
|
||||
st.selection.key_anchor_point(&st.doc)
|
||||
}
|
||||
|
||||
/// [`align`] of the selected anchor points (whole paths among them give all theirs): each point
|
||||
/// moves to the edge or centre of the points' bounds, or of the artboard with Align To Artboard.
|
||||
/// moves to the edge or centre of the points' bounds, of the artboard with Align To Artboard, or to
|
||||
/// the key anchor when aligning to it.
|
||||
fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&str>, Option<&str>)) -> Result<Value> {
|
||||
let targets = crate::cmd::path::anchor_targets(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
@@ -304,9 +318,10 @@ fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&st
|
||||
let Some(bounds) = pts.iter().skip(1).fold(pts.first().map(|q| Rect::from_points(*q, *q)), |b, q| b.map(|b| b.union_pt(*q))) else {
|
||||
return ok();
|
||||
};
|
||||
// shortcut: no key anchor yet, so Align To Key Object aligns to the points' bounds as Selection does
|
||||
// (or to a key guide).
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, Measure::default(), Some(bounds))?;
|
||||
// Aligning to the key, the points go to the key anchor, which stays where it is. Without one,
|
||||
// a key object aligns them to their bounds as Selection does (a key guide lines them up on it).
|
||||
let own = key_anchor_point(s, p).map_or(bounds, |k| Rect::from_points(k, k));
|
||||
let (r, along_x, along_y) = align_reference(s, p, ids, Measure::default(), Some(own))?;
|
||||
let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y));
|
||||
let target = |q: Point| {
|
||||
let x = match h {
|
||||
@@ -410,9 +425,10 @@ fn apply_spaced(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], horiz:
|
||||
|
||||
/// [`distribute`] and [`distribute_spacing`] of the selected anchor points (whole paths among them
|
||||
/// give all theirs): the points between the first and the last along the axis are spaced evenly,
|
||||
/// or `gap` apart from the first. A point has no size, so every Distribute option of an axis
|
||||
/// gives the same result.
|
||||
fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64>) -> Result<Value> {
|
||||
/// or `gap` apart from the first. With a gap and a key anchor `key` among them, the key anchor stays
|
||||
/// where it is and the others are placed `gap` apart outward from it, in their order along the
|
||||
/// axis. A point has no size, so every Distribute option of an axis gives the same result.
|
||||
fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64>, key: Option<(NodeId, (usize, usize))>) -> Result<Value> {
|
||||
let targets = crate::cmd::path::anchor_targets(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let along = |q: Point| if horiz { q.x } else { q.y };
|
||||
@@ -431,8 +447,11 @@ fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64
|
||||
return ok();
|
||||
}
|
||||
let step = gap.unwrap_or((last - first) / (pts.len() - 1) as f64);
|
||||
// The point the spacing starts from: the key anchor with a gap, else the first point.
|
||||
let (from, at_from) =
|
||||
gap.and(key).and_then(|(kid, (ksi, kai))| pts.iter().position(|q| (q.0, q.1, q.2) == (kid, ksi, kai))).map_or((0, first), |k| (k, pts[k].3));
|
||||
let moves: Vec<(NodeId, usize, usize, f64)> =
|
||||
pts.iter().enumerate().map(|(i, &(id, si, ai, at))| (id, si, ai, first + step * i as f64 - at)).collect();
|
||||
pts.iter().enumerate().map(|(i, &(id, si, ai, at))| (id, si, ai, at_from + step * (i as f64 - from as f64) - at)).collect();
|
||||
if moves.iter().all(|m| m.3.abs() <= 1e-9) {
|
||||
return ok();
|
||||
}
|
||||
@@ -466,11 +485,13 @@ pub(super) fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let m = measure(s, p, "object.distribute")?;
|
||||
let board = distribute_to(s, p, &ids, m, "object.distribute")?;
|
||||
let spacing = spacing(p, "object.distribute")?;
|
||||
// Anchor points selected with Direct Selection are distributed themselves, as Align aligns them.
|
||||
// Anchor points selected with Direct Selection are distributed themselves, as Align aligns them;
|
||||
// with a key anchor, a spacing places them from it.
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
let key = key_anchor(s, p);
|
||||
return match direction(p, "object.distribute")? {
|
||||
(None, None) => Err(bad("object.distribute", "give horizontal or vertical")),
|
||||
(h, _) => distribute_anchors(s, "Distribute", h.is_some(), None),
|
||||
(h, _) => distribute_anchors(s, "Distribute", h.is_some(), spacing.filter(|_| key.is_some()), key),
|
||||
};
|
||||
}
|
||||
let (horiz, key): (bool, fn(&Rect, bool) -> f64) = match direction(p, "object.distribute")? {
|
||||
@@ -543,7 +564,8 @@ pub(super) fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let board = distribute_to(s, p, &ids, m, "object.distributeSpacing")?;
|
||||
let spacing = spacing(p, "object.distributeSpacing")?;
|
||||
if !s.doc()?.selection.anchors.is_empty() {
|
||||
return distribute_anchors(s, "Distribute Spacing", horiz, spacing);
|
||||
let key = key_anchor(s, p);
|
||||
return distribute_anchors(s, "Distribute Spacing", horiz, spacing, key);
|
||||
}
|
||||
// The selected guides across the axis are spaced with the objects, as items with no size (#1597).
|
||||
let mut items = spaced_items(s, &ids, m, horiz)?;
|
||||
|
||||
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, or to the artboard (#1180)",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
@@ -269,7 +269,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key or with anchor points selected), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; not used with anchor points selected, or with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636)",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
can_distribute,
|
||||
distribute
|
||||
),
|
||||
@@ -278,7 +278,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute Spacing",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing and without anchor points selected, and with a key guide; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636)",
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
can_distribute,
|
||||
distribute_spacing
|
||||
),
|
||||
|
||||
@@ -81,11 +81,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cancel Key Object",
|
||||
[],
|
||||
None,
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection; any other id or guide is an error that leaves the key as it was → {key, guide?} (the resulting key object, or null; guide: the key guide, left out without one)",
|
||||
"{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put), anchor?: [subpath, anchor] with `id` the path (an anchor point selected with Direct Selection beside at least one other point becomes the key anchor: Align and Distribute move the other points relative to it and it stays put; select.anchors add or toggle of one point makes it the key anchor, as a Shift-click does)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection, or a key anchor that is deselected, deleted or left as the only selected point; any other id, guide or anchor is an error that leaves the key as it was → {key, guide?, keyAnchor?} (the resulting key object, or null; guide: the key guide, left out without one; keyAnchor: {id, anchor}, left out without one)",
|
||||
has_doc,
|
||||
key
|
||||
),
|
||||
cmd!("select.anchors", "Select Anchors", [], None, "{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}", has_doc, anchors),
|
||||
cmd!(
|
||||
"select.anchors",
|
||||
"Select Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, anchors: [[subpath, anchor]…], mode: \"set\"|\"add\"|\"toggle\"}; add or toggle that selects one point makes it the key anchor while another point is selected too (see select.key)",
|
||||
has_doc,
|
||||
anchors
|
||||
),
|
||||
cmd!(
|
||||
"select.segments",
|
||||
"Select Segments",
|
||||
@@ -670,6 +678,9 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(v) = p.get("anchor").filter(|v| !v.is_null()) {
|
||||
return key_anchor(s, id, guide, v);
|
||||
}
|
||||
if let Some(g) = guide {
|
||||
let sel = &s.doc()?.selection;
|
||||
if id.is_some() {
|
||||
@@ -684,6 +695,7 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.select(|_, sel| {
|
||||
sel.key = None;
|
||||
sel.key_anchor = None;
|
||||
sel.key_guide = Some(gid);
|
||||
})?;
|
||||
return key_result(s);
|
||||
@@ -700,17 +712,52 @@ fn key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.select(|_, sel| {
|
||||
sel.key = id;
|
||||
sel.key_guide = None;
|
||||
sel.key_anchor = None;
|
||||
})?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
/// `{key}`, with `guide` when a guide is the key.
|
||||
/// `select.key {id, anchor: [subpath, anchor]}`: anchor point `anchor` of path `id`, selected with
|
||||
/// Direct Selection beside at least one other point, becomes the key anchor
|
||||
/// ([`vectorcraft_doc::Selection::key_anchor`]).
|
||||
fn key_anchor(s: &mut Session, id: Option<NodeId>, guide: Option<usize>, v: &Value) -> Result<Value> {
|
||||
const C: &str = "select.key";
|
||||
let r = match checked_refs(Some(&Value::Array(vec![v.clone()])), C)?.as_slice() {
|
||||
[r] => *r,
|
||||
_ => return Err(bad(C, "`anchor` must be a [subpath, anchor] pair")),
|
||||
};
|
||||
if guide.is_some() {
|
||||
return Err(bad(C, "give `anchor` or `guide`, not both"));
|
||||
}
|
||||
let id = id.ok_or_else(|| bad(C, "`anchor` needs `id`, the path the point is on"))?;
|
||||
let st = s.doc()?;
|
||||
let sel = &st.selection;
|
||||
let on_path = st.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.subpaths.get(r.0).is_some_and(|sp| r.1 < sp.anchors.len()));
|
||||
if !on_path || sel.segments.contains_key(&id) || !sel.anchors.get(&id).is_some_and(|set| set.contains(&r)) {
|
||||
return Err(bad(C, format!("anchor [{}, {}] of object {id} is not a selected anchor point", r.0, r.1)));
|
||||
}
|
||||
// Check the new key on a copy first, so a request that fails leaves the key as it was.
|
||||
let mut trial = sel.clone();
|
||||
trial.key_anchor = Some((id, r));
|
||||
trial.prune(&st.doc);
|
||||
if trial.key_anchor.is_none() {
|
||||
return Err(bad(C, "select another anchor point to align to the key anchor"));
|
||||
}
|
||||
s.select(|_, sel| sel.key_anchor = Some((id, r)))?;
|
||||
key_result(s)
|
||||
}
|
||||
|
||||
/// `{key}`, with `guide` when a guide is the key and `keyAnchor` (`{id, anchor}`) when an anchor
|
||||
/// point is.
|
||||
fn key_result(s: &Session) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut out = json!({ "key": st.selection.key });
|
||||
if let Some(g) = st.selection.key_guide.and_then(|id| super::docmenu::guide_indexes(&st.doc, &[id]).first().copied()) {
|
||||
out["guide"] = json!(g);
|
||||
}
|
||||
if let Some((id, (si, ai))) = st.selection.key_anchor {
|
||||
out["keyAnchor"] = json!({ "id": id.0, "anchor": [si, ai] });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -843,15 +890,23 @@ fn anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if whole && let Some(path) = d.node(id).and_then(|n| n.path_data()) {
|
||||
e.extend(path.anchors().map(|(s, i, _)| (s, i)));
|
||||
}
|
||||
// One point that add or toggle selects becomes the key anchor (a Shift-click with Direct
|
||||
// Selection); `prune` drops it unless another point is selected too.
|
||||
let single = refs.len() == 1;
|
||||
let mut newest = None;
|
||||
for r in refs {
|
||||
if mode == "toggle" && e.contains(&r) {
|
||||
e.remove(&r);
|
||||
} else {
|
||||
e.insert(r);
|
||||
} else if e.insert(r) && single {
|
||||
newest = Some(r);
|
||||
}
|
||||
}
|
||||
if e.is_empty() {
|
||||
sel.remove(id);
|
||||
} else if mode != "set"
|
||||
&& let Some(r) = newest
|
||||
{
|
||||
sel.key_anchor = Some((id, r));
|
||||
}
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -245,39 +245,92 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"name": name, "kind": kind.label()}))
|
||||
}
|
||||
|
||||
/// Whether the object `id`, bound to the variable `name`, can stay bound to it once the variable
|
||||
/// is of `kind`: a text variable drives type that holds no other text variable, an image variable
|
||||
/// drives an image object, a graph variable drives a graph root, and a visibility variable drives
|
||||
/// any object. Locks and hidden layers don't count, as they don't unbind anything else either.
|
||||
fn keeps_binding(doc: &Document, id: NodeId, name: &str, kind: VariableKind) -> bool {
|
||||
let Some(n) = doc.node(id) else { return false };
|
||||
match kind {
|
||||
VariableKind::Text => {
|
||||
matches!(n.kind, NodeKind::Text(_))
|
||||
&& !doc.variables.bindings.get(&id).is_some_and(|bound| {
|
||||
doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && v.name != name && bound.contains(&v.name))
|
||||
})
|
||||
}
|
||||
VariableKind::Visibility => true,
|
||||
VariableKind::Image => matches!(n.kind, NodeKind::Image(_)),
|
||||
VariableKind::Graph => n.extras().graph.is_some(),
|
||||
VariableKind::Unknown => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Variable Options: rename a variable (`newName`), change its kind (`kind`), or both, in one undo
|
||||
/// step, carrying its bindings and its values in every data set to the new name. A kind change
|
||||
/// unbinds the objects that can't hold the new kind ([`keeps_binding`]) and drops the variable's
|
||||
/// value in every data set. A call that changes nothing adds no undo step.
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "variable.rename";
|
||||
let from = var_name(p, C)?;
|
||||
let to = named(p.get("newName").and_then(Value::as_str), "newName", C)?;
|
||||
let st = s.doc()?;
|
||||
if st.doc.variables.variable(&from).is_none() {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
// An omitted key is no change; a null, like any other value that isn't a name or a kind, is refused.
|
||||
let to = match p.get("newName") {
|
||||
None => None,
|
||||
Some(v) => Some(named(v.as_str(), "newName", C)?),
|
||||
};
|
||||
let kind = match p.get("kind") {
|
||||
None => None,
|
||||
Some(v) => Some(v.as_str().and_then(VariableKind::parse).ok_or_else(|| bad(C, "`kind` must be `text`, `visibility`, `image` or `graph`"))?),
|
||||
};
|
||||
if to.is_none() && kind.is_none() {
|
||||
return Err(bad(C, "missing `newName` or `kind`"));
|
||||
}
|
||||
if st.doc.variables.variable(&to).is_some() {
|
||||
let doc = &s.doc()?.doc;
|
||||
let Some(old) = doc.variables.variable(&from) else {
|
||||
return Err(bad(C, format!("no variable named `{from}`")));
|
||||
};
|
||||
let to = to.unwrap_or_else(|| from.clone());
|
||||
if to != from && doc.variables.variable(&to).is_some() {
|
||||
return Err(bad(C, format!("variable `{to}` already exists")));
|
||||
}
|
||||
s.edit("Rename Variable", |d, _| {
|
||||
let v = d.variables.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
let kind = kind.unwrap_or(old.kind);
|
||||
let retyped = kind != old.kind;
|
||||
let unbound: Vec<NodeId> =
|
||||
if retyped { doc.variables.objects_of(&from).into_iter().filter(|id| !keeps_binding(doc, *id, &from, kind)).collect() } else { Vec::new() };
|
||||
let label = if retyped { "Variable Options" } else { "Rename Variable" };
|
||||
let dropped = edit_variables(s, label, |vars| {
|
||||
let v = vars.variables.iter_mut().find(|v| v.name == from).ok_or_else(|| bad(C, format!("no variable named `{from}`")))?;
|
||||
v.name = to.clone();
|
||||
for bound in d.variables.bindings.values_mut() {
|
||||
v.kind = kind;
|
||||
for id in &unbound {
|
||||
vars.unbind(*id, &from);
|
||||
}
|
||||
for bound in vars.bindings.values_mut() {
|
||||
if bound.remove(&from) {
|
||||
bound.insert(to.clone());
|
||||
}
|
||||
}
|
||||
for ds in &mut d.variables.datasets {
|
||||
if let Some(value) = ds.values.remove(&from) {
|
||||
ds.values.insert(to.clone(), value);
|
||||
let mut dropped = 0;
|
||||
for ds in &mut vars.datasets {
|
||||
match ds.values.remove(&from) {
|
||||
// A rename alone carries every value, one that doesn't fit the kind included; a kind
|
||||
// change drops them all, as none was given for the new kind.
|
||||
Some(value) if !retyped => {
|
||||
ds.values.insert(to.clone(), value);
|
||||
}
|
||||
Some(_) => dropped += 1,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(dropped)
|
||||
})?;
|
||||
// The highlight names a variable, so it follows the rename rather than going stale.
|
||||
// The highlight names a variable, so it follows the rename rather than going stale. A call
|
||||
// that leaves the name as it was leaves the revision alone too.
|
||||
let st = s.doc_mut()?;
|
||||
if st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
if to != from && st.variables_highlight.as_deref() == Some(from.as_str()) {
|
||||
st.variables_highlight = Some(to.clone());
|
||||
st.revision += 1;
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(json!({"from": from, "name": to}))
|
||||
Ok(json!({"from": from, "name": to, "kind": kind.label(), "unbound": unbound.iter().map(|i| i.0).collect::<Vec<_>>(), "droppedValues": dropped}))
|
||||
}
|
||||
|
||||
/// Make Text / Visibility / Image / Graph Dynamic: define a variable of that kind and bind the
|
||||
@@ -837,7 +890,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rename Variable",
|
||||
["Window", "Variables"],
|
||||
None,
|
||||
"{name, newName} rename a variable, with its bindings and its values in every dataset; refused while the variables are locked",
|
||||
"{name, newName?, kind?: text|visibility|image|graph} Variable Options: rename a variable, with its bindings and its values in every dataset, change its kind, or both, in one undo step (none when the name and the kind are the ones it has). A kind change unbinds every object that can't hold the new kind (a text variable keeps type that has no other text variable, an image variable keeps image objects, a graph variable keeps graph roots, a visibility variable keeps every object) and drops the variable's values in every dataset; locked and hidden objects keep their binding when they can hold it. Needs `newName` or `kind`, and a null or empty one is refused; refused while the variables are locked → {from, name, kind, unbound: [id…], droppedValues}",
|
||||
variables_unlocked,
|
||||
rename
|
||||
),
|
||||
|
||||
@@ -308,6 +308,8 @@ fn document_base(s: &Session) -> Value {
|
||||
"key": st.selection.key.map(|k| k.0),
|
||||
// The ruler guide that is the key instead (`select.key {guide}`): an index into `guide.list`.
|
||||
"keyGuide": st.selection.key_guide.and_then(|id| crate::cmd::guide_indexes(d, &[id]).first().copied()),
|
||||
// The anchor point that is the key instead (`select.key {id, anchor}`): {id, anchor}.
|
||||
"keyAnchor": st.selection.key_anchor.map(|(id, (si, ai))| json!({"id": id.0, "anchor": [si, ai]})),
|
||||
"history": st.history.undo.iter().map(|h| h.label.clone()).collect::<Vec<_>>(),
|
||||
"redo": st.history.redo.iter().rev().map(|h| h.label.clone()).collect::<Vec<_>>(),
|
||||
"objects": d.node_count(),
|
||||
|
||||
@@ -245,6 +245,8 @@ pub struct Session {
|
||||
/// keyboard: those files, and the files they link to, are read under these roots, so a queue
|
||||
/// an agent loaded never reads beyond what it was given.
|
||||
pub(crate) place_queue_roots: Option<std::sync::Arc<file_access::AutomationRoots>>,
|
||||
/// How many times the place cursor has been loaded ([`Session::place_queue_loads`]).
|
||||
pub(crate) place_queue_loads: u64,
|
||||
/// While [`Session::import_image_read`] runs `clipboard.importImage`: the image read for it,
|
||||
/// which the command loads instead of reading `dataBase64`; `None` otherwise.
|
||||
pub(crate) image_hand_off: Option<cmd::clipboard::ImageRead>,
|
||||
|
||||
@@ -113,6 +113,7 @@ impl Session {
|
||||
place_hand_off: None,
|
||||
queue_hand_off: None,
|
||||
place_queue_roots: None,
|
||||
place_queue_loads: 0,
|
||||
image_hand_off: None,
|
||||
trace_hand_off: None,
|
||||
place_cursor_requests: false,
|
||||
|
||||
@@ -86,6 +86,7 @@ mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
mod journal;
|
||||
mod keyanchor;
|
||||
mod keyguide;
|
||||
mod knockout;
|
||||
mod labspots;
|
||||
|
||||
@@ -5341,8 +5341,9 @@ fn add_image(s: &mut Session, r: &vectorcraft_trace::Raster, xf: Affine) -> Node
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The traced paths of an Image Trace object: its children but the image and the seam fills.
|
||||
fn traced_paths(n: &Node) -> Vec<Arc<Node>> {
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).cloned().collect()
|
||||
n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5961,6 +5962,73 @@ fn image_trace_release_and_expand() {
|
||||
assert!(s.execute("imageTrace.release", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// Abutting with Fills: the strokes along the edges the paths share sit in a "Seam Fills" group
|
||||
/// under the paths, in the lower path's color, and stay under them through Expand by color.
|
||||
#[test]
|
||||
fn image_trace_abutting_seam_fills_sit_under_the_paths() {
|
||||
// Red beside blue, the edge between them anti-aliased.
|
||||
let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| {
|
||||
let share = (16.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
});
|
||||
let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned();
|
||||
let made = |method: &str, cmd: &str, by_color: bool| {
|
||||
let mut s = session();
|
||||
let img = add_image(&mut s, &art, Affine::scale(2.0));
|
||||
let params = json!({"mode": "color", "palette": "limited", "colors": 2, "method": method});
|
||||
let mut p = json!({ "params": params });
|
||||
if by_color {
|
||||
p["byColor"] = json!(true);
|
||||
}
|
||||
let r = s.execute(cmd, &p).unwrap();
|
||||
(s, img, r)
|
||||
};
|
||||
let (mut s, _, r) = made("abutting", "imageTrace.make", false);
|
||||
assert_eq!(r["paths"], 2, "{r}");
|
||||
let g = NodeId(r["id"].as_u64().unwrap());
|
||||
let n = node(&s, g);
|
||||
let kids = n.children().unwrap();
|
||||
assert_eq!(kids.len(), 4, "the image, the seam fills and two paths");
|
||||
assert!(matches!(kids[0].kind, NodeKind::Image(_)));
|
||||
let group = seams(&n).unwrap();
|
||||
assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths");
|
||||
let strokes = group.children().unwrap();
|
||||
assert_eq!(strokes.len(), 1);
|
||||
assert_eq!(strokes[0].appearance.fill_paint(), Paint::None);
|
||||
let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) };
|
||||
assert_eq!((layer.cap, layer.join, layer.width), (LineCap::Butt, LineJoin::Round, 3.0), "1.5 image pixels, the image scaled 2×");
|
||||
assert_eq!(layer.paint, kids[2].appearance.fill_paint(), "the lower path's color");
|
||||
// The stroke runs along the edge, from the image's top to its bottom.
|
||||
let bb = outline(&strokes[0]).0.bounds().unwrap();
|
||||
assert!((bb.center().x - 32.8).abs() < 1.0 && bb.y0.abs() < 1e-9 && (bb.y1 - 40.0).abs() < 1e-9, "{bb:?}");
|
||||
// Expand by color keeps the seam fills under the color groups, renamed too; Release gives the
|
||||
// image back.
|
||||
s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let n = node(&s, g);
|
||||
let names: Vec<_> = n.children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names.len(), 3, "{names:?}");
|
||||
assert_eq!(names[0], "Edges", "{names:?}");
|
||||
assert_eq!(n.children().unwrap()[0].id, group.id);
|
||||
let (mut s, img, _) = made("abutting", "imageTrace.make", false);
|
||||
assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]);
|
||||
// Make and Expand by color too.
|
||||
let (s, _, r) = made("abutting", "imageTrace.makeAndExpand", true);
|
||||
let n = node(&s, NodeId(r["id"].as_u64().unwrap()));
|
||||
assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Seam Fills"));
|
||||
// Overlapping paths are stacked: no seam fills.
|
||||
let (s, _, r) = made("overlapping", "imageTrace.make", false);
|
||||
assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none());
|
||||
// An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale.
|
||||
let mut s = session();
|
||||
add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5));
|
||||
let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap();
|
||||
let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap();
|
||||
let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") };
|
||||
assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width);
|
||||
}
|
||||
|
||||
/// Expand by color: each color's paths in a group of their own, named by the color, the groups
|
||||
/// stacked by the lowest path in each and the art drawn as before; Release to Layers then gives a
|
||||
/// sublayer for each color.
|
||||
@@ -5995,7 +6063,11 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
};
|
||||
let (flat, fg) = expand(false);
|
||||
let (mut s, g) = expand(true);
|
||||
let paths = node(&flat, fg).children().unwrap().clone();
|
||||
let kids = node(&flat, fg).children().unwrap().clone();
|
||||
// Abutting: the seam fills' group comes first, under every path, with byColor too.
|
||||
let seams = usize::from(method == "abutting");
|
||||
assert!(kids.iter().take(seams).all(|c| c.name.as_deref() == Some("Seam Fills")), "{method}");
|
||||
let paths = kids[seams..].to_vec();
|
||||
// Without byColor (the default) the paths sit in the trace's group, with no group of their own.
|
||||
assert!(paths.iter().all(|p| !matches!(p.kind, NodeKind::Group { .. })), "{method}");
|
||||
let (default, dg) = {
|
||||
@@ -6004,7 +6076,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
let r = s.execute("imageTrace.makeAndExpand", &json!({"params": params})).unwrap();
|
||||
(s, NodeId(r["id"].as_u64().unwrap()))
|
||||
};
|
||||
assert!(*node(&default, dg).children().unwrap() == paths, "{method}: byColor is false when not given");
|
||||
assert!(*node(&default, dg).children().unwrap() == kids, "{method}: byColor is false when not given");
|
||||
// The colors in the order they first come in, bottom to top.
|
||||
let mut order: Vec<String> = vec![];
|
||||
for p in &paths {
|
||||
@@ -6019,10 +6091,11 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
// Overlapping fills the ring whole and draws the field inside it above the ring: that path starts a second
|
||||
// group of the field's color, above the black one.
|
||||
let want: Vec<String> = if method == "overlapping" { order.iter().chain(order.first()).cloned().collect() } else { order.clone() };
|
||||
assert_eq!(names(&n), want, "{method}");
|
||||
assert_eq!(names(&n)[seams..], want, "{method}");
|
||||
assert!(n.children().unwrap().iter().take(seams).all(|c| *c == kids[0]), "{method}: the seam fills stay as they are");
|
||||
// Each group holds its color's paths, and in turn they are the paths of the trace without
|
||||
// byColor, in their order.
|
||||
let groups = n.children().unwrap();
|
||||
let groups = &n.children().unwrap()[seams..];
|
||||
for c in groups {
|
||||
assert!(matches!(c.kind, NodeKind::Group { .. }), "{method}");
|
||||
assert!(c.children().unwrap().iter().all(|m| Some(hex(m)) == c.name), "{method}: {:?}", c.name);
|
||||
@@ -6033,8 +6106,8 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
// Release to Layers: a sublayer for each color, in the same order.
|
||||
let r = s.execute("layer.releaseToLayers", &json!({"id": g.0})).unwrap();
|
||||
let subs = ids(&r);
|
||||
assert_eq!(subs.len(), want.len(), "{method}");
|
||||
for (sub, name) in subs.iter().zip(&want) {
|
||||
assert_eq!(subs.len(), seams + want.len(), "{method}");
|
||||
for (sub, name) in subs[seams..].iter().zip(&want) {
|
||||
let l = node(&s, *sub);
|
||||
assert!(matches!(l.kind, NodeKind::Layer { .. }), "{method}");
|
||||
assert_eq!(names(&l), std::slice::from_ref(name), "{method}");
|
||||
@@ -6051,7 +6124,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let mut got = names(&node(&s, g));
|
||||
got.sort();
|
||||
assert_eq!(got, ["#000000", "#c82832", "#f0f0dc"]);
|
||||
assert_eq!(got, ["#000000", "#c82832", "#f0f0dc", "Seam Fills"]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace"));
|
||||
|
||||
@@ -6086,7 +6159,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
});
|
||||
add_image(&mut s, &stripes, Affine::IDENTITY);
|
||||
let g = NodeId(s.execute("imageTrace.make", &json!({"params": grouped})).unwrap()["id"].as_u64().unwrap());
|
||||
assert!(node(&s, g).children().unwrap().iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })));
|
||||
assert!(traced_paths(&node(&s, g)).iter().all(|c| !matches!(c.kind, NodeKind::Group { .. })));
|
||||
let e = s.execute("imageTrace.expand", &json!({"byColor": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("Auto Grouping"), "{e}");
|
||||
assert_eq!(node(&s, g).name.as_deref(), Some("Image Trace"));
|
||||
@@ -6103,8 +6176,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
add_image(&mut s, &r, Affine::IDENTITY);
|
||||
let limited = json!({"mode": "color", "palette": "limited", "colors": 3});
|
||||
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
|
||||
let paths: Vec<(u64, String)> =
|
||||
node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| (c.id.0, hex(c))).collect();
|
||||
let paths: Vec<(u64, String)> = traced_paths(&node(&s, g)).iter().map(|c| (c.id.0, hex(c))).collect();
|
||||
let mut colors: Vec<&str> = paths.iter().map(|(_, h)| h.as_str()).collect();
|
||||
colors.sort();
|
||||
colors.dedup();
|
||||
@@ -6116,14 +6188,14 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let mut got = names(&node(&s, g));
|
||||
got.sort();
|
||||
assert_eq!(got, ["#28a03c", "Ink", "Sky 50%"]);
|
||||
assert_eq!(got, ["#28a03c", "Ink", "Seam Fills", "Sky 50%"]);
|
||||
// A swatch named as another color's #rrggbb still gets a group of its own.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "newName": "#28a03c"})).unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let mut got = names(&node(&s, g));
|
||||
got.sort();
|
||||
assert_eq!(got, ["#28a03c", "#28a03c", "Sky 50%"]);
|
||||
assert_eq!(got, ["#28a03c", "#28a03c", "Seam Fills", "Sky 50%"]);
|
||||
|
||||
// Gradient fills share one group, and a stroked line goes by its stroke.
|
||||
let ramp = vectorcraft_trace::Raster::from_fn(100, 60, |x, _| {
|
||||
@@ -6192,7 +6264,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
add_image(&mut s, &stripes, Affine::IDENTITY);
|
||||
let limited = json!({"mode": "color", "palette": "limited", "colors": 3, "method": "abutting"});
|
||||
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
|
||||
let paths: Vec<Arc<Node>> = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).cloned().collect();
|
||||
let paths = traced_paths(&node(&s, g));
|
||||
assert_eq!(paths.len(), 3);
|
||||
let (first, middle, last) = (&paths[0], &paths[1], &paths[2]);
|
||||
s.execute("paint.setFill", &json!({"ids": [last.id.0], "color": hex(first)})).unwrap();
|
||||
@@ -6220,7 +6292,7 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
for how in ["move", "transform", "shadow", "beside"] {
|
||||
let (flat, _) = edited(false, how);
|
||||
let (s, g) = edited(true, how);
|
||||
assert_eq!(names(&node(&s, g)).len(), 3, "{how}");
|
||||
assert_eq!(names(&node(&s, g)).len(), 4, "{how}: the seam fills and three colors");
|
||||
assert!(shot(&s) == shot(&flat), "{how}: the edited art changed");
|
||||
}
|
||||
|
||||
@@ -6230,14 +6302,14 @@ fn image_trace_expand_by_color_groups_each_colors_paths() {
|
||||
add_image(&mut s, &stripes, Affine::IDENTITY);
|
||||
let limited = json!({"mode": "color", "palette": "limited", "colors": 3});
|
||||
let g = NodeId(s.execute("imageTrace.make", &json!({"params": limited})).unwrap()["id"].as_u64().unwrap());
|
||||
let paths: Vec<u64> = node(&s, g).children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_))).map(|c| c.id.0).collect();
|
||||
let paths: Vec<u64> = traced_paths(&node(&s, g)).iter().map(|c| c.id.0).collect();
|
||||
assert_eq!(paths.len(), 3);
|
||||
s.execute("paint.setFill", &json!({"ids": [paths[0]], "swatch": "Sky", "tint": 50.1})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [paths[1], paths[2]], "swatch": "Sky", "tint": 50.4})).unwrap();
|
||||
s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap();
|
||||
let groups = node(&s, g).children().unwrap().clone();
|
||||
assert_eq!(names(&node(&s, g)), ["Sky 50%", "Sky 50%"]);
|
||||
assert_eq!(groups.iter().map(|c| c.children().unwrap().len()).collect::<Vec<_>>(), [1, 2]);
|
||||
assert_eq!(names(&node(&s, g)), ["Seam Fills", "Sky 50%", "Sky 50%"]);
|
||||
assert_eq!(groups.iter().skip(1).map(|c| c.children().unwrap().len()).collect::<Vec<_>>(), [1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -6289,7 +6361,7 @@ fn image_trace_make_and_expand_and_color_presets() {
|
||||
assert_eq!(res["paths"], 4);
|
||||
let g = node(&s, NodeId(res["id"].as_u64().unwrap()));
|
||||
assert!(g.name.is_none());
|
||||
assert_eq!(g.children().unwrap().len(), 4);
|
||||
assert_eq!(traced_paths(&g).len(), 4);
|
||||
assert!(s.execute("imageTrace.make", &json!({"preset": "No Such Preset"})).is_err());
|
||||
assert!(s.execute("imageTrace.make", &json!({"params": {"mode": "rainbow"}})).is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! #1636: the key anchor. With Direct Selection, the point a Shift-click adds to two or more
|
||||
//! selected anchor points is the key anchor; Align moves the other points to it, Distribute with a
|
||||
//! spacing places them from it, and it stays in place.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> NodeId {
|
||||
NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn pts(s: &Session, id: NodeId) -> Vec<(f64, f64)> {
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect()
|
||||
}
|
||||
|
||||
fn key_anchor(s: &Session) -> Option<(NodeId, (usize, usize))> {
|
||||
s.doc().unwrap().selection.key_anchor
|
||||
}
|
||||
|
||||
/// A Direct Selection click at (`x`, `y`), with Shift when `shift`.
|
||||
fn click(s: &mut Session, x: f64, y: f64, shift: bool) {
|
||||
let (v, mods) = (ViewInfo::default(), Mods { shift, ..Default::default() });
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), v).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shift_click_makes_the_key_anchor_and_a_plain_click_narrows_the_selection() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
s.select_tool("directSelection", ViewInfo::default()).unwrap();
|
||||
click(&mut s, 100.0, 40.0, false);
|
||||
assert_eq!(key_anchor(&s), None, "one point: no key anchor");
|
||||
click(&mut s, 150.0, 160.0, true);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))), "the point the Shift-click added");
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 1))), "the last point added");
|
||||
let inspect = s.execute("document.inspect", &json!({})).unwrap();
|
||||
assert_eq!(inspect["keyAnchor"], json!({"id": id.0, "anchor": [0, 1]}));
|
||||
// A Shift-click on the key anchor deselects it, and there is no key anchor.
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
click(&mut s, 200.0, 60.0, true);
|
||||
// A plain click on one of the selected points selects that point alone.
|
||||
click(&mut s, 100.0, 40.0, false);
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!(sel.anchors.get(&id).map(|a| a.iter().copied().collect::<Vec<_>>()), Some(vec![(0, 0)]));
|
||||
assert_eq!(sel.key_anchor, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_moves_the_other_points_to_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M100 40 L200 60 L150 160 L60 120 Z");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None, "a set selects no key anchor");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((id, (0, 2))));
|
||||
s.execute("object.align", &json!({"horizontal": "left"})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(150.0, 40.0), (150.0, 60.0), (150.0, 160.0), (60.0, 120.0)], "to the key anchor's x");
|
||||
s.execute("object.align", &json!({"vertical": "bottom"})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(150.0, 160.0), (150.0, 160.0), (150.0, 160.0), (60.0, 120.0)], "the key anchor stays");
|
||||
let steps = super::history(&s);
|
||||
s.execute("object.align", &json!({"vertical": "top"})).unwrap();
|
||||
assert_eq!(super::history(&s), steps, "nothing moved: no undo step");
|
||||
// `to: "selection"` aligns to the points' bounds instead.
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 3]], "mode": "add"})).unwrap();
|
||||
s.execute("object.align", &json!({"horizontal": "left", "to": "selection"})).unwrap();
|
||||
assert_eq!(pts(&s, id).iter().map(|p| p.0).collect::<Vec<_>>(), [60.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distribute_with_a_spacing_places_the_points_from_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let id = path(&mut s, "M10 10 L20 50 L100 30 L60 90");
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]], "mode": "toggle"})).unwrap();
|
||||
s.execute("object.distributeSpacing", &json!({"axis": "horizontal", "spacing": 20})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(60.0, 10.0), (80.0, 50.0), (100.0, 30.0), (60.0, 90.0)], "20 apart, outward from the key anchor");
|
||||
s.execute("object.distribute", &json!({"vertical": "center", "spacing": 5})).unwrap();
|
||||
assert_eq!(pts(&s, id), [(60.0, 25.0), (80.0, 35.0), (100.0, 30.0), (60.0, 90.0)], "in their order along y, from y 30");
|
||||
// Without a spacing, Distribute spaces the points between the first and the last.
|
||||
s.execute("object.distribute", &json!({"horizontal": "center"})).unwrap();
|
||||
assert_eq!(pts(&s, id)[1].0, 80.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_anchor_goes_when_it_can_no_longer_be_one() {
|
||||
let mut s = session();
|
||||
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
let b = path(&mut s, "M300 300 L400 300");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((b, (0, 1))), "a point of another path");
|
||||
assert!(s.doc().unwrap().selection.has_key());
|
||||
let r = s.execute("select.key", &json!({})).unwrap();
|
||||
assert_eq!((r["key"].clone(), r.get("keyAnchor")), (json!(null), None), "select.key {{}} cancels it");
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
let r = s.execute("select.key", &json!({"id": b.0, "anchor": [0, 1]})).unwrap();
|
||||
assert_eq!(r["keyAnchor"], json!({"id": b.0, "anchor": [0, 1]}));
|
||||
// Deleting the key anchor's path leaves no key anchor.
|
||||
s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
// A key object replaces a key anchor.
|
||||
let c = path(&mut s, "M500 500 L600 500");
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))), "beside a path selected whole");
|
||||
s.execute("select.key", &json!({"id": c.0})).unwrap();
|
||||
let sel = &s.doc().unwrap().selection;
|
||||
assert_eq!((sel.key, sel.key_anchor), (Some(c), None));
|
||||
// Type selected whole has no points to align, so one anchor beside it is no key anchor.
|
||||
let t = NodeId(s.execute("text.create", &json!({"x": 40, "y": 400, "size": 12, "text": "Key"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_key_rejects_an_anchor_that_cannot_be_the_key() {
|
||||
let mut s = session();
|
||||
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
|
||||
let err = |s: &mut Session, p: serde_json::Value| s.execute("select.key", &p).expect_err(&p.to_string()).to_string();
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("select another anchor point"), "the only point");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 9]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), None, "a point the path does not have");
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("select another anchor point"), "the only point on the path");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap();
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 2]})).contains("is not a selected anchor point"));
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 9]})).contains("is not a selected anchor point"));
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0]})).contains("expected [subpath, anchor]"));
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, -1]})).contains("non-negative integer"));
|
||||
assert!(err(&mut s, json!({"anchor": [0, 1]})).contains("needs `id`"));
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 1], "guide": 0})).contains("not both"));
|
||||
// A selected segment's ends are not selected anchor points.
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap();
|
||||
assert!(err(&mut s, json!({"id": a.0, "anchor": [0, 0]})).contains("is not a selected anchor point"));
|
||||
assert_eq!(key_anchor(&s), None, "the key stays as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_select_key_keeps_the_key_anchor() {
|
||||
let mut s = session();
|
||||
let a = path(&mut s, "M100 40 L200 60 L150 160 Z");
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 9]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))));
|
||||
// [0, 9] is in the selection but not on the path.
|
||||
let err = s.execute("select.key", &json!({"id": a.0, "anchor": [0, 9]})).expect_err("a point the path does not have").to_string();
|
||||
assert!(err.contains("is not a selected anchor point"), "{err}");
|
||||
assert_eq!(key_anchor(&s), Some((a, (0, 1))), "the key stays as it was");
|
||||
}
|
||||
@@ -126,6 +126,34 @@ fn spot_tints_print_their_percentage_of_the_plate() {
|
||||
assert!(pdf.contains("cs 0.4 scn"), "the tint is the Separation value");
|
||||
}
|
||||
|
||||
/// Extrude & Bevel (Classic) with Preserve Spot Colors keeps a spot fill's plate in PDF: the faces
|
||||
/// are tints of the Separation, and with the option off they are process colors.
|
||||
#[test]
|
||||
fn classic_3d_preserve_spot_colors_keeps_the_spot_plate_in_pdf() {
|
||||
let pdf = |preserve: bool| {
|
||||
let mut s = inks();
|
||||
rect(&mut s);
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Ink"}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
let params = json!({"preserveSpotColors": preserve, "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60});
|
||||
run(&mut s, "effect.apply", json!({"effect": "threeD.classicExtrude", "params": params}));
|
||||
let bytes =
|
||||
vectorcraft_pdf::export(doc(&s), &vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() })
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
};
|
||||
// The Separation values the page sets ("/CS1 cs 0.6 scn").
|
||||
let tints = |pdf: &str| -> std::collections::BTreeSet<String> {
|
||||
pdf.split(" scn").filter_map(|s| s.rsplit("cs ").next().filter(|t| t.parse::<f32>().is_ok()).map(str::to_string)).collect()
|
||||
};
|
||||
let kept = pdf(true);
|
||||
assert!(kept.contains("/Separation/Ink/DeviceCMYK"), "the faces print on the Ink plate");
|
||||
assert!(tints(&kept).len() > 1, "the highlight prints lighter tints of the ink: {:?}", tints(&kept));
|
||||
assert!(kept.contains("/Multiply"), "the shading is black multiplied over the ink");
|
||||
// Off, only a face left unshaded keeps the swatch, at its full tint.
|
||||
assert!(tints(&pdf(false)).len() <= 1, "without the option shaded faces are process mixes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_mode_shifts_tints_of_linked_colours_only() {
|
||||
let mut s = inks();
|
||||
|
||||
@@ -1063,6 +1063,110 @@ fn renaming_a_missing_name_onto_a_taken_one_reports_the_missing_name() {
|
||||
assert!(e.contains("no dataset named `Nope`"), "{e}");
|
||||
}
|
||||
|
||||
/// Variable Options changes a variable's kind: the objects that can't hold the new kind are
|
||||
/// unbound, the ones that can (locked ones too) stay bound, every value of the old kind goes, and
|
||||
/// the change is one undo step.
|
||||
#[test]
|
||||
fn variable_options_changes_the_kind_and_unbinds_what_cant_hold_it() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, "Alice");
|
||||
let r = rect(&mut s);
|
||||
let other = text(&mut s, "Held");
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Title", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Show", "ids": [t.0, r.0, other.0]})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Title", "ids": [other.0]})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "A", "values": {"Show": false, "Title": "Bob"}})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "B", "values": {"Show": true}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
|
||||
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).unwrap();
|
||||
// The rectangle isn't type, and the other type object already has the text variable Title.
|
||||
assert_eq!(v["unbound"], json!([r.0, other.0]));
|
||||
assert_eq!((v["name"].clone(), v["kind"].clone(), v["droppedValues"].clone()), (json!("Show"), json!("text"), json!(2)));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.objects_of("Show"), [t], "the locked type object stays bound");
|
||||
assert_eq!(vars.objects_of("Title"), [other], "the other variable keeps its binding");
|
||||
let sets = s.execute("dataset.list", &json!({})).unwrap();
|
||||
assert_eq!((sets["datasets"][0]["values"].clone(), sets["datasets"][1]["values"].clone()), (json!({"Title": {"text": "Bob"}}), json!({})));
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert_eq!(vars.variable("Show").map(|v| v.kind), Some(vectorcraft_doc::VariableKind::Visibility));
|
||||
assert_eq!(vars.objects_of("Show"), [t, r, other]);
|
||||
assert_eq!(vars.dataset("A").and_then(|d| d.values.get("Show")), Some(&vectorcraft_doc::DataValue::Visible(false)));
|
||||
|
||||
// A new name and a new kind together are one undo step, and every visibility binding stays.
|
||||
s.execute("variable.rename", &json!({"name": "Title", "newName": "Heading", "kind": "visibility"})).unwrap();
|
||||
assert_eq!(steps(&s), before + 1, "one step after the undo");
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert_eq!(
|
||||
(vars.variable("Heading").map(|v| v.kind), vars.objects_of("Heading")),
|
||||
(Some(vectorcraft_doc::VariableKind::Visibility), vec![other])
|
||||
);
|
||||
// An image variable keeps only image objects.
|
||||
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "image"})).unwrap();
|
||||
assert_eq!(v["unbound"], json!([t.0, r.0, other.0]));
|
||||
}
|
||||
|
||||
/// Variable Options with the variable's own name and kind changes nothing and adds no undo step;
|
||||
/// a bad kind, a taken name, no change asked for and locked variables are refused.
|
||||
#[test]
|
||||
fn variable_options_refuses_bad_params_and_skips_a_change_that_changes_nothing() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s);
|
||||
s.execute("variable.define", &json!({"name": "Show", "kind": "visibility"})).unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Show", "ids": [r.0]})).unwrap();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = steps(&s);
|
||||
for p in [
|
||||
json!({"name": "Show", "newName": "Show"}),
|
||||
json!({"name": "Show", "kind": "visibility"}),
|
||||
json!({"name": "Show", "newName": "Show", "kind": "visible"}),
|
||||
] {
|
||||
let v = s.execute("variable.rename", &p).unwrap();
|
||||
assert_eq!((v["unbound"].clone(), v["droppedValues"].clone()), (json!([]), json!(0)), "{p}");
|
||||
assert_eq!(steps(&s), before, "{p}: no undo step");
|
||||
}
|
||||
for (p, want) in [
|
||||
(json!({"name": "Show", "kind": "unknown"}), "`kind` must be"),
|
||||
(json!({"name": "Show", "kind": "number"}), "`kind` must be"),
|
||||
(json!({"name": "Show", "kind": 1}), "`kind` must be"),
|
||||
(json!({"name": "Show", "newName": "New", "kind": null}), "`kind` must be"),
|
||||
(json!({"name": "Show", "newName": null, "kind": "text"}), "missing `newName`"),
|
||||
(json!({"name": "Show", "newName": " ", "kind": "text"}), "missing `newName`"),
|
||||
(json!({"name": "Show"}), "missing `newName` or `kind`"),
|
||||
(json!({"name": "Show", "newName": "Other", "kind": "text"}), "already exists"),
|
||||
(json!({"name": "Ghost", "kind": "text"}), "no variable named `Ghost`"),
|
||||
] {
|
||||
let e = s.execute("variable.rename", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
// A rename alone carries a value that doesn't fit the kind, as a file may hold one.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc)
|
||||
.variables
|
||||
.datasets
|
||||
.push(vectorcraft_doc::DataSet { name: "Odd".into(), values: [("Show".to_string(), vectorcraft_doc::DataValue::Text("x".into()))].into() });
|
||||
s.execute("variable.rename", &json!({"name": "Show", "newName": "Shown"})).unwrap();
|
||||
let odd = s.doc().unwrap().doc.variables.dataset("Odd").and_then(|d| d.values.get("Shown")).cloned();
|
||||
assert_eq!(odd, Some(vectorcraft_doc::DataValue::Text("x".into())));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A kind change drops it, though it fits the new kind: nobody gave it for that kind.
|
||||
let v = s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).unwrap();
|
||||
assert_eq!(v["droppedValues"], 1);
|
||||
assert!(s.doc().unwrap().doc.variables.dataset("Odd").is_some_and(|d| d.values.is_empty()));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("variable.lock", &json!({"locked": true})).unwrap();
|
||||
assert!(s.execute("variable.rename", &json!({"name": "Show", "kind": "text"})).is_err(), "refused while the variables are locked");
|
||||
let vars = &s.doc().unwrap().doc.variables;
|
||||
assert_eq!((vars.variable("Show").map(|v| v.kind), vars.objects_of("Show")), (Some(vectorcraft_doc::VariableKind::Visibility), vec![r]));
|
||||
}
|
||||
|
||||
/// `dataset.set` is how a value changes after the row exists: replacing it must not need the
|
||||
/// dataset to be deleted and rebuilt (which loses its place in the list and the active one).
|
||||
#[test]
|
||||
|
||||
@@ -1262,6 +1262,14 @@ impl Session {
|
||||
/// is placed under ([`Session::place_queue_roots`]).
|
||||
fn note_place_queue_roots(&mut self) {
|
||||
self.place_queue_roots = crate::file_access::current();
|
||||
self.place_queue_loads = self.place_queue_loads.wrapping_add(1);
|
||||
}
|
||||
|
||||
/// How many times the place cursor has been loaded (`file.place.queue`, or a `queue` set on
|
||||
/// the Place tool): a frontend that keeps its own state about the loaded cursor compares it to
|
||||
/// tell a newer load.
|
||||
pub fn place_queue_loads(&self) -> u64 {
|
||||
self.place_queue_loads
|
||||
}
|
||||
|
||||
/// The automation roots the place cursor's files are placed under: those in force when it
|
||||
|
||||
@@ -823,7 +823,13 @@ fn color_settings_come_back_in_the_next_session() {
|
||||
a.execute("edit.colorSettings", &json!({})).unwrap();
|
||||
assert!(!file.exists(), "nothing to keep before the settings change");
|
||||
a.execute("edit.colorSettings", &json!({"rgb": loaded, "cmyk": cms::DEVICE_CMYK, "intent": "perceptual", "bpc": false})).unwrap();
|
||||
let chosen = cms::ColorSettings { rgb: loaded.into(), cmyk: cms::DEVICE_CMYK.into(), intent: cms::Intent::Perceptual, bpc: false };
|
||||
let chosen = cms::ColorSettings {
|
||||
rgb: loaded.into(),
|
||||
cmyk: cms::DEVICE_CMYK.into(),
|
||||
intent: cms::Intent::Perceptual,
|
||||
bpc: false,
|
||||
..cms::ColorSettings::default()
|
||||
};
|
||||
assert_eq!(cms::active_settings(), chosen);
|
||||
|
||||
// The next start begins with the defaults and without the loaded profile, which the profile
|
||||
@@ -865,3 +871,163 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
|
||||
assert!(!saved.bpc && saved.cmyk == cms::GENERIC_CMYK, "written over by the next change: {saved:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit › Color Settings' color management policies decide what opening a document tagged with
|
||||
/// profiles other than the working spaces does with them: Preserve Embedded Profiles keeps them,
|
||||
/// Off and Preserve Numbers take them off and keep the color numbers, and Convert to Working Space
|
||||
/// converts the colors into the working spaces, keeping how they look, and takes them off. A
|
||||
/// document a policy changed opens with unsaved changes, and the open reply names each profile.
|
||||
/// A profile that is the working space stays, and File › Revert and File › New from Template apply
|
||||
/// the policies too.
|
||||
#[test]
|
||||
fn color_management_policies_keep_take_off_or_convert_a_tagged_profile() {
|
||||
let _g = settings();
|
||||
let dir = fresh_dir("policies");
|
||||
let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] };
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let tagged = dir.join("tagged.vectorcraft");
|
||||
let mut s = session();
|
||||
let (blue, ink) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0));
|
||||
exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"}));
|
||||
exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}}));
|
||||
exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK}));
|
||||
// An artboard background, a character style's fill and a freeform gradient swatch, colors
|
||||
// outside the art.
|
||||
let paper = vectorcraft_color::Color::Rgb { r: 0.9, g: 0.8, b: 0.6 };
|
||||
let free = rect(&mut s, 40.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[free]);
|
||||
exec(&mut s, "paint.setFill", json!({"gradient": {"kind": "freeform"}}));
|
||||
exec(&mut s, "paint.freeform.setPoint", json!({"index": 0, "color": "#e6cc99", "stroke": false}));
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.artboards[0].color = Some(paper);
|
||||
let mut style = vectorcraft_doc::TextStyleDef { name: "Inked".into(), attrs: Default::default() };
|
||||
style.attrs.insert("fill".into(), serde_json::to_value(vectorcraft_color::Paint::solid(paper)).unwrap());
|
||||
d.char_styles.push(style);
|
||||
let paint = d.node(free).unwrap().appearance.fill().unwrap().paint.clone();
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Free".into(), paint, global: false, spot: false });
|
||||
}
|
||||
exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()}));
|
||||
let settings_colors = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let style = serde_json::from_value::<vectorcraft_color::Paint>(d.char_styles[0].attrs["fill"].clone()).unwrap();
|
||||
(d.artboards[0].color.unwrap(), style.color().unwrap())
|
||||
};
|
||||
// The first point of the freeform swatch and of the freeform fill.
|
||||
let free_points = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let first = |p: &vectorcraft_color::Paint| match p {
|
||||
vectorcraft_color::Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points[0].color),
|
||||
_ => None,
|
||||
};
|
||||
let swatch = d.swatches.iter().find(|w| w.name == "Free").and_then(|w| first(&w.paint)).unwrap();
|
||||
(swatch, first(&d.node(free).unwrap().appearance.fill().unwrap().paint).unwrap())
|
||||
};
|
||||
let (free0, _) = free_points(&s);
|
||||
let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap();
|
||||
let (blue0, ink0) = (fill(&s, blue), fill(&s, ink));
|
||||
let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), Some(cms::DEVICE_CMYK));
|
||||
let notes = |r: &serde_json::Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("profile")).count();
|
||||
// A session that opened the file under the policies, and the open reply.
|
||||
let open = |rgb: &str, cmyk: &str| {
|
||||
let mut s = session();
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": rgb, "cmykPolicy": cmyk}));
|
||||
let r = exec(&mut s, "document.open", json!({"path": tagged.to_str().unwrap()}));
|
||||
(r, s)
|
||||
};
|
||||
|
||||
let (r, kept) = open("preserveEmbedded", "preserveEmbedded");
|
||||
assert_eq!(doc_profiles(&kept.doc().unwrap().doc), (Some(cms::WIDE_GAMUT_RGB.into()), Some(cms::DEVICE_CMYK.into())));
|
||||
assert_eq!((fill(&kept, blue), fill(&kept, ink), notes(&r)), (blue0, ink0, 0));
|
||||
assert!(!kept.doc().unwrap().is_dirty());
|
||||
|
||||
for (rgb, cmyk) in [("off", "off"), ("off", "preserveNumbers")] {
|
||||
let (r, off) = open(rgb, cmyk);
|
||||
assert_eq!(doc_profiles(&off.doc().unwrap().doc), (None, None), "{cmyk}");
|
||||
assert_eq!((fill(&off, blue), fill(&off, ink), notes(&r)), (blue0, ink0, 2), "{cmyk}: the numbers stay");
|
||||
assert!(off.doc().unwrap().is_dirty(), "{cmyk}: the document changed");
|
||||
}
|
||||
|
||||
let (r, converted) = open("convert", "convert");
|
||||
assert_eq!(doc_profiles(&converted.doc().unwrap().doc), (None, None));
|
||||
assert_eq!(notes(&r), 2);
|
||||
let working = cms::working();
|
||||
let (blue1, ink1) = (fill(&converted, blue), fill(&converted, ink));
|
||||
assert!(blue1 != blue0 && ink1 != ink0, "the numbers change: {blue1:?} {ink1:?}");
|
||||
assert!(cms::delta_e2000(source.lab(&blue0), working.lab(&blue1)) < 1.0, "{blue0:?} → {blue1:?}");
|
||||
assert!(cms::delta_e2000(source.lab(&ink0), working.lab(&ink1)) < 3.0, "{ink0:?} → {ink1:?}");
|
||||
assert!(converted.doc().unwrap().is_dirty());
|
||||
let (board, styled) = settings_colors(&converted);
|
||||
assert_eq!(board, styled, "the artboard and the style convert alike");
|
||||
assert!(board != paper && cms::delta_e2000(source.lab(&paper), working.lab(&board)) < 1.0, "{paper:?} → {board:?}");
|
||||
assert_eq!(settings_colors(&kept), (paper, paper), "kept with the profile");
|
||||
let (swatch_point, fill_point) = free_points(&converted);
|
||||
assert_eq!(swatch_point, fill_point, "the freeform swatch and fill convert alike");
|
||||
assert!(swatch_point != free0 && cms::delta_e2000(source.lab(&free0), working.lab(&swatch_point)) < 1.0, "{free0:?} → {swatch_point:?}");
|
||||
|
||||
// A color mode asked for on open converts the colors the policy converted, through the working
|
||||
// spaces, also when the document in front draws through another profile.
|
||||
let mut s2 = session();
|
||||
exec(&mut s2, "edit.assignProfile", json!({"rgb": cms::DISPLAY_P3}));
|
||||
exec(&mut s2, "edit.colorSettings", json!({"rgbPolicy": "convert", "cmykPolicy": "convert"}));
|
||||
exec(&mut s2, "document.open", json!({"path": tagged.to_str().unwrap(), "colorMode": "cmyk"}));
|
||||
let intent = working.settings().intent;
|
||||
let want = working.convert(&blue1, cms::Model::Cmyk, intent);
|
||||
let got = fill(&s2, blue);
|
||||
assert!(cms::delta_e2000(working.lab(&want), working.lab(&got)) < 0.01, "{want:?} vs {got:?}");
|
||||
|
||||
// A profile that is the working space is kept whatever the policy.
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
|
||||
let (r, same) = open("off", "off");
|
||||
assert_eq!(doc_profiles(&same.doc().unwrap().doc), (Some(cms::WIDE_GAMUT_RGB.into()), None));
|
||||
assert_eq!(notes(&r), 1);
|
||||
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::SRGB}));
|
||||
|
||||
// File › Revert reads the file again under the policies.
|
||||
let (_, mut reverted) = open("preserveEmbedded", "preserveEmbedded");
|
||||
exec(&mut reverted, "paint.setFill", json!({"ids": [blue.0], "color": "#ff0000"}));
|
||||
exec(&mut reverted, "edit.colorSettings", json!({"cmykPolicy": "preserveNumbers"}));
|
||||
let r = exec(&mut reverted, "file.revert", json!({"confirmed": true}));
|
||||
assert_eq!(doc_profiles(&reverted.doc().unwrap().doc), (Some(cms::WIDE_GAMUT_RGB.into()), None));
|
||||
assert_eq!((fill(&reverted, blue), notes(&r)), (blue0, 1));
|
||||
|
||||
// File › New from Template applies the policies as opening does.
|
||||
let mut from_template = session();
|
||||
exec(&mut from_template, "edit.colorSettings", json!({"rgbPolicy": "convert", "cmykPolicy": "off"}));
|
||||
let r = exec(&mut from_template, "file.newFromTemplate", json!({"path": tagged.to_str().unwrap()}));
|
||||
assert_eq!(doc_profiles(&from_template.doc().unwrap().doc), (None, None));
|
||||
assert_eq!(notes(&r), 2);
|
||||
assert_eq!(fill(&from_template, ink), ink0, "Off keeps the CMYK numbers");
|
||||
let blue2 = fill(&from_template, blue);
|
||||
assert!(blue2 != blue0 && cms::delta_e2000(source.lab(&blue0), working.lab(&blue2)) < 1.0, "{blue0:?} → {blue2:?}");
|
||||
assert!(from_template.doc().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
/// The policies are checked, come back in the reply and in `Color Settings.json`, and a saved file
|
||||
/// that gives the RGB policy Preserve Numbers, a CMYK policy only, leaves the defaults.
|
||||
#[test]
|
||||
fn color_management_policies_are_checked_and_kept() {
|
||||
let _g = settings();
|
||||
let dir = fresh_dir("policies-kept");
|
||||
let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] };
|
||||
let file = dir.join("Color Settings.json");
|
||||
let mut s = session();
|
||||
s.attach_color_settings(file.clone());
|
||||
for bad in [json!({"rgbPolicy": "preserveNumbers"}), json!({"cmykPolicy": "keep"}), json!({"rgbPolicy": 1})] {
|
||||
assert!(s.execute("edit.colorSettings", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(!file.exists(), "a refused change keeps nothing");
|
||||
let r = exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert", "cmykPolicy": "preserveNumbers"}));
|
||||
assert_eq!((r["rgbPolicy"].as_str(), r["cmykPolicy"].as_str()), (Some("convert"), Some("preserveNumbers")));
|
||||
let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
|
||||
assert_eq!((saved.rgb_policy, saved.cmyk_policy), (cms::Policy::Convert, cms::Policy::PreserveNumbers));
|
||||
cms::set_active(&cms::ColorSettings::default()).unwrap();
|
||||
std::fs::write(
|
||||
&file,
|
||||
json!({"rgb": cms::SRGB, "cmyk": cms::GENERIC_CMYK, "intent": "relative", "bpc": true, "rgbPolicy": "preserveNumbers"}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut next = Session::new();
|
||||
next.attach_color_settings(file);
|
||||
assert_eq!(cms::active_settings(), cms::ColorSettings::default());
|
||||
}
|
||||
|
||||
@@ -274,6 +274,7 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
// The objects that may keep their effects in an art style, as they are before baking (not on
|
||||
// a large canvas, whose scale the styles' strokes and effects would need).
|
||||
let styled = writer::styled_objects(doc);
|
||||
let (symbol_styled, pattern_styled) = writer::styled_definitions(doc);
|
||||
let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles;
|
||||
let links = writer::style_links(doc);
|
||||
// Live geometry effects as their result, as the PDF part draws them.
|
||||
@@ -311,16 +312,14 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
w.reserve_swatch_gradients();
|
||||
if scale == 1.0 {
|
||||
w.styled = styled;
|
||||
(w.symbol_styled, w.pattern_styled) = (symbol_styled, pattern_styled);
|
||||
w.panel_styles();
|
||||
} else if !styled.is_empty() || own_styles || links > 0 {
|
||||
} else if !styled.is_empty() || !symbol_styled.is_empty() || !pattern_styled.is_empty() || own_styles || links > 0 {
|
||||
w.warnings.push(writer::LARGE_CANVAS_STYLES.to_string());
|
||||
}
|
||||
for layer in &doc.layers {
|
||||
w.layer(layer);
|
||||
}
|
||||
if scale == 1.0 {
|
||||
w.lost_links(links);
|
||||
}
|
||||
// The symbols no instance uses too; their art adds definitions.
|
||||
w.symbols();
|
||||
// The brushes, once the layers have said whether an object is written with one.
|
||||
@@ -328,6 +327,10 @@ fn export_within(doc: &Document, o: &AiEditingOptions, max_objects: usize) -> Re
|
||||
// The palette first: its gradient and pattern swatches add definitions.
|
||||
let mut palette = String::new();
|
||||
w.palette(&mut palette);
|
||||
// Once every definition is written: their opacity masks' art keeps links too.
|
||||
if scale == 1.0 {
|
||||
w.lost_links(links);
|
||||
}
|
||||
let library = w.variable_library();
|
||||
let first = to_art.transform_rect_bbox(board);
|
||||
let art = doc
|
||||
|
||||
@@ -6761,6 +6761,159 @@ fn hidden_and_nested_mask_art_keep_live_offset_path() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image 60 × 40 points at (10, 10) whose opacity mask, of `art`, doesn't clip.
|
||||
fn masked_image_node(doc: &mut Document, art: Node) -> Node {
|
||||
let im = image_node(doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([60.0, 0.0, 0.0, 40.0, 10.0, 10.0]), None);
|
||||
with_mask(im, art)
|
||||
}
|
||||
|
||||
/// A red square from (10, 10) to (70, 50) whose opacity mask, of `art`, doesn't clip.
|
||||
fn masked_square(doc: &mut Document, art: Node) -> Node {
|
||||
let sq = square(doc, Rect::new(10.0, 10.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
with_mask(sq, art)
|
||||
}
|
||||
|
||||
/// `n` with an opacity mask of `art` that doesn't clip.
|
||||
fn with_mask(mut n: Node, art: Node) -> Node {
|
||||
n.extras_mut().mask = Some(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true }.into());
|
||||
n
|
||||
}
|
||||
|
||||
/// The opacity mask art of the first object with one in `n`, its masks' art included.
|
||||
fn mask_art_in(n: &Node) -> Option<Arc<Node>> {
|
||||
let mut art = None;
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
if art.is_none()
|
||||
&& let Some(mask) = m.extras().mask.as_ref()
|
||||
{
|
||||
art = Some(mask.art.clone());
|
||||
}
|
||||
});
|
||||
art
|
||||
}
|
||||
|
||||
/// The Offset Path distance of `n`'s one live effect, when that is all it has.
|
||||
fn offset_path_of(n: &Node) -> Option<f64> {
|
||||
match n.appearance.effects.as_slice() {
|
||||
[e] if e.id == "path.offsetPath" => e.params.get("offset").and_then(serde_json::Value::as_f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity mask art of an image in a symbol's art keeps its live effects as an art style: a
|
||||
/// black path with Offset Path reads back with the effect live on the definition's mask art, when
|
||||
/// the mask's art root is hidden and when the symbol is used inside another symbol's art too, and
|
||||
/// both instances draw as they did.
|
||||
#[test]
|
||||
fn a_symbols_mask_art_keeps_live_offset_path() {
|
||||
let offset = fx("path.offsetPath", serde_json::json!({"offset": 6.0}));
|
||||
let made = |effects: Vec<vectorcraft_doc::Effect>, case: &str| {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut grown = styled_rect(&mut doc, "Grown", Rect::new(25.0, 20.0, 45.0, 40.0), solid(Color::BLACK), Paint::None, effects);
|
||||
grown.visible = case != "hidden";
|
||||
let im = masked_image_node(&mut doc, grown);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Picture".into(), art: Arc::new(im) });
|
||||
let mut used = "Picture";
|
||||
if case == "nested" {
|
||||
let inner = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Picture".into(), xf: Affine::translate((5.0, 0.0)) });
|
||||
let dot = square(&mut doc, Rect::new(0.0, 0.0, 4.0, 4.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let frame = group(&mut doc, vec![inner, dot], false);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Frame".into(), art: Arc::new(frame) });
|
||||
used = "Frame";
|
||||
}
|
||||
for x in [0.0, 100.0] {
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: used.into(), xf: Affine::translate((x, 20.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
}
|
||||
doc
|
||||
};
|
||||
for case in ["shown", "hidden", "nested"] {
|
||||
let doc = made(vec![offset.clone()], case);
|
||||
assert!(pixels_apart(&doc, &made(vec![], case)) > 0, "{case}: the effect draws nothing");
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{case}: {:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let picture = back.symbols.iter().find(|s| s.name == "Picture").unwrap_or_else(|| panic!("{case}: {:?}", back.symbols));
|
||||
let art = mask_art_in(&picture.art).unwrap_or_else(|| panic!("{case}: no masked image in {:?}", picture.art.kind));
|
||||
assert_eq!(offset_path_of(&art), Some(6.0), "{case}: {:?}", art.appearance.effects);
|
||||
assert_eq!(pixels_apart(&doc, &back), 0, "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacity mask art of a square in a pattern's tile keeps its live effects as an art style: the
|
||||
/// tile's black path with Offset Path reads back with the effect live, and the pattern fill draws as
|
||||
/// it did.
|
||||
#[test]
|
||||
fn a_pattern_tiles_mask_art_keeps_live_offset_path() {
|
||||
let offset = fx("path.offsetPath", serde_json::json!({"offset": 6.0}));
|
||||
let made = |effects: Vec<vectorcraft_doc::Effect>| {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let grown = styled_rect(&mut doc, "Grown", Rect::new(25.0, 20.0, 45.0, 40.0), solid(Color::BLACK), Paint::None, effects);
|
||||
let sq = masked_square(&mut doc, grown);
|
||||
let tile = Rect::new(0.0, 0.0, 80.0, 60.0);
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Masked", vec![Arc::new(sq)]) });
|
||||
let fill = Paint::Pattern { pattern: "Masked".into(), xf: Affine::IDENTITY };
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 160.0, 60.0)), Appearance::basic(fill, Paint::None, 0.0));
|
||||
doc.insert(Some(layer), usize::MAX, filled).unwrap();
|
||||
doc
|
||||
};
|
||||
let doc = made(vec![offset]);
|
||||
assert!(pixels_apart(&doc, &made(vec![])) > 0, "the effect draws nothing");
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::EFFECTS), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let def = back.pattern("Masked").unwrap_or_else(|| panic!("{:?}", back.patterns.iter().map(|p| &p.name).collect::<Vec<_>>()));
|
||||
let art = def.art.iter().find_map(|a| mask_art_in(a)).expect("a masked image in the tile");
|
||||
assert_eq!(offset_path_of(&art), Some(6.0), "{:?}", art.appearance.effects);
|
||||
assert_eq!(pixels_apart(&doc, &back), 0);
|
||||
}
|
||||
|
||||
/// Each opacity mask's art keeps its own art style: masks on the layers, in a symbol's art and in a
|
||||
/// pattern's tile with different Offset Path distances read back with their own distances, and a
|
||||
/// symbol's mask art with an effect no art style holds (Roughen) reads back without a live effect.
|
||||
#[test]
|
||||
fn mask_art_styles_stay_with_their_own_art() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let masked = |doc: &mut Document, effect: vectorcraft_doc::Effect| {
|
||||
let grown = styled_rect(doc, "Grown", Rect::new(25.0, 20.0, 45.0, 40.0), solid(Color::BLACK), Paint::None, vec![effect]);
|
||||
masked_image_node(doc, grown)
|
||||
};
|
||||
let by = |d: f64| fx("path.offsetPath", serde_json::json!({"offset": d}));
|
||||
let on_layer = masked(&mut doc, by(3.0));
|
||||
doc.insert(Some(layer), usize::MAX, on_layer).unwrap();
|
||||
let picture = masked(&mut doc, by(6.0));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Picture".into(), art: Arc::new(picture) });
|
||||
let rough = masked(&mut doc, fx("distort.roughen", serde_json::json!({"size": 6.0, "relative": false, "points": "corner"})));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Rough".into(), art: Arc::new(rough) });
|
||||
for (symbol, x) in [("Picture", 100.0), ("Rough", 120.0)] {
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: Affine::translate((x, 40.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
}
|
||||
let grown = styled_rect(&mut doc, "Grown", Rect::new(25.0, 20.0, 45.0, 40.0), solid(Color::BLACK), Paint::None, vec![by(9.0)]);
|
||||
let tile = masked_square(&mut doc, grown);
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef {
|
||||
tile: Rect::new(0.0, 0.0, 80.0, 60.0),
|
||||
..vectorcraft_doc::PatternDef::new("Masked", vec![Arc::new(tile)])
|
||||
});
|
||||
let fill = Paint::Pattern { pattern: "Masked".into(), xf: Affine::IDENTITY };
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 60.0, 80.0, 100.0)), Appearance::basic(fill, Paint::None, 0.0));
|
||||
doc.insert(Some(layer), usize::MAX, filled).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let symbol_art = |name: &str| {
|
||||
let s = back.symbols.iter().find(|s| s.name == name).unwrap_or_else(|| panic!("{name}: {:?}", back.symbols));
|
||||
mask_art_in(&s.art).unwrap_or_else(|| panic!("{name}: no masked image"))
|
||||
};
|
||||
assert_eq!(offset_path_of(&image_mask_art(&back)), Some(3.0));
|
||||
assert_eq!(offset_path_of(&symbol_art("Picture")), Some(6.0));
|
||||
let tile = back.pattern("Masked").and_then(|p| p.art.iter().find_map(|a| mask_art_in(a))).expect("a masked image in the tile");
|
||||
assert_eq!(offset_path_of(&tile), Some(9.0));
|
||||
let rough = symbol_art("Rough");
|
||||
assert!(rough.appearance.effects.is_empty(), "{:?}", rough.appearance.effects);
|
||||
}
|
||||
|
||||
/// A geometry effect on an opacity mask's art that no art style holds (Roughen) is applied to the
|
||||
/// art written, so the mask reads back drawing what it drew, but for pixels on its edge that the
|
||||
/// written points' rounding moves.
|
||||
@@ -6900,6 +7053,142 @@ fn a_filled_even_odd_object_is_written_as_its_drawn_look() {
|
||||
assert_eq!(n.extras().graphic_style, None);
|
||||
}
|
||||
|
||||
/// Links to graphic styles in pattern tiles count toward the warning about lost links: a tile's
|
||||
/// object linked to a style, which is written without its link, warns; and so does an object on the
|
||||
/// layers that loses its link while a tile's opacity mask art keeps its own.
|
||||
#[test]
|
||||
fn pattern_tile_style_links_count_toward_lost_links() {
|
||||
let made = |linked_tile: bool| {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let ap = Appearance::basic(black_fill(), Paint::None, 0.0);
|
||||
let mut g = vectorcraft_doc::GraphicStyle::new("Solid", ap.clone());
|
||||
g.id = 7;
|
||||
doc.graphic_styles.push(g);
|
||||
let mut linked = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(25.0, 20.0, 45.0, 40.0)), ap.clone());
|
||||
linked.extras_mut().graphic_style = Some(7);
|
||||
let art = if linked_tile {
|
||||
linked
|
||||
} else {
|
||||
// An even-odd path is written without its link (see the test above).
|
||||
let mut lost = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 140.0, 40.0)), ap);
|
||||
lost.extras_mut().graphic_style = Some(7);
|
||||
if let NodeKind::Path { rule, .. } = &mut lost.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
put(&mut doc, lost);
|
||||
masked_square(&mut doc, linked)
|
||||
};
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef {
|
||||
tile: Rect::new(0.0, 0.0, 80.0, 60.0),
|
||||
..vectorcraft_doc::PatternDef::new("Linked", vec![Arc::new(art)])
|
||||
});
|
||||
let fill = Paint::Pattern { pattern: "Linked".into(), xf: Affine::IDENTITY };
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 50.0, 80.0, 100.0)), Appearance::basic(fill, Paint::None, 0.0));
|
||||
put(&mut doc, filled);
|
||||
doc
|
||||
};
|
||||
for linked_tile in [true, false] {
|
||||
let doc = made(linked_tile);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{linked_tile}: {:?}", out.warnings);
|
||||
}
|
||||
let back = read_back(&made(false));
|
||||
let tile = back.pattern("Linked").and_then(|p| p.art.iter().find_map(|a| mask_art_in(a))).expect("a masked square in the tile");
|
||||
assert!(tile.extras().graphic_style.is_some(), "the tile's mask art keeps its link");
|
||||
}
|
||||
|
||||
/// An opacity mask's art linked to a graphic style reads back linked to it.
|
||||
#[test]
|
||||
fn opacity_mask_art_keeps_its_graphic_style_link() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let ap = Appearance::basic(black_fill(), Paint::None, 0.0);
|
||||
let mut g = vectorcraft_doc::GraphicStyle::new("Solid", ap.clone());
|
||||
g.id = 7;
|
||||
doc.graphic_styles.push(g);
|
||||
let mut linked = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(25.0, 20.0, 45.0, 40.0)), ap);
|
||||
linked.extras_mut().graphic_style = Some(7);
|
||||
let sq = masked_square(&mut doc, linked);
|
||||
put(&mut doc, sq);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let art = mask_art_in(&back.layers[0]).expect("a masked square");
|
||||
let id = art.extras().graphic_style.expect("the mask's art keeps its link");
|
||||
assert_eq!(back.graphic_style_by_id(id).map(|g| g.name.as_str()), Some("Solid"));
|
||||
}
|
||||
|
||||
/// A link written in a pattern tile's opacity mask art that the object limit then leaves out with
|
||||
/// the rest of the tile is not counted as kept: at every limit where the style isn't written, the
|
||||
/// export warns that the link is lost.
|
||||
#[test]
|
||||
fn mask_art_links_left_out_at_the_object_limit_are_reported_lost() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let ap = Appearance::basic(black_fill(), Paint::None, 0.0);
|
||||
let mut g = vectorcraft_doc::GraphicStyle::new("Solid", ap.clone());
|
||||
g.id = 7;
|
||||
doc.graphic_styles.push(g);
|
||||
let mut linked = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(25.0, 20.0, 45.0, 40.0)), ap);
|
||||
linked.extras_mut().graphic_style = Some(7);
|
||||
let mut art = vec![Arc::new(masked_square(&mut doc, linked))];
|
||||
for i in 0..6 {
|
||||
let x = 2.0 + 12.0 * f64::from(i);
|
||||
art.push(Arc::new(square(&mut doc, Rect::new(x, 52.0, x + 8.0, 58.0), Color::rgb(0.0, 0.0, 1.0))));
|
||||
}
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef { tile: Rect::new(0.0, 0.0, 80.0, 60.0), ..vectorcraft_doc::PatternDef::new("Linked", art) });
|
||||
let fill = Paint::Pattern { pattern: "Linked".into(), xf: Affine::IDENTITY };
|
||||
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 60.0)), Appearance::basic(fill, Paint::None, 0.0));
|
||||
doc.insert(Some(layer), usize::MAX, filled).unwrap();
|
||||
let mut left_out = 0;
|
||||
for max in 1..40 {
|
||||
let out = export_within(&doc, &opts(), max).unwrap();
|
||||
let text = String::from_utf8_lossy(&out.program).into_owned();
|
||||
if !text.contains("(Solid) XW") {
|
||||
left_out += 1;
|
||||
assert!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{max}: {:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
assert!(left_out > 0 && left_out < 39, "{left_out}");
|
||||
}
|
||||
|
||||
/// The links of opacity masks' art in a symbol no instance uses and in a pattern only the Swatches
|
||||
/// panel holds are written with those definitions, after the layers, and count as kept: no warning
|
||||
/// about lost links.
|
||||
#[test]
|
||||
fn mask_art_links_in_unused_definitions_are_not_reported_lost() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let ap = Appearance::basic(black_fill(), Paint::None, 0.0);
|
||||
let mut g = vectorcraft_doc::GraphicStyle::new("Solid", ap.clone());
|
||||
g.id = 7;
|
||||
doc.graphic_styles.push(g);
|
||||
let linked = |doc: &mut Document| {
|
||||
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(25.0, 20.0, 45.0, 40.0)), ap.clone());
|
||||
n.extras_mut().graphic_style = Some(7);
|
||||
masked_square(doc, n)
|
||||
};
|
||||
let unused = linked(&mut doc);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Unused".into(), art: Arc::new(unused) });
|
||||
let tile = linked(&mut doc);
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef {
|
||||
tile: Rect::new(0.0, 0.0, 80.0, 60.0),
|
||||
..vectorcraft_doc::PatternDef::new("Swatch only", vec![Arc::new(tile)])
|
||||
});
|
||||
let swatch = Swatch {
|
||||
name: "Swatch only".into(),
|
||||
paint: Paint::Pattern { pattern: "Swatch only".into(), xf: Affine::IDENTITY },
|
||||
global: false,
|
||||
spot: false,
|
||||
};
|
||||
swatches_plus(&mut doc, vec![swatch]);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::STYLE_LINKS), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Unused").and_then(|s| mask_art_in(&s.art)).expect("the unused symbol's mask art");
|
||||
assert!(symbol.extras().graphic_style.is_some(), "the symbol's mask art keeps its link");
|
||||
let tile = back.pattern("Swatch only").and_then(|p| p.art.iter().find_map(|a| mask_art_in(a))).expect("the swatch's mask art");
|
||||
assert!(tile.extras().graphic_style.is_some(), "the pattern's mask art keeps its link");
|
||||
}
|
||||
|
||||
/// A compound path filled by the non-zero rule keeps its effects, its gradient fill and its link to
|
||||
/// a graphic style.
|
||||
#[test]
|
||||
|
||||
@@ -28,7 +28,7 @@ mod variables;
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects};
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
|
||||
@@ -133,6 +133,10 @@ struct Charges {
|
||||
kept_objects: usize,
|
||||
kept_symbol_nodes: u64,
|
||||
left_out: usize,
|
||||
/// The objects written with the graphic style they are linked to, and those of them in the
|
||||
/// definitions written.
|
||||
links: usize,
|
||||
kept_links: usize,
|
||||
}
|
||||
|
||||
pub(super) struct Writer<'a> {
|
||||
@@ -171,6 +175,8 @@ pub(super) struct Writer<'a> {
|
||||
definition_objects: usize,
|
||||
/// The objects of symbol art in those definitions ([`Self::symbol_nodes`]).
|
||||
definition_symbol_nodes: u64,
|
||||
/// The objects in those definitions written with the graphic style they are linked to.
|
||||
definition_links: usize,
|
||||
/// The most objects written ([`Self::take_objects`]): the most the reader reads,
|
||||
/// [`crate::import::MAX_EDITING_OBJECTS`].
|
||||
pub(super) max_objects: usize,
|
||||
@@ -268,6 +274,12 @@ pub(super) struct Writer<'a> {
|
||||
/// The objects that may be written with an art style, as they were before baking, by id
|
||||
/// ([`styles::styled_objects`]).
|
||||
pub(super) styled: HashMap<NodeId, Arc<Node>>,
|
||||
/// The objects of the opacity masks' art in each symbol's art and each pattern's tile art that
|
||||
/// may be written with an art style, by the symbol's or pattern's name
|
||||
/// ([`styles::styled_definitions`]). [`Self::define_symbol`] and [`Self::define_pattern`] write
|
||||
/// a definition's art with its own as [`Self::styled`].
|
||||
pub(super) symbol_styled: HashMap<String, styles::StyledMap>,
|
||||
pub(super) pattern_styled: HashMap<String, styles::StyledMap>,
|
||||
/// The art styles written ([`styles`]).
|
||||
styles: styles::Styles,
|
||||
/// An object's drawn look is being written: no object in it is written with a style, and its
|
||||
@@ -365,6 +377,8 @@ impl<'a> Writer<'a> {
|
||||
symbol_scales: HashMap::new(),
|
||||
root_entries: None,
|
||||
styled: HashMap::new(),
|
||||
symbol_styled: HashMap::new(),
|
||||
pattern_styled: HashMap::new(),
|
||||
styles: styles::Styles::default(),
|
||||
in_look: false,
|
||||
drawn: 0,
|
||||
@@ -376,6 +390,7 @@ impl<'a> Writer<'a> {
|
||||
objects: 0,
|
||||
left_out: 0,
|
||||
definition_objects: 0,
|
||||
definition_links: 0,
|
||||
definition_symbol_nodes: 0,
|
||||
max_objects: crate::import::MAX_EDITING_OBJECTS,
|
||||
last_samples: None,
|
||||
@@ -434,6 +449,8 @@ impl<'a> Writer<'a> {
|
||||
kept_objects: self.definition_objects,
|
||||
kept_symbol_nodes: self.definition_symbol_nodes,
|
||||
left_out: self.left_out,
|
||||
links: self.styles.links_written,
|
||||
kept_links: self.definition_links,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,15 +464,18 @@ impl<'a> Writer<'a> {
|
||||
fn keep_since(&mut self, c: Charges) {
|
||||
self.definition_objects = c.kept_objects + (self.objects - c.objects);
|
||||
self.definition_symbol_nodes = c.kept_symbol_nodes + (self.symbol_nodes - c.symbol_nodes);
|
||||
self.definition_links = c.kept_links + (self.styles.links_written - c.links);
|
||||
}
|
||||
|
||||
/// Art written since `c` as `lines` is not used: the objects and symbol art charged since are
|
||||
/// given back, except those of the definitions written since, and the images `lines` marks
|
||||
/// Art written since `c` as `lines` is not used: the objects and symbol art charged since, and
|
||||
/// the objects counted as written with their graphic style, are given back, except those of the
|
||||
/// definitions written since, and the images `lines` marks
|
||||
/// are emptied (the others keep their indices). An image whose whole copy is among them is no
|
||||
/// longer written whole ([`Self::whole_images`]).
|
||||
fn give_back(&mut self, c: Charges, lines: &str) {
|
||||
self.objects = c.objects + (self.definition_objects - c.kept_objects);
|
||||
self.symbol_nodes = c.symbol_nodes + (self.definition_symbol_nodes - c.kept_symbol_nodes);
|
||||
self.styles.links_written = c.links + (self.definition_links - c.kept_links);
|
||||
let mut emptied = HashSet::new();
|
||||
for index in lines.split(PAYLOAD).skip(1).step_by(2) {
|
||||
if let Some((i, p)) = index.parse::<usize>().ok().and_then(|i| Some((i, self.payloads.get_mut(i)?))) {
|
||||
@@ -675,12 +695,11 @@ impl<'a> Writer<'a> {
|
||||
if n.extras().graph.is_some() && !self.in_look && graph.is_none() {
|
||||
self.warn(GRAPHS);
|
||||
}
|
||||
// On the layers or in an opacity mask's art, outside art cut to a clipping object: with its
|
||||
// art style, when it has one.
|
||||
// On the layers or in an opacity mask's art (a symbol's and a pattern tile's included),
|
||||
// outside art cut to a clipping object: with its art style, when it has one.
|
||||
if !self.in_look
|
||||
&& ((self.hidden == 0 && self.nest == 0) || self.mask_level == Some((self.hidden, self.nest)))
|
||||
&& ((self.hidden == 0 && self.nest == 0 && !self.in_symbol) || self.mask_level == Some((self.hidden, self.nest)))
|
||||
&& self.clip.is_none()
|
||||
&& !self.in_symbol
|
||||
&& let Some(orig) = self.styled.get(&n.id).cloned()
|
||||
&& self.check_left(&orig)
|
||||
&& let Some(name) = self.object_style(n, &orig)
|
||||
|
||||
@@ -483,6 +483,8 @@ impl Writer<'_> {
|
||||
self.gs.replace(Xy::OPAQUE),
|
||||
(self.clip.take(), std::mem::take(&mut self.shown)),
|
||||
self.block_end,
|
||||
// The tile's masks' objects are written with their art styles, those of no other art.
|
||||
(std::mem::replace(&mut self.styled, self.pattern_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()),
|
||||
);
|
||||
// `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its
|
||||
// placement is worked out in the tile's space turned y up.
|
||||
@@ -505,7 +507,15 @@ impl Writer<'_> {
|
||||
self.hidden -= 1;
|
||||
self.nest -= 1;
|
||||
let art;
|
||||
(art, (self.to_art, self.grad_space, self.canvas), self.state, self.gs, (self.clip, self.shown), self.block_end) = saved;
|
||||
(
|
||||
art,
|
||||
(self.to_art, self.grad_space, self.canvas),
|
||||
self.state,
|
||||
self.gs,
|
||||
(self.clip, self.shown),
|
||||
self.block_end,
|
||||
(self.styled, self.mask_level),
|
||||
) = saved;
|
||||
let art = std::mem::replace(&mut self.body, art);
|
||||
self.defining.pop();
|
||||
if self.left_out_since(before) {
|
||||
|
||||
@@ -26,7 +26,8 @@ pub(in crate::ai_editing) const PANEL_EMPTY: &str =
|
||||
pub(in crate::ai_editing) const WARPED_IMAGES: &str = "images with a Warp after the first 256 envelopes and images with a Warp are written as their drawn look, without their Warp, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are left out of the editing data for other apps on type, images, symbol instances, knockout shapes and other objects that aren't written with their graphic style";
|
||||
|
||||
/// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style.
|
||||
/// How many objects of `doc`'s layers, opacity masks, symbols and pattern tiles are linked to a
|
||||
/// graphic style.
|
||||
pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize {
|
||||
fn count(n: &Node) -> usize {
|
||||
// Ruler guides are not written as objects.
|
||||
@@ -37,7 +38,9 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize {
|
||||
let mask = n.extras().mask.as_ref().map_or(0, |m| count(&m.art));
|
||||
own + mask + n.children().map_or(0, |c| c.iter().map(|m| count(m)).sum())
|
||||
}
|
||||
doc.layers.iter().map(|l| count(l)).sum::<usize>() + doc.symbols.iter().map(|s| count(&s.art)).sum::<usize>()
|
||||
doc.layers.iter().map(|l| count(l)).sum::<usize>()
|
||||
+ doc.symbols.iter().map(|s| count(&s.art)).sum::<usize>()
|
||||
+ doc.patterns.iter().flat_map(|p| p.art.iter()).map(|a| count(a)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The objects of `doc`'s layers and of their opacity masks' art that may be written with an art
|
||||
@@ -48,10 +51,30 @@ pub(in crate::ai_editing) fn style_links(doc: &Document) -> usize {
|
||||
/// Knockout Shape (the reader takes an object's transparency
|
||||
/// from its look, which doesn't carry it). A group's members are paths, compound paths or such
|
||||
/// groups, none with effects or anything baking changes.
|
||||
pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap<NodeId, Arc<Node>> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut HashMap<NodeId, Arc<Node>>) {
|
||||
pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> StyledMap {
|
||||
styled_in(&doc.layers, true)
|
||||
}
|
||||
|
||||
/// The objects that may be written with an art style, by id, as they are before baking.
|
||||
pub(in crate::ai_editing) type StyledMap = HashMap<NodeId, Arc<Node>>;
|
||||
|
||||
/// The objects of the opacity masks' art in each of `doc`'s symbols' art, by symbol name, and in
|
||||
/// each of its patterns' tile art, by pattern name, that may be written with an art style, as
|
||||
/// [`styled_objects`] finds them on the layers. A definition's own objects outside its masks' art
|
||||
/// are not among them, and definitions without such objects are left out.
|
||||
pub(in crate::ai_editing) fn styled_definitions(doc: &Document) -> (HashMap<String, StyledMap>, HashMap<String, StyledMap>) {
|
||||
let symbols = doc.symbols.iter().map(|s| (s.name.clone(), styled_in(std::slice::from_ref(&s.art), false)));
|
||||
let patterns = doc.patterns.iter().map(|p| (p.name.clone(), styled_in(&p.art, false)));
|
||||
let kept = |(_, m): &(String, StyledMap)| !m.is_empty();
|
||||
(symbols.filter(kept).collect(), patterns.filter(kept).collect())
|
||||
}
|
||||
|
||||
/// The objects of `nodes` that may be written with an art style ([`styled_objects`]): with `own`,
|
||||
/// `nodes` and their members as well as their opacity masks' art, else their masks' art only.
|
||||
fn styled_in(nodes: &[Arc<Node>], own: bool) -> StyledMap {
|
||||
fn walk(nodes: &[Arc<Node>], own: bool, out: &mut StyledMap) {
|
||||
for n in nodes {
|
||||
if candidate(n) {
|
||||
if own && candidate(n) {
|
||||
out.insert(n.id, n.clone());
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref() {
|
||||
@@ -59,7 +82,7 @@ pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap<NodeId, A
|
||||
if !art.visible {
|
||||
Arc::make_mut(&mut art).visible = true;
|
||||
}
|
||||
walk(std::slice::from_ref(&art), out);
|
||||
walk(std::slice::from_ref(&art), true, out);
|
||||
}
|
||||
// A group's members are written with a style of their own only when the group is written
|
||||
// without one. Baking a container with effects of its own changes its members, which
|
||||
@@ -67,12 +90,12 @@ pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap<NodeId, A
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &n.kind
|
||||
&& !bakes_members(n)
|
||||
{
|
||||
walk(children, out);
|
||||
walk(children, own, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
walk(&doc.layers, &mut out);
|
||||
walk(nodes, own, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -613,7 +636,8 @@ impl Writer<'_> {
|
||||
let doc = self.doc;
|
||||
// A new document's styles are what the reader gives a file without a style list; they are
|
||||
// still written when an object is linked to one of them, so that it keeps its link.
|
||||
let linked = self.styled.values().any(|n| n.extras().graphic_style.is_some());
|
||||
let definitions = self.symbol_styled.values().chain(self.pattern_styled.values()).flat_map(HashMap::values);
|
||||
let linked = self.styled.values().chain(definitions).any(|n| n.extras().graphic_style.is_some());
|
||||
if !linked && doc.graphic_styles == Document::new(1.0, 1.0).graphic_styles {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -252,6 +252,8 @@ impl Writer<'_> {
|
||||
self.root_entries.take(),
|
||||
std::mem::take(&mut self.wrote_pattern),
|
||||
(std::mem::take(&mut self.wrote_fixed), std::mem::replace(&mut self.inner_scale, 1.0)),
|
||||
// The art's masks' objects are written with their art styles, those of no other art.
|
||||
(std::mem::replace(&mut self.styled, self.symbol_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()),
|
||||
);
|
||||
// Gradients' matrices and instances' matrices are written about the canvas point of art
|
||||
// space's origin, y up; `Bg` places a gradient on the art as it lies in the symbol's space.
|
||||
@@ -309,6 +311,7 @@ impl Writer<'_> {
|
||||
self.root_entries,
|
||||
self.wrote_pattern,
|
||||
(self.wrote_fixed, self.inner_scale),
|
||||
(self.styled, self.mask_level),
|
||||
) = saved;
|
||||
self.doc = page_doc;
|
||||
(self.in_look, self.drawn) = (in_look, drawn);
|
||||
|
||||
@@ -1399,8 +1399,9 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// Link the objects of `links` among `nodes` to their graphic style's id, each only when it has its
|
||||
/// style's appearance and transparency (`styles`, whose ids are 1, 2, … in order). A path, which
|
||||
/// has no contents, takes the style's contents slot.
|
||||
/// style's appearance and transparency (`styles`, whose ids are 1, 2, … in order), their members
|
||||
/// and their opacity masks' art included. A path, which has no contents, takes the style's contents
|
||||
/// slot.
|
||||
fn link_styles(nodes: &mut [Arc<Node>], links: &HashMap<NodeId, u32>, styles: &[GraphicStyle], depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
@@ -1419,6 +1420,11 @@ fn link_styles(nodes: &mut [Arc<Node>], links: &HashMap<NodeId, u32>, styles: &[
|
||||
n.extras_mut().graphic_style = Some(*id);
|
||||
}
|
||||
}
|
||||
if n.extras().mask.is_some()
|
||||
&& let Some(m) = Arc::make_mut(n).extras_mut().mask.as_mut()
|
||||
{
|
||||
link_styles(std::slice::from_mut(&mut m.art), links, styles, depth + 1);
|
||||
}
|
||||
if n.children().is_some_and(|c| !c.is_empty())
|
||||
&& let Some(c) = Arc::make_mut(n).children_mut()
|
||||
{
|
||||
|
||||
@@ -790,6 +790,41 @@ fn colorized_images_keep_their_color() {
|
||||
assert_eq!(out.warnings, [IMAGE_ALPHA]);
|
||||
}
|
||||
|
||||
/// The pieces of a colorized warped image work out the image's coverage once, and an image with
|
||||
/// other data works out its own: a black and white image's pieces are written as image masks
|
||||
/// in its color, and a gray image's pieces with its color in their pixels.
|
||||
#[test]
|
||||
fn the_pieces_of_a_colorized_warped_image_work_out_its_coverage_once() {
|
||||
// GUARDS: each piece of a colorized warped image decoded the image again for its coverage.
|
||||
let mut doc = Document::new(400.0, 200.0);
|
||||
doc.layers.clear();
|
||||
let layer = doc.add_layer(Some("Art"));
|
||||
let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
|
||||
let checks: Vec<u8> = (0..16 * 16).map(|i| if (i % 16 + i / 16) % 2 == 0 { 0 } else { 255 }).collect();
|
||||
let ramp: Vec<u8> = (0..16 * 16).map(|i| (i % 16 * 16) as u8).collect();
|
||||
for (gray, x) in [(checks, 10.0), (ramp, 210.0)] {
|
||||
let photo = colorized_image(&mut doc, (16, 16), gray, &paint, (x, 10.0));
|
||||
let NodeKind::Image(im) = &photo.kind else { panic!("{:?}", photo.kind) };
|
||||
let bend = move |p: vectorcraft_geom::Point| vectorcraft_geom::Point::new(p.x, p.y + 8.0 * ((p.x - x) / 160.0 * std::f64::consts::PI).sin());
|
||||
let warped = vectorcraft_doc::live::mesh_warp_image(&photo, im, &bend, 4, false, false);
|
||||
doc.insert(Some(layer), usize::MAX, warped).unwrap();
|
||||
}
|
||||
super::writer::COVERAGE_RUNS.with(|n| n.set(0));
|
||||
let out = write(&doc);
|
||||
assert_eq!(super::writer::COVERAGE_RUNS.with(std::cell::Cell::get), 2, "once for each image");
|
||||
let text = String::from_utf8(out.bytes).unwrap();
|
||||
let images = rasters(&text);
|
||||
assert_eq!(images.len(), 64, "32 pieces of each image");
|
||||
let xi = |piece: &Vec<&str>| piece.iter().find(|l| l.ends_with(" XI")).map(|l| l.to_string()).unwrap_or_default();
|
||||
assert!(images[..32].iter().all(|p| xi(p).ends_with(" 1 1 0 0 0 1 XI")), "{:?}", images[..32].iter().map(xi).collect::<Vec<_>>());
|
||||
assert!(images[32..].iter().all(|p| xi(p).ends_with(" 8 3 0 0 0 0 XI")), "{:?}", images[32..].iter().map(xi).collect::<Vec<_>>());
|
||||
// The first piece holds the whole image: each row of 16 pixels in two bytes, its black pixels 0 bits.
|
||||
assert!(xi(&images[0]).ends_with(" ] 0 0 16 16 16 16 1 1 0 0 0 1 XI"), "{}", xi(&images[0]));
|
||||
let data: Vec<&str> = images[0].iter().filter_map(|l| l.strip_prefix('%')).filter(|l| l.bytes().all(|b| b.is_ascii_hexdigit())).collect();
|
||||
assert_eq!(data.concat(), "5555AAAA".repeat(8));
|
||||
assert_eq!(out.warnings, [IMAGE_ALPHA]);
|
||||
}
|
||||
|
||||
/// An image mask is only for a colorized image the writer draws as the document does: not one
|
||||
/// with an opacity mask turned on, and not one with more pixels than the writer writes.
|
||||
#[test]
|
||||
|
||||
@@ -11,6 +11,15 @@ use super::{
|
||||
};
|
||||
use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`Writer::coverage`] has worked out an image's coverage on this thread.
|
||||
pub(super) static COVERAGE_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel.
|
||||
type Coverage = (u32, u32, Arc<Vec<u8>>);
|
||||
|
||||
pub(super) struct Writer<'a> {
|
||||
doc: &'a Document,
|
||||
/// The document → art space.
|
||||
@@ -50,6 +59,9 @@ pub(super) struct Writer<'a> {
|
||||
/// The image decoded last (`None` when it can't be): the pieces of a warped image, which follow
|
||||
/// one another, decode it once.
|
||||
last_image: Option<(ImageBlob, Option<Arc<image::DynamicImage>>)>,
|
||||
/// The coverage of [`Self::last_image`] once a colorized piece of it asked for it (`Some(None)`
|
||||
/// when it can't be worked out), so the pieces of a colorized warped image work it out once.
|
||||
last_coverage: Option<Option<Coverage>>,
|
||||
/// The images written whole so far, by the address of their data (which each entry keeps).
|
||||
whole_images: std::collections::HashMap<usize, Arc<Vec<u8>>>,
|
||||
/// Writing a graph's art with its records: a graph inside it is written as its art.
|
||||
@@ -79,6 +91,7 @@ impl<'a> Writer<'a> {
|
||||
kumi: false,
|
||||
clips: vec![],
|
||||
last_image: None,
|
||||
last_coverage: None,
|
||||
whole_images: std::collections::HashMap::new(),
|
||||
in_graph: false,
|
||||
}
|
||||
@@ -1104,7 +1117,7 @@ impl<'a> Writer<'a> {
|
||||
let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h));
|
||||
let coverage = match colorize {
|
||||
Some(paint) => {
|
||||
let Some((_, _, coverage)) = ImageBlob::coverage(blob).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else {
|
||||
let Some((_, _, coverage)) = self.coverage(blob).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else {
|
||||
self.warn(UNDECODED);
|
||||
return;
|
||||
};
|
||||
@@ -1172,9 +1185,26 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
let img = image::load_from_memory(&blob.bytes).ok().map(Arc::new);
|
||||
self.last_image = Some((blob.clone(), img.clone()));
|
||||
self.last_coverage = None;
|
||||
img
|
||||
}
|
||||
|
||||
/// The coverage of `blob` ([`ImageBlob::coverage`]), worked out once for images that follow one
|
||||
/// another with the same data, as [`Self::decoded`] decodes them.
|
||||
fn coverage(&mut self, blob: &ImageBlob) -> Option<Coverage> {
|
||||
let last = self.last_image.as_ref().is_some_and(|(last, _)| Arc::ptr_eq(&last.bytes, &blob.bytes) && last.mime == blob.mime);
|
||||
if last && let Some(coverage) = &self.last_coverage {
|
||||
return coverage.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
COVERAGE_RUNS.with(|n| n.set(n.get() + 1));
|
||||
let coverage = ImageBlob::coverage(blob).map(|(w, h, c)| (w, h, Arc::new(c)));
|
||||
if last {
|
||||
self.last_coverage = Some(coverage.clone());
|
||||
}
|
||||
coverage
|
||||
}
|
||||
|
||||
/// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]`
|
||||
/// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`]
|
||||
/// digits, `%AI5_EndRaster`, then `F`.
|
||||
|
||||
@@ -612,6 +612,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"Shift+Tab",
|
||||
"{} show/hide the dock and the floating panels (hiding them closes a panel popped out of the icon column), leaving the toolbar and the Control bar as they are; returns whether the panels show",
|
||||
),
|
||||
(
|
||||
"window.panels.peek",
|
||||
"Show Hidden Panels at Edge",
|
||||
"",
|
||||
"{side: left|right|null} while Tab or Shift+Tab hides the panels, show the docked panels on that side of the canvas over its edge, as resting the pointer on that edge of the window for 0.3 s does; they hide again 0.3 s after the pointer moves away from them, and null hides them now. Floating panels, the toolbar and the Control bar stay hidden, and Tab or Shift+Tab shows the panels for good. Fails and changes nothing while the panels show, in Presentation Mode, for any other side, or when no panel is docked on that side; returns the side shown or null",
|
||||
),
|
||||
(
|
||||
"window.panel",
|
||||
"Show Panel",
|
||||
|
||||
@@ -529,18 +529,18 @@ impl Exporter<'_> {
|
||||
/// their own.
|
||||
fn warn_spot_image(&mut self, g: &vectorcraft_color::GradientPaint) {
|
||||
let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points();
|
||||
let prints_spot = || g.gradient.stops.iter().zip(g.gradient.drawn_stops()).any(|(s, d)| self.printed_spot(s, d).is_some());
|
||||
if from_stops && prints_spot() {
|
||||
if from_stops && self.prints_spot(&g.gradient) {
|
||||
self.warn(
|
||||
"spot colors in gradients exported as images (freeform or dithered gradients, ones mixed around the hue wheel, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is a stop of `g` linked to a spot swatch?
|
||||
fn has_spot_stop(&self, g: &vectorcraft_color::Gradient) -> bool {
|
||||
let doc = self.doc;
|
||||
g.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot)))
|
||||
/// Does a stop of `g` print a spot swatch ([`Self::printed_spot`]): color something that draws
|
||||
/// ([`vectorcraft_color::Gradient::drawn_stops`]) at a tint above 0 or with process plates? A
|
||||
/// stop linked to a spot swatch that colors nothing adds no spot ink.
|
||||
fn prints_spot(&self, g: &vectorcraft_color::Gradient) -> bool {
|
||||
g.stops.iter().zip(g.drawn_stops()).any(|(s, d)| self.printed_spot(s, d).is_some())
|
||||
}
|
||||
|
||||
/// Draw diamond gradient `g`, placed on `bounds`, over `area` (inside the current clip) as four
|
||||
@@ -638,8 +638,8 @@ impl Exporter<'_> {
|
||||
/// scaled type gets its pixels too): a freeform gradient's colour field (at most
|
||||
/// [`MAX_FIELD_PX`] a side), or a linear, radial, conic or diamond gradient (at most [`MAX_GRADIENT_PX`] a side),
|
||||
/// with dither's noise when it paints a fill (`fill`). A linear or radial gradient whose stops
|
||||
/// are all CMYK and not linked to a spot swatch is a CMYK image, unless its Perceptual curve
|
||||
/// has too many stops; any other is an RGB image.
|
||||
/// are all CMYK and none of which prints a spot swatch ([`Self::prints_spot`]) is a CMYK image,
|
||||
/// unless its Perceptual curve has too many stops; any other is an RGB image.
|
||||
pub(super) fn field_image(&mut self, s: &mut Surface, g: &vectorcraft_color::GradientPaint, bounds: Rect, area: Rect, fill: bool) {
|
||||
use vectorcraft_color::cms::Model;
|
||||
use vectorcraft_color::freeform::{painted_box, spread_scale};
|
||||
@@ -667,7 +667,7 @@ impl Exporter<'_> {
|
||||
} else if !freeform {
|
||||
self.warn("linear and radial gradients drawn as pixels are exported as images");
|
||||
}
|
||||
let ramp_inks = if freeform || self.has_spot_stop(&g.gradient) { None } else { g.ink_pixels(b, area, cols, rows, fill) };
|
||||
let ramp_inks = if freeform || self.prints_spot(&g.gradient) { None } else { g.ink_pixels(b, area, cols, rows, fill) };
|
||||
let ink_image = |inks, alpha| {
|
||||
let convert = if self.convert { self.out.cmyk_pixels() } else { None };
|
||||
crate::images::from_inks(inks, alpha, cols.into(), rows.into(), self.interpolate, convert)
|
||||
|
||||
@@ -962,6 +962,35 @@ fn gradients_with_a_stop_that_is_not_process_cmyk_stay_rgb_images() {
|
||||
assert_eq!(w[0].space, "DeviceCMYK", "{w:?}");
|
||||
}
|
||||
|
||||
/// A stop linked to a spot swatch that prints no ink (it colors only clear stretches, sits out of
|
||||
/// order where it colors nothing, or has a tint of 0 and no process plates) leaves a dithered
|
||||
/// gradient of CMYK stops a CMYK image without the spot warning; a drawn stop with process plates
|
||||
/// at a tint of 0 still prints, so its gradient stays an RGB image with the warning.
|
||||
#[test]
|
||||
fn gradients_whose_spot_stops_print_nothing_stay_cmyk_images() {
|
||||
let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1);
|
||||
let stop = |offset: f32, color: Color, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, color) };
|
||||
let spot = |offset: f32, opacity: f32| GradientStop { swatch: Some("Gold".into()), ..stop(offset, gold, opacity) };
|
||||
let (cyan, black) = (Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0));
|
||||
let clear = vec![stop(0.0, cyan, 1.0), stop(0.5, black, 1.0), stop(0.6, black, 0.0), spot(0.8, 0.0), stop(1.0, black, 0.0)];
|
||||
let out_of_order = vec![stop(0.0, cyan, 1.0), stop(0.6, black, 1.0), spot(0.3, 1.0), stop(0.6, black, 1.0), stop(1.0, black, 1.0)];
|
||||
let no_tint = vec![stop(0.0, cyan, 1.0), GradientStop { tint: 0.0, ..spot(1.0, 1.0) }];
|
||||
let plates = vec![stop(0.0, cyan, 1.0), GradientStop { tint: 0.0, plates: Some([0.0, 0.0, 0.0, 0.5]), ..spot(1.0, 1.0) }];
|
||||
for (name, stops, prints) in
|
||||
[("clear", clear, false), ("out of order", out_of_order, false), ("tint 0", no_tint, false), ("plates", plates, true)]
|
||||
{
|
||||
let mut d = gradient_doc(ColorMode::Cmyk, drawn_as_pixels(GradientKind::Linear, stops, true));
|
||||
d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true });
|
||||
let out = export_with_report(&d, &opts(json!({}))).unwrap();
|
||||
let w = written(&out.bytes);
|
||||
let warned = out.warnings.iter().any(|m| m.contains("written in process colors"));
|
||||
let space = if prints { "DeviceRGB" } else { "DeviceCMYK" };
|
||||
assert!(w.iter().any(|i| i.space == space), "{name}: {w:?}");
|
||||
assert!(!w.iter().any(|i| i.space == if prints { "DeviceCMYK" } else { "DeviceRGB" }), "{name}: {w:?}");
|
||||
assert_eq!(warned, prints, "{name}: {:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_gradients_of_lab_points_are_written_as_their_lab_mix() {
|
||||
let d = freeform_doc(ColorMode::Rgb, Color::lab(90.0, -60.0, 40.0), Color::lab(30.0, 60.0, -40.0), 1.0);
|
||||
|
||||
@@ -662,6 +662,17 @@ fn a_spot_gradient_stop_prints_its_process_plates() {
|
||||
assert_eq!(first(json!({"output": {"mode": "separations", "spotsToProcess": true}})), [25.0, 10.0, 64.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_gradient_stop_whose_tint_is_not_a_number_prints_no_spot_ink() {
|
||||
let mut mixed = GradientStop::new(0.0, Color::cmyk(0.25, 0.1, 0.8, 0.05));
|
||||
(mixed.swatch, mixed.tint, mixed.plates) = (Some("Gold".into()), f32::NAN, Some([0.25, 0.0, 0.4, 0.0]));
|
||||
let g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![mixed, GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]));
|
||||
let d = gold_gradient_doc(g);
|
||||
let first = |v| gradient_plates(&d, v).into_iter().map(|(s, _)| s).collect::<Vec<_>>();
|
||||
assert_eq!(first(json!({"output": {"mode": "separations"}})), [25.0, 0.0, 40.0, 0.0, 0.0], "Cyan, Magenta, Yellow, Black, Gold");
|
||||
assert_eq!(first(json!({"output": {"mode": "separations", "spotsToProcess": true}})), [25.0, 0.0, 40.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_freeform_gradients_points_separate_into_plates() {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, 1.0))]));
|
||||
|
||||
@@ -145,7 +145,7 @@ fn composite_font_parts_are_not_highlighted_as_substituted_glyphs() {
|
||||
let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular"));
|
||||
parts.roman = CompositePart::new("JetBrains Mono", "Regular");
|
||||
parts.numerals = CompositePart::new("Inter", "Regular");
|
||||
db.set_composite_font(&CompositeFont { name: "CF Highlight".into(), parts });
|
||||
db.set_composite_font(&CompositeFont { name: "CF Highlight".into(), parts, custom: Vec::new() });
|
||||
let style = CharStyle { size: 40.0, font_family: "CF Highlight".into(), ..Default::default() };
|
||||
let t = TextObject::point(Point::new(10.0, 60.0), "Ab12", style);
|
||||
let g = text_geom(&t);
|
||||
@@ -175,7 +175,7 @@ fn a_documents_own_composite_font_draws_without_being_registered() {
|
||||
let (mut composite, id) = typed(NAME);
|
||||
let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular"));
|
||||
parts.roman = CompositePart::new("JetBrains Mono", "Regular");
|
||||
composite.composite_fonts.push(CompositeFont { name: NAME.into(), parts });
|
||||
composite.composite_fonts.push(CompositeFont { name: NAME.into(), parts, custom: Vec::new() });
|
||||
let (plain, plain_id) = typed("JetBrains Mono");
|
||||
assert!(db.composite_font(NAME).is_none());
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
@@ -236,7 +236,7 @@ fn a_placed_document_draws_its_own_definition_of_a_name_the_page_defines() {
|
||||
let definition = |roman: &str| {
|
||||
let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular"));
|
||||
parts.roman = CompositePart::new(roman, "Regular");
|
||||
CompositeFont { name: NAME.into(), parts }
|
||||
CompositeFont { name: NAME.into(), parts, custom: Vec::new() }
|
||||
};
|
||||
let typed = |family: &str| {
|
||||
let mut d = Document::new(300.0, 150.0);
|
||||
@@ -319,7 +319,7 @@ fn a_document_draws_type_in_another_documents_composite_font_as_missing() {
|
||||
};
|
||||
let mut parts = CompositeParts::all(CompositePart::new("Source Sans 3", "Regular"));
|
||||
parts.roman = CompositePart::new("JetBrains Mono", "Regular");
|
||||
db.set_composite_font(&CompositeFont { name: NAME.into(), parts });
|
||||
db.set_composite_font(&CompositeFont { name: NAME.into(), parts, custom: Vec::new() });
|
||||
let (drawn, as_missing, in_front) = (draw(&back, id), draw(&missing, missing_id), draw(&plain, plain_id));
|
||||
db.remove_composite_font(NAME);
|
||||
assert!(drawn.0 != in_front.0, "not in the front document's definition");
|
||||
|
||||
@@ -119,6 +119,9 @@ pub struct FontDb {
|
||||
/// type naming one as its family is set in its parts' fonts. A thread's guards can lend others
|
||||
/// in their place ([`FontDb::lend_composite_fonts`]).
|
||||
composites: RwLock<HashMap<String, Arc<vectorcraft_doc::CompositeFont>>>,
|
||||
/// The lookups of the custom character sets of the composite fonts held or lent, each built
|
||||
/// when first used.
|
||||
custom_classes: Mutex<composite::CustomClasses>,
|
||||
}
|
||||
|
||||
/// Where a database's system font scan looks: folders (read with their subfolders) and font files.
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
//! Composite fonts (Type › Composite Fonts…) in the font database: each is listed first in the
|
||||
//! font menus and resolves to its base (Kanji) font, and layout sets each character of type in one
|
||||
//! in the font of the character's class ([`FontDb::composite_split`]).
|
||||
//! in the font of the custom character set that lists it, else of its class
|
||||
//! ([`FontDb::composite_split`]).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, TextObject, TextRun};
|
||||
use vectorcraft_doc::text::CompositeClasses;
|
||||
use vectorcraft_doc::{CharClass, CompositeClass, CompositeFont, CompositePart, TextObject, TextRun};
|
||||
|
||||
use super::face::FALLBACK_FAMILY;
|
||||
use super::{Arc, FontDb, FontFace, FontMatch};
|
||||
@@ -17,6 +20,13 @@ use super::{Arc, FontDb, FontFace, FontMatch};
|
||||
/// A face [`FontDb::resolve`] found and how it matched.
|
||||
type Resolved = Option<(Arc<FontFace>, FontMatch)>;
|
||||
|
||||
/// The base class: type without characters and anything no part names takes its part.
|
||||
const KANJI: CompositeClass = CompositeClass::Fixed(CharClass::Kanji);
|
||||
|
||||
/// Lookups of the custom character sets of composite fonts, by the address of the font's `Arc`,
|
||||
/// each with a weak reference that tells when that font has gone and the address may be reused.
|
||||
pub(super) type CustomClasses = HashMap<usize, (Weak<CompositeFont>, Arc<CompositeClasses>)>;
|
||||
|
||||
thread_local! {
|
||||
/// The composite fonts the guards of this thread lend ([`FontDb::lend_composite_fonts`]), the
|
||||
/// latest loan last. Only the latest loan of a database is looked in.
|
||||
@@ -41,15 +51,25 @@ struct Loan {
|
||||
print: u64,
|
||||
}
|
||||
|
||||
/// Feed composite font `f`'s name and parts to `h`.
|
||||
/// Feed composite font `f`'s name, parts and custom character sets to `h`.
|
||||
fn hash_font(f: &CompositeFont, h: &mut DefaultHasher) {
|
||||
f.name.hash(h);
|
||||
let p = &f.parts;
|
||||
for part in [&p.kanji, &p.kana, &p.punctuation, &p.symbols, &p.roman, &p.numerals] {
|
||||
(&part.font, &part.style, part.scale_at_center).hash(h);
|
||||
for v in [part.size, part.baseline, part.h_scale, part.v_scale] {
|
||||
v.to_bits().hash(h);
|
||||
}
|
||||
hash_part(part, h);
|
||||
}
|
||||
f.custom.len().hash(h);
|
||||
for s in &f.custom {
|
||||
(&s.name, &s.characters).hash(h);
|
||||
hash_part(&s.part, h);
|
||||
}
|
||||
}
|
||||
|
||||
/// Feed part `part`'s font and values to `h`.
|
||||
fn hash_part(part: &CompositePart, h: &mut DefaultHasher) {
|
||||
(&part.font, &part.style, part.scale_at_center).hash(h);
|
||||
for v in [part.size, part.baseline, part.h_scale, part.v_scale] {
|
||||
v.to_bits().hash(h);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,8 +156,8 @@ impl FontDb {
|
||||
.unwrap_or(g)
|
||||
}
|
||||
|
||||
/// The face composite font `name` sets character `c` in (its class's part's), and whether
|
||||
/// that part's font is missing. `None` when `name` is no composite font.
|
||||
/// The face composite font `name` sets character `c` in (its custom set's or its class's
|
||||
/// part's), and whether that part's font is missing. `None` when `name` is no composite font.
|
||||
pub fn composite_face(&self, name: &str, c: char) -> Option<(bool, u32)> {
|
||||
self.composite_resolve(name, c).map(|(face, m)| (m == FontMatch::Missing, face.id()))
|
||||
}
|
||||
@@ -149,30 +169,58 @@ impl FontDb {
|
||||
self.composite_resolve(name, first)
|
||||
}
|
||||
|
||||
/// The face composite font `name` sets character `c` in (its class's part's), and how that
|
||||
/// part's font matched ([`FontDb::resolve`]). `None` when `name` is no composite font, or no
|
||||
/// font at all is loaded.
|
||||
/// The face composite font `name` sets character `c` in (its custom set's or its class's
|
||||
/// part's), and how that part's font matched ([`FontDb::resolve`]). `None` when `name` is no
|
||||
/// composite font, or no font at all is loaded.
|
||||
pub fn composite_resolve(&self, name: &str, c: char) -> Option<(Arc<FontFace>, FontMatch)> {
|
||||
let f = self.composite_font(name)?;
|
||||
let (family, style) = self.part_font(&f, CharClass::of(c));
|
||||
let (family, style) = self.part_font(&f, self.composite_class(&f, c));
|
||||
self.resolve(&family, &style)
|
||||
}
|
||||
|
||||
/// Where composite font `f` sets character `c`: the last custom set that lists it, else its
|
||||
/// class. The lookup of `f`'s sets is built once and kept while `f` lives.
|
||||
fn composite_class(&self, f: &Arc<CompositeFont>, c: char) -> CompositeClass {
|
||||
if f.custom.is_empty() {
|
||||
return CompositeClass::Fixed(CharClass::of(c));
|
||||
}
|
||||
self.custom_lookup(f).of(c)
|
||||
}
|
||||
|
||||
/// The lookup of composite font `f`'s custom character sets, built when first asked for.
|
||||
fn custom_lookup(&self, f: &Arc<CompositeFont>) -> Arc<CompositeClasses> {
|
||||
if f.custom.is_empty() {
|
||||
return Arc::default();
|
||||
}
|
||||
let key = Arc::as_ptr(f) as usize;
|
||||
let mut cache = self.custom_classes.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((font, lookup)) = cache.get(&key)
|
||||
&& font.upgrade().is_some_and(|g| Arc::ptr_eq(&g, f))
|
||||
{
|
||||
return lookup.clone();
|
||||
}
|
||||
cache.retain(|_, (font, _)| font.strong_count() > 0);
|
||||
let lookup = Arc::new(f.classes());
|
||||
cache.insert(key, (Arc::downgrade(f), lookup.clone()));
|
||||
lookup
|
||||
}
|
||||
|
||||
/// The fonts (family, style) composite font `name` sets `text` in: those of the parts its
|
||||
/// grapheme clusters fall in (each by its first character, as layout splits them), each once,
|
||||
/// in the order first used; the Kanji part's for text without characters. `None` when `name` is
|
||||
/// no composite font.
|
||||
pub fn composite_fonts_for(&self, name: &str, text: &str) -> Option<Vec<(String, String)>> {
|
||||
let f = self.composite_font(name)?;
|
||||
let mut classes: Vec<CharClass> = Vec::new();
|
||||
let lookup = self.custom_lookup(&f);
|
||||
let mut classes: Vec<CompositeClass> = Vec::new();
|
||||
for g in text.graphemes(true) {
|
||||
let c = g.chars().next().map_or(CharClass::Kanji, CharClass::of);
|
||||
let c = g.chars().next().map_or(KANJI, |c| lookup.of(c));
|
||||
if !classes.contains(&c) {
|
||||
classes.push(c);
|
||||
}
|
||||
}
|
||||
if classes.is_empty() {
|
||||
classes.push(CharClass::Kanji);
|
||||
classes.push(KANJI);
|
||||
}
|
||||
let mut fonts: Vec<(String, String)> = Vec::with_capacity(classes.len());
|
||||
for c in classes {
|
||||
@@ -196,8 +244,9 @@ impl FontDb {
|
||||
FontMatch::Style => 1,
|
||||
FontMatch::Missing => 2,
|
||||
};
|
||||
let mut faces: Vec<(CharClass, Resolved)> = Vec::new();
|
||||
let mut face_of = |class: CharClass| {
|
||||
let lookup = self.custom_lookup(&f);
|
||||
let mut faces: Vec<(CompositeClass, Resolved)> = Vec::new();
|
||||
let mut face_of = |class: CompositeClass| {
|
||||
if let Some((_, found)) = faces.iter().find(|(c, _)| *c == class) {
|
||||
return found.clone();
|
||||
}
|
||||
@@ -213,7 +262,7 @@ impl FontDb {
|
||||
graphemes.push("");
|
||||
}
|
||||
for g in graphemes {
|
||||
let class = g.chars().next().map_or(CharClass::Kanji, CharClass::of);
|
||||
let class = g.chars().next().map_or(KANJI, |c| lookup.of(c));
|
||||
let found = face_of(class);
|
||||
let m = found.as_ref().map_or(FontMatch::Missing, |(_, m)| *m);
|
||||
if worst.as_ref().is_none_or(|(w, _)| rank(m) > rank(*w)) {
|
||||
@@ -307,10 +356,11 @@ impl FontDb {
|
||||
LentCompositeFonts { number: pushed.then_some(number), thread: PhantomData }
|
||||
}
|
||||
|
||||
/// The family and style composite font `f` sets characters of `class` in: its part's, or the
|
||||
/// fallback font's when that part names a composite font.
|
||||
fn part_font(&self, f: &CompositeFont, class: CharClass) -> (String, String) {
|
||||
let p = f.parts.get(class);
|
||||
/// The family and style composite font `f` sets characters of `class` in: its part's (the
|
||||
/// Kanji part's for a custom set it doesn't have), or the fallback font's when that part names
|
||||
/// a composite font.
|
||||
fn part_font(&self, f: &CompositeFont, class: CompositeClass) -> (String, String) {
|
||||
let p = f.part(class).unwrap_or(&f.parts.kanji);
|
||||
if self.composite_font(&p.font).is_some() { (FALLBACK_FAMILY.to_string(), "Regular".to_string()) } else { (p.font.clone(), p.style.clone()) }
|
||||
}
|
||||
|
||||
@@ -326,11 +376,13 @@ impl FontDb {
|
||||
/// names a composite font too. `None` when `name` is no composite font.
|
||||
pub(super) fn composite_base(&self, name: &str) -> Option<(String, String)> {
|
||||
let f = self.composite_font(name)?;
|
||||
Some(self.part_font(&f, CharClass::Kanji))
|
||||
Some(self.part_font(&f, KANJI))
|
||||
}
|
||||
|
||||
/// `t` with each run set in a composite font split into runs of one [`CharClass`] each, set in
|
||||
/// that class's font: its size and baseline shift from the part's size and baseline (in
|
||||
/// `t` with each run set in a composite font split into runs of one custom character set or
|
||||
/// [`CharClass`] each (a set listing a character takes it ahead of its class, the font's last
|
||||
/// such set when several do), set in that set's or class's font: its size and baseline shift
|
||||
/// from the part's size and baseline (in
|
||||
/// percent of the run's size), its scales multiplied by the part's, and Kana scaled at the
|
||||
/// center raised so the em box's center stays where it was. Each grapheme cluster goes with
|
||||
/// its first character. Also the index of the run of `t` each run came from. `None` when no run
|
||||
@@ -352,10 +404,11 @@ impl FontDb {
|
||||
from.push(i);
|
||||
continue;
|
||||
};
|
||||
let lookup = self.custom_lookup(font);
|
||||
let mut start = 0;
|
||||
let mut class = None;
|
||||
for (at, g) in r.text.grapheme_indices(true) {
|
||||
let c = g.chars().next().map_or(CharClass::Kanji, CharClass::of);
|
||||
let c = g.chars().next().map_or(KANJI, |c| lookup.of(c));
|
||||
if let Some(k) = class
|
||||
&& k != c
|
||||
{
|
||||
@@ -365,16 +418,16 @@ impl FontDb {
|
||||
}
|
||||
class = Some(c);
|
||||
}
|
||||
runs.push(self.composite_run(r.text.get(start..).unwrap_or_default(), r, font, class.unwrap_or(CharClass::Kanji)));
|
||||
runs.push(self.composite_run(r.text.get(start..).unwrap_or_default(), r, font, class.unwrap_or(KANJI)));
|
||||
from.push(i);
|
||||
}
|
||||
Some((TextObject { runs, ..t.clone() }, from))
|
||||
}
|
||||
|
||||
/// Characters `text` of run `r` (set in composite font `font`), all of class `class`, as a run
|
||||
/// set in that class's part.
|
||||
fn composite_run(&self, text: &str, r: &TextRun, font: &CompositeFont, class: CharClass) -> TextRun {
|
||||
let p = font.parts.get(class);
|
||||
/// Characters `text` of run `r` (set in composite font `font`), all of class or set `class`,
|
||||
/// as a run set in that class's or set's part.
|
||||
fn composite_run(&self, text: &str, r: &TextRun, font: &CompositeFont, class: CompositeClass) -> TextRun {
|
||||
let p = font.part(class).unwrap_or(&font.parts.kanji);
|
||||
let mut st = r.style.clone();
|
||||
let base = st.size;
|
||||
let (family, style) = self.part_font(font, class);
|
||||
@@ -386,7 +439,7 @@ impl FontDb {
|
||||
st.baseline_shift += base * p.baseline / 100.0;
|
||||
st.h_scale *= p.h_scale / 100.0;
|
||||
st.v_scale *= p.v_scale / 100.0;
|
||||
if class == CharClass::Kana && p.scale_at_center && p.v_scale != 100.0 {
|
||||
if class == CompositeClass::Fixed(CharClass::Kana) && p.scale_at_center && p.v_scale != 100.0 {
|
||||
let centre = self.style_face(&st).map_or(0.38, |f| f.ideographic_centre());
|
||||
st.baseline_shift += st.size * centre * (1.0 - p.v_scale / 100.0);
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ impl FontDb {
|
||||
stamp: Mutex::new(None),
|
||||
instances: Mutex::new(Instances::default()),
|
||||
composites: RwLock::new(HashMap::new()),
|
||||
custom_classes: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,51 @@ fn composite_runs_split_by_class() {
|
||||
assert!(db.composite_split(&TextObject::point(Point::ZERO, "Ab", style("Inter", 12.0))).is_none());
|
||||
}
|
||||
|
||||
/// A custom character set takes the characters it lists ahead of their class, the later of two
|
||||
/// sets wins a character both list, and the set's part sizes, raises and scales them. The fonts
|
||||
/// used for the text, how it is covered and the face of one character follow the sets too.
|
||||
#[test]
|
||||
fn custom_character_sets_take_their_characters_first() {
|
||||
use vectorcraft_doc::{CompositePart, CustomCharSet};
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let mut f = mixed("Custom");
|
||||
let mut part = CompositePart::new("Inter", "Regular");
|
||||
part.size = 150.0;
|
||||
part.baseline = -10.0;
|
||||
part.h_scale = 90.0;
|
||||
let mut first = CustomCharSet::new("Letters", CompositePart::new("Source Sans 3", "Regular"));
|
||||
first.characters = "Bか".into();
|
||||
let mut second = CustomCharSet::new("B only", part);
|
||||
second.characters = "B".into();
|
||||
f.custom = vec![first, second];
|
||||
db.set_composite_font(&f);
|
||||
let t = TextObject::point(Point::ZERO, "ABか1", style("Custom", 20.0));
|
||||
let (split, from) = db.composite_split(&t).expect("split");
|
||||
let pieces: Vec<(&str, &str)> = split.runs.iter().map(|r| (r.text.as_str(), r.style.font_family.as_str())).collect();
|
||||
assert_eq!(pieces, [("A", "JetBrains Mono"), ("B", "Inter"), ("か", "Source Sans 3"), ("1", "Inter")]);
|
||||
assert_eq!(from, [0, 0, 0, 0]);
|
||||
let b = &split.runs[1].style;
|
||||
assert_eq!((b.size, b.baseline_shift, b.h_scale, b.v_scale), (30.0, -2.0, 90.0, 100.0));
|
||||
// か is in a set, so the Kana part's Scale at Center does not apply to it.
|
||||
let ka = &split.runs[2].style;
|
||||
assert_eq!((ka.v_scale, ka.baseline_shift), (100.0, 0.0));
|
||||
assert_eq!(db.composite_face("Custom", 'B').map(|(_, id)| id), Some(face_id(&db, "Inter")));
|
||||
let fonts = db.composite_fonts_for("Custom", "BA").unwrap();
|
||||
assert_eq!(fonts, [("Inter".to_string(), "Regular".to_string()), ("JetBrains Mono".to_string(), "Regular".to_string())]);
|
||||
let l = layout(&db, &t);
|
||||
let ids: Vec<u32> = l.glyphs.iter().map(|g| g.font_id).collect();
|
||||
assert_eq!(ids[1], face_id(&db, "Inter"));
|
||||
// A changed set is a changed definition: lending it lays the type out again.
|
||||
let mut changed = f.clone();
|
||||
changed.custom[1].characters = "A".into();
|
||||
let g0 = db.generation();
|
||||
let lent = db.lend_composite_fonts(&[changed]);
|
||||
assert_ne!(db.generation(), g0);
|
||||
let (split, _) = db.composite_split(&t).expect("split");
|
||||
assert_eq!(split.runs[0].style.font_family, "Inter");
|
||||
drop(lent);
|
||||
}
|
||||
|
||||
/// Laid out, each character is drawn in its class's font, sized by its part, and the glyphs still
|
||||
/// name the run of the text they belong to.
|
||||
#[test]
|
||||
|
||||
@@ -57,6 +57,7 @@ mod logo;
|
||||
mod mosaic;
|
||||
mod opaque;
|
||||
mod quantize;
|
||||
mod seam;
|
||||
mod shapes;
|
||||
mod smooth;
|
||||
mod subpixel;
|
||||
@@ -71,6 +72,7 @@ pub use gradient::TracedGradient;
|
||||
pub use mosaic::mosaic;
|
||||
pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline};
|
||||
pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize};
|
||||
pub use seam::{SEAM_WIDTH, seam_fills};
|
||||
pub use shapes::TracedShape;
|
||||
use subpixel::Crack;
|
||||
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Abutting with Fills: seam fills, thin strokes under the filled paths along the edges they share.
|
||||
//!
|
||||
//! Abutting paths meet edge to edge, so a renderer that anti-aliases each path on its own leaves
|
||||
//! the pixels along a shared edge partly covered by each path and lets what is behind them show
|
||||
//! through as a light hairline. A stroke along the edge in the color of the path drawn first,
|
||||
//! under every path, fills those pixels with that color: drawing the two paths over it then gives
|
||||
//! each pixel the colors of the two paths in the shares each covers. The paths themselves are not
|
||||
//! changed, and an edge a path shares with no other path (the image's border, a transparent area,
|
||||
//! a color left out) gets no stroke.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use vectorcraft_geom::{Anchor, PathData, Point, SubPath};
|
||||
|
||||
use super::params::{Method, Mode, TraceParams};
|
||||
use super::pipeline::TracedPath;
|
||||
|
||||
/// How wide each seam fill's stroke is, in pixels: it covers every pixel the shared edge passes
|
||||
/// through, at any angle (a pixel's corner is up to 0.71 px from a line through it).
|
||||
pub const SEAM_WIDTH: f64 = 1.5;
|
||||
|
||||
/// A segment, the same for the segment and the segment run backwards: two 64-bit hashes of its
|
||||
/// points' bits, 16 bytes a segment instead of 64. Two different segments with the same key would
|
||||
/// only give the lower one's color a stroke along a piece it does not share.
|
||||
type Key = u128;
|
||||
|
||||
fn key(a: &Anchor, b: &Anchor) -> Key {
|
||||
let bits = |[p, q, r, s]: [Point; 4]| [p.x, p.y, q.x, q.y, r.x, r.y, s.x, s.y].map(f64::to_bits);
|
||||
let points = bits([a.p, a.h_out, b.h_in, b.p]).min(bits([b.p, b.h_in, a.h_out, a.p]));
|
||||
let hash = |seed: u8| {
|
||||
let mut h = DefaultHasher::new();
|
||||
(seed, points).hash(&mut h);
|
||||
h.finish()
|
||||
};
|
||||
(u128::from(hash(0)) << 64) | u128::from(hash(1))
|
||||
}
|
||||
|
||||
/// The seam fills of a trace made with `params`: for Abutting with Fills (not Flat Logo), thin
|
||||
/// strokes to draw under every path of `paths` (bottom-most first). For each color, one path
|
||||
/// stroked [`SEAM_WIDTH`] pixels wide along the edges where a filled path of that color meets a
|
||||
/// filled path drawn after it, with `color` and `gradient` that path's; the paths with a gradient
|
||||
/// get one each. Bottom-most first, as the paths they lie under. The stroke has at most as many
|
||||
/// anchors as `paths` (each of its segments is a segment of a path), and finding them keeps about
|
||||
/// 40 bytes for each segment of `paths` while it runs. Empty for any other trace.
|
||||
pub fn seam_fills(paths: &[TracedPath], params: &TraceParams) -> Vec<TracedPath> {
|
||||
if params.method != Method::Abutting || !params.fills || params.mode == Mode::Logo {
|
||||
return vec![];
|
||||
}
|
||||
fills(paths)
|
||||
}
|
||||
|
||||
/// The segments of `sp`: each anchor and the one after it (back to the first, if closed).
|
||||
fn segments(sp: &SubPath) -> impl Iterator<Item = (&Anchor, &Anchor)> {
|
||||
let n = sp.anchors.len();
|
||||
let count = if sp.closed { n } else { n.saturating_sub(1) };
|
||||
(0..count).filter_map(move |k| Some((sp.anchors.get(k)?, sp.anchors.get((k + 1) % n)?)))
|
||||
}
|
||||
|
||||
/// [`seam_fills`] of Abutting `paths`, whatever the settings.
|
||||
fn fills(paths: &[TracedPath]) -> Vec<TracedPath> {
|
||||
// For each segment, the first path it is in, and whether another path has it too.
|
||||
let mut owner: HashMap<Key, (usize, bool)> = HashMap::new();
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) {
|
||||
for sp in &p.path.subpaths {
|
||||
for (a, b) in segments(sp).filter(|(a, b)| a.p != b.p) {
|
||||
let e = owner.entry(key(a, b)).or_insert((i, false));
|
||||
if e.0 != i {
|
||||
e.1 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// One fill per color (per path, for a gradient), in the order of the first path it lies under.
|
||||
let mut out: Vec<TracedPath> = vec![];
|
||||
let mut by_color: HashMap<[u8; 3], usize> = HashMap::new();
|
||||
for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) {
|
||||
let mut runs: Vec<SubPath> = vec![];
|
||||
for sp in &p.path.subpaths {
|
||||
let lower = |a: &Anchor, b: &Anchor| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true));
|
||||
let marks: Vec<bool> = segments(sp).map(|(a, b)| lower(a, b)).collect();
|
||||
let n = sp.anchors.len();
|
||||
if marks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if sp.closed && marks.iter().all(|&m| m) {
|
||||
runs.push(SubPath::new(sp.anchors.clone(), true));
|
||||
continue;
|
||||
}
|
||||
// Start after an unmarked segment, so that a run across the subpath's first anchor
|
||||
// stays one run.
|
||||
let start = if sp.closed { marks.iter().position(|&m| !m).map_or(0, |k| k + 1) } else { 0 };
|
||||
let mut run: Vec<Anchor> = vec![];
|
||||
for j in 0..marks.len() {
|
||||
let k = (start + j) % marks.len();
|
||||
let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % n)) else { continue };
|
||||
if marks.get(k).copied().unwrap_or(false) {
|
||||
if run.is_empty() {
|
||||
run.push(Anchor { h_in: a.p, ..a });
|
||||
}
|
||||
run.push(b);
|
||||
} else if !run.is_empty() {
|
||||
runs.push(open_run(std::mem::take(&mut run)));
|
||||
}
|
||||
}
|
||||
if !run.is_empty() {
|
||||
runs.push(open_run(run));
|
||||
}
|
||||
}
|
||||
if runs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let slot = if p.gradient.is_some() { None } else { by_color.get(&p.color).copied() };
|
||||
match slot.and_then(|s| out.get_mut(s)) {
|
||||
Some(fill) => fill.path.subpaths.extend(runs),
|
||||
None => {
|
||||
if p.gradient.is_none() {
|
||||
by_color.insert(p.color, out.len());
|
||||
}
|
||||
out.push(TracedPath {
|
||||
path: PathData::new(runs),
|
||||
color: p.color,
|
||||
pixels: 0,
|
||||
stroke: Some(SEAM_WIDTH),
|
||||
shape: None,
|
||||
gradient: p.gradient.clone(),
|
||||
square_caps: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An open run of anchors: the last one has no handle out.
|
||||
fn open_run(mut run: Vec<Anchor>) -> SubPath {
|
||||
if let Some(last) = run.last_mut() {
|
||||
last.h_out = last.p;
|
||||
}
|
||||
SubPath::new(run, false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Method, Mode, Raster, TraceParams, trace};
|
||||
|
||||
fn polygon(rings: &[&[(f64, f64)]], color: u8) -> TracedPath {
|
||||
let subpaths = rings.iter().map(|r| SubPath::polyline(&r.iter().map(|&(x, y)| Point::new(x, y)).collect::<Vec<_>>(), true)).collect();
|
||||
TracedPath { path: PathData::new(subpaths), color: [color; 3], pixels: 1, stroke: None, shape: None, gradient: None, square_caps: false }
|
||||
}
|
||||
|
||||
fn points(sp: &SubPath) -> Vec<(f64, f64)> {
|
||||
sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect()
|
||||
}
|
||||
|
||||
/// Each segment of `p`'s subpaths, by [`key`].
|
||||
fn keys(p: &TracedPath) -> Vec<Key> {
|
||||
p.path.subpaths.iter().flat_map(|sp| segments(sp).map(|(a, b)| key(a, b)).collect::<Vec<_>>()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_edge_gets_a_stroke_in_the_color_of_the_path_drawn_first() {
|
||||
let left = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
let fills = fills(&[left.clone(), right.clone()]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!((fills[0].color, fills[0].stroke, fills[0].gradient.as_ref()), ([10; 3], Some(SEAM_WIDTH), None));
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
let sp = &fills[0].path.subpaths[0];
|
||||
assert!(!sp.closed);
|
||||
assert_eq!(points(sp), [(2.0, 0.0), (2.0, 2.0)]);
|
||||
// Drawn the other way round, the stroke takes the other color.
|
||||
let swapped = super::fills(&[right, left]);
|
||||
assert_eq!(swapped.len(), 1);
|
||||
assert_eq!((swapped[0].color, points(&swapped[0].path.subpaths[0])), ([20; 3], vec![(2.0, 2.0), (2.0, 0.0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_island_gets_a_closed_stroke_in_the_color_around_it() {
|
||||
let hole: &[(f64, f64)] = &[(2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0)];
|
||||
let around = polygon(&[&[(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], hole], 10);
|
||||
let island = polygon(&[&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]], 20);
|
||||
let fills = fills(&[around, island]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].color, [10; 3]);
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
assert!(fills[0].path.subpaths[0].closed);
|
||||
assert_eq!(points(&fills[0].path.subpaths[0]), hole);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shared_run_across_a_subpaths_first_anchor_stays_one_stroke() {
|
||||
// The left square starts halfway along the edge it shares; the right one splits that edge
|
||||
// at the same point.
|
||||
let left = polygon(&[&[(2.0, 1.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0), (2.0, 0.0)]], 10);
|
||||
let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 1.0)]], 20);
|
||||
let fills = fills(&[left, right]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].path.subpaths.len(), 1);
|
||||
assert_eq!(points(&fills[0].path.subpaths[0]), [(2.0, 0.0), (2.0, 1.0), (2.0, 2.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_shared_with_no_other_filled_path_get_no_stroke() {
|
||||
let square = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
assert_eq!(fills(std::slice::from_ref(&square)), []);
|
||||
// A stroked line along the square's edge is not a filled neighbour.
|
||||
let mut line = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20);
|
||||
line.stroke = Some(1.0);
|
||||
assert_eq!(fills(&[square, line]), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_of_one_color_share_one_stroke_and_gradients_keep_their_own() {
|
||||
let a = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10);
|
||||
let b = polygon(&[&[(0.0, 4.0), (2.0, 4.0), (2.0, 6.0), (0.0, 6.0)]], 10);
|
||||
let c = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 6.0), (2.0, 6.0), (2.0, 4.0), (2.0, 2.0)]], 20);
|
||||
let fills = fills(&[a, b, c]);
|
||||
assert_eq!(fills.len(), 1, "{fills:?}");
|
||||
assert_eq!(fills[0].path.subpaths.iter().map(points).collect::<Vec<_>>(), [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]);
|
||||
}
|
||||
|
||||
/// Two colors side by side, the edge between them anti-aliased at `x = 10.4`.
|
||||
fn two_colors() -> Raster {
|
||||
Raster::from_fn(24, 16, |x, _| {
|
||||
let share = (10.4 - f64::from(x)).clamp(0.0, 1.0);
|
||||
let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8;
|
||||
[mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255]
|
||||
})
|
||||
}
|
||||
|
||||
fn color(method: Method) -> TraceParams {
|
||||
TraceParams { mode: Mode::Color, colors: 2, method, ignore_white: false, ..TraceParams::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_abutting_trace_strokes_the_edges_its_filled_paths_share() {
|
||||
let params = color(Method::Abutting);
|
||||
let res = trace(&two_colors(), ¶ms);
|
||||
assert_eq!(res.paths.len(), 2, "{res:?}");
|
||||
let seams = seam_fills(&res.paths, ¶ms);
|
||||
assert_eq!(seams.len(), 1, "{seams:?}");
|
||||
let seam = &seams[0];
|
||||
assert_eq!((seam.color, seam.stroke), (res.paths[0].color, Some(SEAM_WIDTH)));
|
||||
// Every piece of the stroke is a piece of both paths, and it runs from the image's top to
|
||||
// its bottom along the edge, not along the image's border.
|
||||
let (lower, upper) = (keys(&res.paths[0]), keys(&res.paths[1]));
|
||||
assert!(keys(seam).iter().all(|k| lower.contains(k) && upper.contains(k)));
|
||||
assert!(seam.path.anchor_count() <= res.anchor_count());
|
||||
for a in seam.path.subpaths.iter().flat_map(|sp| &sp.anchors) {
|
||||
assert!((a.p.x - 10.4).abs() < 0.5, "{a:?}");
|
||||
}
|
||||
let ys: Vec<f64> = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect();
|
||||
assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_abutting_fills_get_seam_strokes() {
|
||||
let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params);
|
||||
let img = two_colors();
|
||||
assert_eq!(seams(&img, &color(Method::Overlapping)), []);
|
||||
assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), []);
|
||||
// Flat Logo's shapes are stacked, whatever the method says.
|
||||
let abutting = trace(&img, &color(Method::Abutting));
|
||||
assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }), []);
|
||||
// A color left out leaves no neighbour: a dark bar on white, with Ignore White.
|
||||
let bar = Raster::from_fn(24, 16, |x, _| if (8..16).contains(&x) { [0, 0, 0, 255] } else { [255; 4] });
|
||||
let bw = TraceParams { mode: Mode::BlackAndWhite, method: Method::Abutting, ignore_white: true, ..TraceParams::default() };
|
||||
let res = trace(&bar, &bw);
|
||||
assert_eq!(res.paths.len(), 1, "{res:?}");
|
||||
assert_eq!(seam_fills(&res.paths, &bw), []);
|
||||
// Both colors traced, the bar's two sides are shared.
|
||||
let both = seams(&bar, &TraceParams { ignore_white: false, ..bw });
|
||||
assert_eq!(both.iter().map(|s| s.path.subpaths.len()).sum::<usize>(), 2, "{both:?}");
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,11 @@ impl<'a> HandleLook<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many points bigger than the other selected anchors the key anchor's square is drawn.
|
||||
const KEY_ANCHOR_GROW: f32 = 2.0;
|
||||
/// The gap between the key anchor's square and the frame drawn around it.
|
||||
const KEY_ANCHOR_GAP: f32 = 2.0;
|
||||
|
||||
pub(super) fn anchor_square(p: &egui::Painter, c: Pos2, color: Color32, filled: bool, size: f32) {
|
||||
let r = egui::Rect::from_center_size(c, vec2(size, size));
|
||||
if filled {
|
||||
@@ -188,6 +193,14 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf:
|
||||
stroke_path(p, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, Stroke::new(KEY_OUTLINE, c32(st.doc.layer_color(k))));
|
||||
}
|
||||
marks.paint(st, p, xf, &options, key_outline, if big { &[] } else { &st.selection.objects });
|
||||
// The key anchor (Align to Key Anchor): a filled square bigger than the other anchors, in
|
||||
// a frame as thick as a key object's outline.
|
||||
if let Some(((k, _), q)) = st.selection.key_anchor.zip(st.selection.key_anchor_point(&st.doc)) {
|
||||
let (c, color, size) = (xf.to_screen(q), c32(st.doc.layer_color(k)), anchor(direct) + KEY_ANCHOR_GROW);
|
||||
anchor_square(p, c, color, true, size);
|
||||
let frame = egui::Rect::from_center_size(c, vec2(size + 2.0 * KEY_ANCHOR_GAP, size + 2.0 * KEY_ANCHOR_GAP));
|
||||
p.rect_stroke(frame, 0.0, Stroke::new(KEY_OUTLINE, color), StrokeKind::Outside);
|
||||
}
|
||||
}
|
||||
// The spine of each selected blend (or of the blend a selected key object belongs to).
|
||||
let mut spines = vec![];
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
//! Type › Composite Fonts… (with Show East Asian Options): the active document's composite fonts,
|
||||
//! the one picked in Font shown as a table with a row for each class of character (Kanji, Kana,
|
||||
//! Punctuation, Symbols, Roman, Numerals) and its font, style, size, baseline and scales. New adds
|
||||
//! a font based on the one picked, Delete Font takes it out, Import… adds the fonts of a file and
|
||||
//! Export… writes the one picked to a file. Nothing changes in the document until OK, which runs
|
||||
//! `type.compositeFonts.set` with every font as one undo step; Cancel leaves them as they were.
|
||||
//! Punctuation, Symbols, Roman, Numerals), then a row for each custom character set, with its font,
|
||||
//! style, size, baseline and scales. New adds a font based on the one picked, Delete Font takes it
|
||||
//! out, Import… adds the fonts of a file and Export… writes the one picked to a file. Custom shows
|
||||
//! the custom character sets of the font picked: New adds a set based on the one picked, Delete Set
|
||||
//! takes it out, and Add puts the characters typed (Direct Entry) or the character of a Unicode code
|
||||
//! into it; Delete takes the character picked out. Nothing changes in the document until OK, which
|
||||
//! runs `type.compositeFonts.set` with every font as one undo step; Cancel leaves them as they were.
|
||||
//!
|
||||
//! Fields: `fonts` (the composite fonts as `type.compositeFonts.set` takes them), `selected` (the
|
||||
//! index of the one picked) and `name` (its name as typed).
|
||||
//! index of the one picked) and `name` (its name as typed); `custom` (whether the custom character
|
||||
//! sets show), `set` (the index of the set picked), `setName` (its name as typed), `entryMode`
|
||||
//! (`direct` or `unicode`), `entry` (the characters or code typed) and `char` (the index of the
|
||||
//! character picked in the set).
|
||||
//!
|
||||
//! Behavior reference (public documentation):
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>.
|
||||
//! <https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347>,
|
||||
//! custom character sets:
|
||||
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart};
|
||||
use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
|
||||
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CustomCharSet};
|
||||
use vectorcraft_engine::cmd::compositefonts::EXTS;
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
@@ -27,12 +35,28 @@ pub const KIND: &str = "compositeFonts";
|
||||
/// The command OK runs, and the menu item's.
|
||||
pub const COMMAND: &str = "type.compositeFonts.set";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Composite Fonts").into(), body, confirm, min_width: 760.0, ..DialogSpec::FORM };
|
||||
/// How many of a custom set's characters each row of its list shows.
|
||||
const CHARS_PER_ROW: usize = 20;
|
||||
|
||||
/// Open Composite Fonts on the active document's composite fonts, the first one picked.
|
||||
/// The tallest the table of parts grows before it scrolls, in points: the header, the six classes
|
||||
/// and a few custom sets.
|
||||
const TABLE_HEIGHT: f32 = 340.0;
|
||||
|
||||
/// `char` is held only while a character is picked, so `ui.dialog.set` takes it from `inputs`.
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Composite Fonts").into(),
|
||||
body,
|
||||
confirm,
|
||||
min_width: 760.0,
|
||||
inputs: |_| &["custom", "entry", "char"],
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
/// Open Composite Fonts on the active document's composite fonts, the first one picked, with the
|
||||
/// custom character sets hidden and nothing typed.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec();
|
||||
let mut d = Dialog::new(KIND, json!({ "fonts": fonts, "selected": 0 }));
|
||||
let mut d = Dialog::new(KIND, json!({ "fonts": fonts, "selected": 0, "custom": false, "entryMode": "direct", "entry": "" }));
|
||||
show_selected(&mut d);
|
||||
app.ui.dialog = Some(d);
|
||||
Ok(Value::Null)
|
||||
@@ -47,12 +71,17 @@ fn put_fonts(d: &mut Dialog, fonts: &[CompositeFont]) {
|
||||
d.fields.insert("fonts".into(), json!(fonts));
|
||||
}
|
||||
|
||||
/// The index of the font picked, within the fonts (0 when there are none).
|
||||
fn selected(d: &Dialog, count: usize) -> usize {
|
||||
d.fields.get("selected").and_then(Value::as_u64).map_or(0, |i| i as usize).min(count.saturating_sub(1))
|
||||
/// The index field `key` holds, within `count` items (0 when there are none).
|
||||
fn index(d: &Dialog, key: &str, count: usize) -> usize {
|
||||
d.fields.get(key).and_then(Value::as_u64).map_or(0, |i| i as usize).min(count.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Pick font `i`: its name goes into Name.
|
||||
/// The index of the font picked, within the fonts (0 when there are none).
|
||||
fn selected(d: &Dialog, count: usize) -> usize {
|
||||
index(d, "selected", count)
|
||||
}
|
||||
|
||||
/// Pick font `i`: its name goes into Name, and its first custom set is picked.
|
||||
fn select(d: &mut Dialog, i: usize) {
|
||||
d.fields.insert("selected".into(), json!(i));
|
||||
show_selected(d);
|
||||
@@ -62,6 +91,17 @@ fn show_selected(d: &mut Dialog) {
|
||||
let fonts = fonts(d);
|
||||
let name = fonts.get(selected(d, fonts.len())).map(|f| f.name.clone()).unwrap_or_default();
|
||||
d.fields.insert("name".into(), json!(name));
|
||||
select_set(d, 0);
|
||||
}
|
||||
|
||||
/// Pick custom set `i` of the font picked: its name goes into the set's Name, and no character is
|
||||
/// picked.
|
||||
fn select_set(d: &mut Dialog, i: usize) {
|
||||
d.fields.insert("set".into(), json!(i));
|
||||
d.fields.remove("char");
|
||||
let fonts = fonts(d);
|
||||
let name = fonts.get(selected(d, fonts.len())).and_then(|f| f.custom.get(i)).map(|s| s.name.clone()).unwrap_or_default();
|
||||
d.fields.insert("setName".into(), json!(name));
|
||||
}
|
||||
|
||||
/// The name of a class's row.
|
||||
@@ -85,12 +125,25 @@ fn new_name(fonts: &[CompositeFont]) -> String {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// "Character Set N", the first N no set in `sets` is named.
|
||||
fn new_set_name(sets: &[CustomCharSet]) -> String {
|
||||
(1..).map(|n| format!("Character Set {n}")).find(|n| !sets.iter().any(|s| CompositeFont::same_name(&s.name, n))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a button asked for, done once the table is drawn.
|
||||
enum Action {
|
||||
New,
|
||||
Delete,
|
||||
Import,
|
||||
Export,
|
||||
/// Custom: show or hide the custom character sets.
|
||||
Custom,
|
||||
NewSet,
|
||||
DeleteSet,
|
||||
/// Add the characters typed, or the character of the code typed, to the set picked.
|
||||
AddChars,
|
||||
/// Take the character picked out of the set picked.
|
||||
DeleteChar,
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
@@ -122,6 +175,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Export…"), 64.0)).inner.clicked() {
|
||||
act = Some(Action::Export);
|
||||
}
|
||||
if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Custom"), 64.0)).inner.clicked() {
|
||||
act = Some(Action::Custom);
|
||||
}
|
||||
});
|
||||
if let Some(k) = picked {
|
||||
select(d, k);
|
||||
@@ -136,6 +192,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
f.name = d.str("name");
|
||||
ui.add_space(8.0);
|
||||
parts_table(app, ui, f);
|
||||
if d.bool("custom") {
|
||||
ui.add_space(8.0);
|
||||
ui.separator();
|
||||
if let Some(a) = custom_sets(ui, d, f) {
|
||||
act = Some(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
put_fonts(d, &list);
|
||||
if let Some(a) = act {
|
||||
@@ -151,6 +214,80 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The custom character sets of `f`: Character Set with New and Delete Set, the set's Name, the
|
||||
/// Character row that adds characters, and the set's characters with Delete. The button pressed.
|
||||
fn custom_sets(ui: &mut egui::Ui, d: &mut Dialog, f: &mut CompositeFont) -> Option<Action> {
|
||||
let mut act = None;
|
||||
let k = index(d, "set", f.custom.len());
|
||||
let names: Vec<&str> = f.custom.iter().map(|s| s.name.as_str()).collect();
|
||||
let mut picked = None;
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Character Set:"));
|
||||
if names.is_empty() {
|
||||
widgets::dim_label(ui, tl!("None"));
|
||||
} else if let Some(n) = widgets::dropdown_names(ui, "composite-fonts-set", names.get(k).copied().unwrap_or_default(), &names, 220.0) {
|
||||
picked = Some(n);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
if ui.add_enabled_ui(f.custom.len() < CUSTOM_SETS_MAX, |ui| widgets::flat_button(ui, tl!("New"), 48.0)).inner.clicked() {
|
||||
act = Some(Action::NewSet);
|
||||
}
|
||||
if ui.add_enabled_ui(!f.custom.is_empty(), |ui| widgets::flat_button(ui, tl!("Delete Set"), 84.0)).inner.clicked() {
|
||||
act = Some(Action::DeleteSet);
|
||||
}
|
||||
});
|
||||
if let Some(n) = picked {
|
||||
select_set(d, n);
|
||||
return None;
|
||||
}
|
||||
let Some(set) = f.custom.get_mut(k) else { return act };
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Name:"));
|
||||
form::text(ui, d, "setName", 260.0);
|
||||
});
|
||||
set.name = d.str("setName");
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Character:"));
|
||||
let modes = [tl!("Direct Entry"), tl!("Unicode")];
|
||||
let unicode = d.str("entryMode") == "unicode";
|
||||
if let Some(m) = widgets::dropdown(ui, "composite-fonts-entry-mode", modes[usize::from(unicode)], &modes, 120.0) {
|
||||
d.fields.insert("entryMode".into(), json!(if m == 1 { "unicode" } else { "direct" }));
|
||||
}
|
||||
form::text(ui, d, "entry", 160.0);
|
||||
if widgets::flat_button(ui, tl!("Add"), 48.0).clicked() {
|
||||
act = Some(Action::AddChars);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let chosen = d.fields.get("char").and_then(Value::as_u64).map(|c| c as usize);
|
||||
let mut pick_char = None;
|
||||
// Only the rows in view are built, so a set of thousands of characters stays quick to draw.
|
||||
let chars: Vec<char> = set.characters.chars().collect();
|
||||
let rows = chars.len().div_ceil(CHARS_PER_ROW);
|
||||
egui::ScrollArea::vertical().id_salt("composite-fonts-chars").max_height(120.0).show_rows(ui, 24.0, rows, |ui, range| {
|
||||
for row in range {
|
||||
ui.horizontal(|ui| {
|
||||
for (n, c) in chars.iter().enumerate().skip(row * CHARS_PER_ROW).take(CHARS_PER_ROW) {
|
||||
let r = ui.add(egui::Button::selectable(chosen == Some(n), c.to_string()).min_size(egui::vec2(24.0, 24.0)));
|
||||
if r.on_hover_text(format!("U+{:04X}", *c as u32)).clicked() {
|
||||
pick_char = Some(n);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(n) = pick_char {
|
||||
d.fields.insert("char".into(), json!(n));
|
||||
}
|
||||
let can_delete = chosen.is_some_and(|n| n < chars.len());
|
||||
if ui.add_enabled_ui(can_delete, |ui| widgets::flat_button(ui, tl!("Delete"), 64.0)).inner.clicked() {
|
||||
act = Some(Action::DeleteChar);
|
||||
}
|
||||
act
|
||||
}
|
||||
|
||||
/// Do what button `act` asks for on the dialog's fonts.
|
||||
fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), String> {
|
||||
let mut list = fonts(d);
|
||||
@@ -178,61 +315,151 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), Stri
|
||||
let f = list.get(i).ok_or("no composite font")?;
|
||||
crate::io::save_command_output(app, "type.compositeFonts.export", EXTS[0], json!({ "fonts": [f] }))?;
|
||||
}
|
||||
Action::Custom => {
|
||||
let open = !d.bool("custom");
|
||||
d.fields.insert("custom".into(), json!(open));
|
||||
}
|
||||
Action::NewSet | Action::DeleteSet | Action::AddChars | Action::DeleteChar => {
|
||||
let f = list.get_mut(i).ok_or("no composite font")?;
|
||||
let at = edit_sets(d, f, act)?;
|
||||
put_fonts(d, &list);
|
||||
if let Some(k) = at {
|
||||
select_set(d, k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The table of `f`'s parts: a row for each class with its font, style, size, baseline, scales and
|
||||
/// (Kana) Scale at Center; the values a class can't take are not shown.
|
||||
/// Do custom set action `act` on font `f`. The set to pick afterwards, when the sets changed.
|
||||
fn edit_sets(d: &mut Dialog, f: &mut CompositeFont, act: Action) -> Result<Option<usize>, String> {
|
||||
let k = index(d, "set", f.custom.len());
|
||||
match act {
|
||||
Action::NewSet => {
|
||||
if f.custom.len() >= CUSTOM_SETS_MAX {
|
||||
return Err(format!("a composite font keeps at most {CUSTOM_SETS_MAX} character sets"));
|
||||
}
|
||||
// Based on the set picked: its characters, font and values.
|
||||
let mut s = f.custom.get(k).cloned().unwrap_or_else(|| CustomCharSet::new("", f.parts.kanji.clone()));
|
||||
s.name = new_set_name(&f.custom);
|
||||
f.custom.push(s);
|
||||
Ok(Some(f.custom.len() - 1))
|
||||
}
|
||||
Action::DeleteSet => {
|
||||
if k < f.custom.len() {
|
||||
f.custom.remove(k);
|
||||
}
|
||||
Ok(Some(k.min(f.custom.len().saturating_sub(1))))
|
||||
}
|
||||
Action::AddChars => {
|
||||
let set = f.custom.get_mut(k).ok_or("no character set")?;
|
||||
let entry = d.str("entry");
|
||||
let add: Vec<char> = if d.str("entryMode") == "unicode" {
|
||||
entry
|
||||
.split(|c: char| c.is_whitespace() || c == ',')
|
||||
.filter(|code| !code.is_empty())
|
||||
.map(|code| CustomCharSet::char_from_code(code).ok_or_else(|| format!("`{code}` is not a code from U+0000 to U+FFFF")))
|
||||
.collect::<Result<_, _>>()?
|
||||
} else {
|
||||
entry.chars().collect()
|
||||
};
|
||||
if let Some(c) = add.iter().find(|&&c| !CustomCharSet::takes(c)) {
|
||||
return Err(format!("`{}`: U+{:04X} is a control character or past U+FFFF", set.name, *c as u32));
|
||||
}
|
||||
let mut count = set.characters.chars().count();
|
||||
for c in add {
|
||||
if set.characters.contains(c) {
|
||||
continue;
|
||||
}
|
||||
if count == CUSTOM_CHARS_MAX {
|
||||
return Err(format!("`{}`: a character set keeps at most {CUSTOM_CHARS_MAX} characters", set.name));
|
||||
}
|
||||
set.characters.push(c);
|
||||
count += 1;
|
||||
}
|
||||
d.fields.insert("entry".into(), json!(""));
|
||||
Ok(None)
|
||||
}
|
||||
Action::DeleteChar => {
|
||||
let set = f.custom.get_mut(k).ok_or("no character set")?;
|
||||
let n = d.fields.get("char").and_then(Value::as_u64).map(|c| c as usize);
|
||||
if let Some(n) = n {
|
||||
set.characters = set.characters.chars().enumerate().filter(|(j, _)| *j != n).map(|(_, c)| c).collect();
|
||||
}
|
||||
d.fields.remove("char");
|
||||
Ok(None)
|
||||
}
|
||||
Action::New | Action::Delete | Action::Import | Action::Export | Action::Custom => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The table of `f`'s parts: a row for each class, then for each custom character set, with its
|
||||
/// font, style, size, baseline, scales and (Kana) Scale at Center; the values a row can't take are
|
||||
/// not shown. Past [`TABLE_HEIGHT`] the table scrolls, so the controls under it stay on screen.
|
||||
fn parts_table(app: &VectorcraftApp, ui: &mut egui::Ui, f: &mut CompositeFont) {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
egui::ScrollArea::vertical().id_salt("composite-fonts-table").max_height(TABLE_HEIGHT).show(ui, |ui| parts_grid(app, ui, f));
|
||||
}
|
||||
|
||||
/// The rows of [`parts_table`].
|
||||
fn parts_grid(app: &VectorcraftApp, ui: &mut egui::Ui, f: &mut CompositeFont) {
|
||||
egui::Grid::new("composite-fonts-parts").num_columns(8).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
for h in ["", tl!("Font"), tl!("Style"), tl!("Size"), tl!("Baseline"), tl!("Horizontal Scale"), tl!("Vertical Scale"), ""] {
|
||||
widgets::dim_label(ui, h);
|
||||
}
|
||||
ui.end_row();
|
||||
for class in CharClass::ALL {
|
||||
let p: &mut CompositePart = f.parts.get_mut(class);
|
||||
ui.label(class_label(class));
|
||||
let id = ("composite-font", class.key());
|
||||
if let Some(crate::font_menu::FontPick::Chosen(family, style)) =
|
||||
crate::font_menu::font_menu(ui, id, &p.font, 190.0, None, crate::font_menu::MenuLook::of(app))
|
||||
&& db.composite_font(&family).is_none()
|
||||
{
|
||||
p.style = style.unwrap_or_else(|| db.styles(&family).first().cloned().unwrap_or_else(|| "Regular".into()));
|
||||
p.font = family;
|
||||
}
|
||||
let styles = db.styles(&p.font);
|
||||
let style_names: Vec<&str> = styles.iter().map(String::as_str).collect();
|
||||
if let Some(k) = widgets::dropdown_names(ui, ("composite-font-style", class.key()), &p.style, &style_names, 120.0)
|
||||
&& let Some(s) = styles.get(k)
|
||||
{
|
||||
p.style.clone_from(s);
|
||||
}
|
||||
let percent = |ui: &mut egui::Ui, key: &str, v: &mut f64, range: &std::ops::RangeInclusive<f64>| {
|
||||
if let Some(n) = widgets::range_field(ui, ("composite-font", class.key(), key), *v, range.clone(), "%", 1, 64.0) {
|
||||
*v = n;
|
||||
}
|
||||
};
|
||||
percent(ui, "size", &mut p.size, &COMPOSITE_SIZE);
|
||||
percent(ui, "baseline", &mut p.baseline, &COMPOSITE_BASELINE);
|
||||
if class.scales() {
|
||||
percent(ui, "hScale", &mut p.h_scale, &COMPOSITE_SCALE);
|
||||
percent(ui, "vScale", &mut p.v_scale, &COMPOSITE_SCALE);
|
||||
} else {
|
||||
ui.label("");
|
||||
ui.label("");
|
||||
}
|
||||
if class == CharClass::Kana {
|
||||
ui.checkbox(&mut p.scale_at_center, tl!("Scale at Center"));
|
||||
} else {
|
||||
ui.label("");
|
||||
}
|
||||
ui.end_row();
|
||||
part_row(app, ui, class.key(), f.parts.get_mut(class), class.scales(), class == CharClass::Kana);
|
||||
}
|
||||
for (n, s) in f.custom.iter_mut().enumerate() {
|
||||
// A set's name is the user's own, shown as it is.
|
||||
ui.label(s.name.as_str());
|
||||
part_row(app, ui, &format!("custom-{n}"), &mut s.part, true, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The cells of part `p`'s row (keyed `key`) after its label: font, style, size, baseline, the
|
||||
/// scales when `scales`, and Scale at Center when `center`.
|
||||
fn part_row(app: &VectorcraftApp, ui: &mut egui::Ui, key: &str, p: &mut CompositePart, scales: bool, center: bool) {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let id = ("composite-font", key);
|
||||
if let Some(crate::font_menu::FontPick::Chosen(family, style)) =
|
||||
crate::font_menu::font_menu(ui, id, &p.font, 190.0, None, crate::font_menu::MenuLook::of(app))
|
||||
&& db.composite_font(&family).is_none()
|
||||
{
|
||||
p.style = style.unwrap_or_else(|| db.styles(&family).first().cloned().unwrap_or_else(|| "Regular".into()));
|
||||
p.font = family;
|
||||
}
|
||||
let styles = db.styles(&p.font);
|
||||
let style_names: Vec<&str> = styles.iter().map(String::as_str).collect();
|
||||
if let Some(k) = widgets::dropdown_names(ui, ("composite-font-style", key), &p.style, &style_names, 120.0)
|
||||
&& let Some(s) = styles.get(k)
|
||||
{
|
||||
p.style.clone_from(s);
|
||||
}
|
||||
let percent = |ui: &mut egui::Ui, field: &str, v: &mut f64, range: &std::ops::RangeInclusive<f64>| {
|
||||
if let Some(n) = widgets::range_field(ui, ("composite-font", key, field), *v, range.clone(), "%", 1, 64.0) {
|
||||
*v = n;
|
||||
}
|
||||
};
|
||||
percent(ui, "size", &mut p.size, &COMPOSITE_SIZE);
|
||||
percent(ui, "baseline", &mut p.baseline, &COMPOSITE_BASELINE);
|
||||
if scales {
|
||||
percent(ui, "hScale", &mut p.h_scale, &COMPOSITE_SCALE);
|
||||
percent(ui, "vScale", &mut p.v_scale, &COMPOSITE_SCALE);
|
||||
} else {
|
||||
ui.label("");
|
||||
ui.label("");
|
||||
}
|
||||
if center {
|
||||
ui.checkbox(&mut p.scale_at_center, tl!("Scale at Center"));
|
||||
} else {
|
||||
ui.label("");
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
/// Import…: the fonts of a picked file join those in the dialog, a font of the same name replaced,
|
||||
/// and the first of them is picked.
|
||||
fn import(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
|
||||
@@ -172,3 +172,111 @@ fn the_dialog_draws_with_and_without_fonts() {
|
||||
frame(&mut app);
|
||||
assert_eq!(fonts(dialog(&mut app)).len(), 1);
|
||||
}
|
||||
|
||||
fn try_press(app: &mut VectorcraftApp, act: Action) -> Result<(), String> {
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
let r = run(app, &mut d, act);
|
||||
app.ui.dialog = Some(d);
|
||||
r
|
||||
}
|
||||
|
||||
fn sets(app: &mut VectorcraftApp) -> Vec<CustomCharSet> {
|
||||
fonts(dialog(app)).first().map(|f| f.custom.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Custom shows the font's custom character sets: New adds a set (based on the one picked), Add
|
||||
/// puts typed characters or the characters of Unicode codes into it once each, Delete takes the
|
||||
/// picked character out, Delete Set takes the set out; OK sets them with the font as one step.
|
||||
#[test]
|
||||
fn custom_character_sets_are_edited_in_the_dialog() {
|
||||
let mut app = app();
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::New);
|
||||
press(&mut app, Action::Custom);
|
||||
assert!(dialog(&mut app).bool("custom"));
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::NewSet);
|
||||
frame(&mut app);
|
||||
assert_eq!(dialog(&mut app).str("setName"), "Character Set 1");
|
||||
let kanji = fonts(dialog(&mut app))[0].parts.kanji.clone();
|
||||
assert_eq!(sets(&mut app)[0].part, kanji);
|
||||
// Direct Entry adds each character once.
|
||||
dialog(&mut app).fields.insert("entry".into(), json!("※A※"));
|
||||
press(&mut app, Action::AddChars);
|
||||
assert_eq!(sets(&mut app)[0].characters, "※A");
|
||||
assert_eq!(dialog(&mut app).str("entry"), "");
|
||||
// Unicode takes codes, with or without U+, and skips characters already in the set.
|
||||
dialog(&mut app).fields.insert("entryMode".into(), json!("unicode"));
|
||||
dialog(&mut app).fields.insert("entry".into(), json!("U+3042, 41"));
|
||||
press(&mut app, Action::AddChars);
|
||||
assert_eq!(sets(&mut app)[0].characters, "※Aあ");
|
||||
for bad in ["zz", "1F600", "0009"] {
|
||||
dialog(&mut app).fields.insert("entry".into(), json!(bad));
|
||||
assert!(try_press(&mut app, Action::AddChars).is_err(), "{bad}");
|
||||
assert_eq!(sets(&mut app)[0].characters, "※Aあ");
|
||||
}
|
||||
dialog(&mut app).fields.insert("entryMode".into(), json!("direct"));
|
||||
dialog(&mut app).fields.insert("entry".into(), json!("B😀"));
|
||||
assert!(try_press(&mut app, Action::AddChars).is_err());
|
||||
assert_eq!(sets(&mut app)[0].characters, "※Aあ");
|
||||
frame(&mut app);
|
||||
// Delete takes the picked character out.
|
||||
dialog(&mut app).fields.insert("char".into(), json!(0));
|
||||
press(&mut app, Action::DeleteChar);
|
||||
assert_eq!(sets(&mut app)[0].characters, "Aあ");
|
||||
// The set's name is edited in Name; New is based on the set picked.
|
||||
dialog(&mut app).fields.insert("setName".into(), json!("Letters"));
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::NewSet);
|
||||
let list = sets(&mut app);
|
||||
assert_eq!(list.iter().map(|s| (s.name.as_str(), s.characters.as_str())).collect::<Vec<_>>(), [("Letters", "Aあ"), ("Character Set 1", "Aあ")]);
|
||||
assert_eq!(dialog(&mut app).fields.get("set"), Some(&json!(1)));
|
||||
press(&mut app, Action::DeleteSet);
|
||||
assert_eq!(sets(&mut app).len(), 1);
|
||||
assert_eq!(dialog(&mut app).str("setName"), "Letters");
|
||||
frame(&mut app);
|
||||
dialog(&mut app).fields.insert("name".into(), json!("UI Composite Sets"));
|
||||
frame(&mut app);
|
||||
let before = steps(&app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
let f = &app.session.active().unwrap().doc.composite_fonts[0];
|
||||
assert_eq!((f.custom.len(), f.custom[0].name.as_str(), f.custom[0].characters.as_str()), (1, "Letters", "Aあ"));
|
||||
}
|
||||
|
||||
/// `ui.dialog.set` takes `custom`, `entry` and `char` as soon as the dialog opens, before Custom is
|
||||
/// clicked or anything is typed, and Add then adds the characters it set.
|
||||
#[test]
|
||||
fn custom_set_fields_are_set_right_after_open() {
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let font =
|
||||
json!({"name": "UI Composite Open", "parts": {"kanji": {"font": "Inter"}}, "custom": [{"name": "Marks", "characters": "", "font": "Inter"}]});
|
||||
app.run(COMMAND, json!({ "fonts": [font] })).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
for (field, value) in [("custom", json!(true)), ("entry", json!("※〒")), ("char", json!(0))] {
|
||||
let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value}));
|
||||
let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") };
|
||||
assert!(r.get("error").is_none(), "{field}: {r}");
|
||||
assert_eq!(dialog(&mut app).fields.get(field), Some(&value), "{field}");
|
||||
}
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::AddChars);
|
||||
assert_eq!(sets(&mut app)[0].characters, "※〒");
|
||||
}
|
||||
|
||||
/// Two sets of the same name keep the dialog open and change nothing.
|
||||
#[test]
|
||||
fn custom_sets_sharing_a_name_keep_the_dialog_open() {
|
||||
let mut app = app();
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::New);
|
||||
press(&mut app, Action::NewSet);
|
||||
press(&mut app, Action::NewSet);
|
||||
dialog(&mut app).fields.insert("setName".into(), json!("character set 1"));
|
||||
dialog(&mut app).fields.insert("custom".into(), json!(true));
|
||||
frame(&mut app);
|
||||
assert!(super::super::confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_some());
|
||||
assert!(names(&app).is_empty());
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The own controls of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) in the
|
||||
//! compact 3D dialog: the extrude and bevel options, or the revolve options, on the Object tab
|
||||
//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps and shading
|
||||
//! color on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D
|
||||
//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps, shading
|
||||
//! color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D
|
||||
//! effect shares.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -41,8 +41,8 @@ pub(super) fn revolve_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
}
|
||||
|
||||
/// The surface, then for Diffuse and Plastic the lights, Ambient Light, the highlight (Plastic
|
||||
/// only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps and Shading Color;
|
||||
/// Draw Hidden Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and
|
||||
/// only, and not for Rotate (Classic), which has no Plastic surface), Blend Steps, Shading Color and
|
||||
/// Preserve Spot Colors (unavailable while Shading Color is Custom); Draw Hidden Faces last, for Extrude & Bevel (Classic) (Revolve (Classic) draws every face, and
|
||||
/// Rotate (Classic)'s plane is seen from either side).
|
||||
pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let id = d.str("__effect");
|
||||
@@ -69,9 +69,11 @@ pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
}
|
||||
number(ui, d, "blendSteps", tl!("Blend Steps"), (1.0, 256.0), "", 0, None);
|
||||
choice(ui, d, "shadingColor", tl!("Shading Color"), &options_of(effect, "shadingColor"));
|
||||
if d.str("shadingColor") == "custom" {
|
||||
let custom = d.str("shadingColor") == "custom";
|
||||
if custom {
|
||||
shading_custom(ui, d);
|
||||
}
|
||||
ui.add_enabled_ui(!custom, |ui| toggle(ui, d, "preserveSpotColors", tl!("Preserve Spot Colors"), false));
|
||||
});
|
||||
if id == CLASSIC_EXTRUDE {
|
||||
toggle(ui, d, "drawHiddenFaces", tl!("Draw Hidden Faces"), false);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! The Variables dialogs (`variable.define`, `variable.bind`, `dataset.new`, `dataset.set`
|
||||
//! and `dataset.select`), opened from Window › Variables or the command palette.
|
||||
//! The Variables dialogs (`variable.define`, `variable.rename` as Variable Options, `variable.bind`,
|
||||
//! `dataset.new`, `dataset.set`, `dataset.rename` and `dataset.select`), opened from Window ›
|
||||
//! Variables or the command palette. Variable Options shows the variable's name and kind, and OK
|
||||
//! changes either or both.
|
||||
//!
|
||||
//! One dialog covers all of them: what it shows is what the command takes. A variable is a
|
||||
//! name and a kind; a dataset is a name and one field per variable — a text field for a
|
||||
@@ -24,6 +26,10 @@ pub const KIND: &str = "variables";
|
||||
/// renames.
|
||||
const EDITED: &str = "__dataset";
|
||||
|
||||
/// The field of Variable Options that names the variable its Name and Kind fields belong to.
|
||||
/// When the Variable field names another one, the next frame fills them from that one.
|
||||
const FILLED: &str = "__filled";
|
||||
|
||||
/// The kinds a variable can have, as `variable.define` names them.
|
||||
const KINDS: [&str; 4] = ["text", "visibility", "image", "graph"];
|
||||
|
||||
@@ -50,7 +56,7 @@ fn opened(id: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// The row `id` renames, which the dialog offers as a dropdown when the document has more than
|
||||
/// one. Variable Options renames the one the panel has highlighted, so it starts there.
|
||||
/// one. Variable Options edits the one the panel has highlighted, so it starts there.
|
||||
fn rename_of(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"variable.rename" => "variable",
|
||||
@@ -116,8 +122,14 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
|
||||
app.status(if key == "variable" { tl!("no variable to rename").to_string() } else { tl!("no data set to rename").to_string() });
|
||||
return true;
|
||||
}
|
||||
fields.insert(key.into(), json!(preselect.filter(|p| names.contains(p)).or(names.first().copied()).unwrap_or_default()));
|
||||
fields.insert("newName".into(), json!(""));
|
||||
let row = preselect.filter(|p| names.contains(p)).or(names.first().copied()).unwrap_or_default();
|
||||
fields.insert(key.into(), json!(row));
|
||||
if key == "variable" {
|
||||
// Variable Options starts on the variable's own name and kind.
|
||||
fill_variable_options(&vars, row, &mut fields);
|
||||
} else {
|
||||
fields.insert("newName".into(), json!(""));
|
||||
}
|
||||
}
|
||||
}
|
||||
fields.insert("__command".into(), json!(id));
|
||||
@@ -126,6 +138,16 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
|
||||
true
|
||||
}
|
||||
|
||||
/// Variable Options' Name and Kind fields for the variable `name`: its name, and its kind as
|
||||
/// `variable.rename` takes it (empty for a variable of unknown kind, which OK leaves as it is).
|
||||
/// [`FILLED`] records which variable they were filled for.
|
||||
fn fill_variable_options(vars: &Variables, name: &str, fields: &mut serde_json::Map<String, Value>) {
|
||||
let kind = vars.variable(name).map(|v| v.kind).filter(|k| *k != VariableKind::Unknown).map(VariableKind::label).unwrap_or_default();
|
||||
fields.insert("newName".into(), json!(name));
|
||||
fields.insert("kind".into(), json!(kind));
|
||||
fields.insert(FILLED.into(), json!(name));
|
||||
}
|
||||
|
||||
/// Whether `id` opens one of these dialogs.
|
||||
pub fn opens(id: &str) -> bool {
|
||||
opened(id).is_some()
|
||||
@@ -181,13 +203,25 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
text(ui, d, "name", 220.0);
|
||||
ui.end_row();
|
||||
label(ui, tl!("Kind"));
|
||||
// The kinds by their translated names; the field keeps the command's own word.
|
||||
let labels = kind_labels();
|
||||
let shown = KINDS.iter().position(|k| *k == d.str("kind")).and_then(|i| labels.get(i)).copied().unwrap_or_default();
|
||||
if let Some(kind) = widgets::dropdown_names(ui, ("variables-dd", "kind"), shown, &labels, 220.0).and_then(|i| KINDS.get(i)) {
|
||||
d.fields.insert("kind".into(), json!(kind));
|
||||
kind_dropdown(ui, d);
|
||||
ui.end_row();
|
||||
}
|
||||
// Variable Options: which variable, and its name and kind; picking another variable
|
||||
// starts its fields over from that one.
|
||||
"variable.rename" => {
|
||||
label(ui, tl!("Variable"));
|
||||
dropdown(ui, d, "variable", &variable_names, 220.0);
|
||||
let picked = d.str("variable");
|
||||
if picked != d.str(FILLED) {
|
||||
fill_variable_options(vars, &picked, &mut d.fields);
|
||||
}
|
||||
ui.end_row();
|
||||
label(ui, tl!("Name"));
|
||||
text(ui, d, "newName", 220.0);
|
||||
ui.end_row();
|
||||
label(ui, tl!("Kind"));
|
||||
kind_dropdown(ui, d);
|
||||
ui.end_row();
|
||||
}
|
||||
"variable.bind" => {
|
||||
label(ui, tl!("Variable"));
|
||||
@@ -199,15 +233,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
dropdown(ui, d, "name", &dataset_names, 220.0);
|
||||
ui.end_row();
|
||||
}
|
||||
// A rename: which row, and its new name.
|
||||
"variable.rename" | "dataset.rename" => {
|
||||
let (key, label_text, names) = if d.str("__command") == "variable.rename" {
|
||||
("variable", tl!("Variable").to_string(), &variable_names)
|
||||
} else {
|
||||
("name", tl!("Data Set").to_string(), &dataset_names)
|
||||
};
|
||||
label(ui, &label_text);
|
||||
dropdown(ui, d, key, names, 220.0);
|
||||
// Rename Data Set: which row, and its new name.
|
||||
"dataset.rename" => {
|
||||
label(ui, tl!("Data Set"));
|
||||
dropdown(ui, d, "name", &dataset_names, 220.0);
|
||||
ui.end_row();
|
||||
label(ui, tl!("New Name"));
|
||||
text(ui, d, "newName", 220.0);
|
||||
@@ -245,6 +274,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The Kind dropdown: the kinds by their translated names, while the `kind` field keeps the
|
||||
/// command's own word. An empty field (a variable of unknown kind) shows no kind.
|
||||
fn kind_dropdown(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let labels = kind_labels();
|
||||
let shown = KINDS.iter().position(|k| *k == d.str("kind")).and_then(|i| labels.get(i)).copied().unwrap_or_default();
|
||||
if let Some(kind) = widgets::dropdown_names(ui, ("variables-dd", "kind"), shown, &labels, 220.0).and_then(|i| KINDS.get(i)) {
|
||||
d.fields.insert("kind".into(), json!(kind));
|
||||
}
|
||||
}
|
||||
|
||||
/// A text field for `key`, written back as it is typed.
|
||||
fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> egui::Response {
|
||||
let mut s = d.str(key);
|
||||
@@ -263,8 +302,26 @@ fn set_text(d: &mut Dialog, key: &str, s: String) {
|
||||
|
||||
/// Records that `field` was typed in or set by `ui.dialog.set`: it no longer holds the row's
|
||||
/// empty text value, so emptying it unsets the variable.
|
||||
///
|
||||
/// In Variable Options, setting the Variable field clears Name and Kind, which OK reads as the
|
||||
/// variable's own name and kind, until a frame fills them from it; setting Name or Kind ties them
|
||||
/// to the variable already named, so no frame fills them over.
|
||||
pub(super) fn note_set(d: &mut Dialog, field: &str) {
|
||||
d.fields.remove(&empty_marker(field));
|
||||
if d.str("__command") == "variable.rename" {
|
||||
match field {
|
||||
// Null rather than removed, so `ui.dialog.set` can still set them.
|
||||
"variable" => {
|
||||
d.fields.insert("newName".into(), Value::Null);
|
||||
d.fields.insert("kind".into(), Value::Null);
|
||||
}
|
||||
"newName" | "kind" => {
|
||||
let row = d.str("variable");
|
||||
d.fields.insert(FILLED.into(), json!(row));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A checkbox for `key`, written back as it is toggled, which screen readers call `name`.
|
||||
@@ -329,7 +386,18 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let p = match cmd.as_str() {
|
||||
"variable.define" => json!({"name": name, "kind": d.str("kind")}),
|
||||
"variable.bind" => json!({"variable": d.str("variable")}),
|
||||
"variable.rename" => json!({"name": d.str("variable"), "newName": d.str("newName")}),
|
||||
// A Name the Variable field just cleared keeps the variable's name (an emptied one is sent,
|
||||
// and refused), and a cleared or empty Kind (a variable of unknown kind) keeps its kind.
|
||||
"variable.rename" => {
|
||||
let variable = d.str("variable");
|
||||
let new_name = if matches!(d.fields.get("newName"), Some(Value::Null) | None) { variable.clone() } else { d.str("newName") };
|
||||
// Any other kind value goes to the command, which refuses one it doesn't know.
|
||||
match d.fields.get("kind") {
|
||||
None | Some(Value::Null) => json!({"name": variable, "newName": new_name}),
|
||||
Some(Value::String(k)) if k.is_empty() => json!({"name": variable, "newName": new_name}),
|
||||
Some(k) => json!({"name": variable, "newName": new_name, "kind": k}),
|
||||
}
|
||||
}
|
||||
"dataset.rename" => json!({"name": name, "newName": d.str("newName")}),
|
||||
"dataset.new" | "dataset.set" => {
|
||||
let values = app.session.active().map(|st| values_of(d, &st.doc.variables)).unwrap_or_else(|| json!({}));
|
||||
@@ -550,4 +618,55 @@ mod tests {
|
||||
open(&mut app, "dataset.rename", Some("Row 1"));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("name"), "Row 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_options_shows_the_name_and_kind_and_changes_either() {
|
||||
let mut app = app_with_variables();
|
||||
let kind_of = |app: &VectorcraftApp, name: &str| app.session.active().and_then(|st| st.doc.variables.variable(name).map(|v| v.kind));
|
||||
open(&mut app, "variable.rename", Some("Badge"));
|
||||
{
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.str("newName"), d.str("kind")), ("Badge".to_string(), "visibility".to_string()));
|
||||
}
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("kind".into(), json!("text"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(kind_of(&app, "Badge"), Some(VariableKind::Text));
|
||||
|
||||
// OK with nothing changed adds no undo step, and an emptied Name is refused.
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
open(&mut app, "variable.rename", Some("Title"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
|
||||
open(&mut app, "variable.rename", Some("Title"));
|
||||
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "newName".into(), json!(""));
|
||||
assert!(crate::dialogs::confirm(&mut app).is_err());
|
||||
assert!(kind_of(&app, "Title").is_some(), "Title keeps its name");
|
||||
|
||||
// Setting the Variable field keeps that variable's own name and kind until Name or Kind is
|
||||
// set, and a frame fills them from it.
|
||||
open(&mut app, "variable.rename", Some("Title"));
|
||||
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "variable".into(), json!("Badge"));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!((kind_of(&app, "Title"), kind_of(&app, "Badge")), (Some(VariableKind::Text), Some(VariableKind::Text)));
|
||||
open(&mut app, "variable.rename", Some("Title"));
|
||||
{
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
crate::dialogs::set_field(d, "variable".into(), json!("Badge"));
|
||||
assert!(crate::dialogs::accepts_field(d, "newName") && crate::dialogs::accepts_field(d, "kind"), "Name and Kind stay settable");
|
||||
crate::dialogs::set_field(d, "newName".into(), json!("Flag"));
|
||||
crate::dialogs::set_field(d, "kind".into(), json!("visibility"));
|
||||
}
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!((kind_of(&app, "Flag"), kind_of(&app, "Title")), (Some(VariableKind::Visibility), Some(VariableKind::Text)));
|
||||
|
||||
// A frame after the Variable field changes fills Name and Kind from that variable.
|
||||
open(&mut app, "variable.rename", Some("Title"));
|
||||
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "variable".into(), json!("Flag"));
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.str("newName"), d.str("kind")), ("Flag".to_string(), "visibility".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
Align to Artboard Подравняване спрямо работната област
|
||||
Align to Glyph Bounds Подравняване спрямо границите на глифа
|
||||
Align to Key Object Подравняване спрямо ключов обект
|
||||
Align to Key Anchor Подравняване спрямо ключова опорна точка
|
||||
Align to Page Подравняване спрямо страницата
|
||||
Align to Path Подравняване спрямо пътя
|
||||
Align to Selection Подравняване спрямо селекцията
|
||||
@@ -3654,6 +3655,8 @@ digits Malayalam Малаялам
|
||||
Kana Кана
|
||||
Numerals Цифри
|
||||
Scale at Center Мащабиране от центъра
|
||||
Delete Set Изтриване на набор
|
||||
Direct Entry Директно въвеждане
|
||||
Up/Down: Нагоре/надолу:
|
||||
Left/Right: Наляво/надясно:
|
||||
Tate-chu-yoko Up/Down Тате-чу-йоко нагоре/надолу
|
||||
@@ -5050,6 +5053,11 @@ axis Both И двете
|
||||
@msg Imported library {name} Импортирана библиотека {name}
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Правило за RGB:
|
||||
CMYK Policy: Правило за CMYK:
|
||||
Preserve Embedded Profiles Запазване на вградените профили
|
||||
Convert to Working Space Преобразуване в работното пространство
|
||||
Preserve Numbers Запазване на числата
|
||||
Texture Текстура
|
||||
Craquelure… Кракелюр…
|
||||
Grain… Зърнистост…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -986,6 +986,11 @@
|
||||
NTSC Colors NTSC boje
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB pravilo:
|
||||
CMYK Policy: CMYK pravilo:
|
||||
Preserve Embedded Profiles Zadrži ugrađene profile
|
||||
Convert to Working Space Pretvori u radni prostor
|
||||
Preserve Numbers Zadrži brojeve
|
||||
CMYK CMYK
|
||||
Texture Tekstura
|
||||
Craquelure… Krakelura…
|
||||
@@ -1492,6 +1497,7 @@ lighting Light Svjetlo
|
||||
Align to Artboard Poravnaj s radnom pločom
|
||||
Align to Glyph Bounds Poravnaj s granicama glifa
|
||||
Align to Key Object Poravnaj s ključnim objektom
|
||||
Align to Key Anchor Poravnaj s ključnom sidrenom tačkom
|
||||
Align to Selection Poravnaj prema odabiru
|
||||
Align To: Poravnaj s:
|
||||
Cancel Key Object Otkaži ključni objekat
|
||||
@@ -1641,6 +1647,8 @@ digits Malayalam Malajalam
|
||||
Kana Kana
|
||||
Numerals Brojevi
|
||||
Scale at Center Skaliraj od centra
|
||||
Delete Set Izbriši skup
|
||||
Direct Entry Direktan unos
|
||||
Up/Down: Gore/dolje:
|
||||
Left/Right: Lijevo/desno:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko gore/dolje
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -242,6 +242,7 @@
|
||||
Align to Artboard Alinea al tauler
|
||||
Align to Glyph Bounds Alinea als límits del glif
|
||||
Align to Key Object Alinea a l’objecte clau
|
||||
Align to Key Anchor Alinea al punt d’ancoratge clau
|
||||
Align to Page Alinea a la pàgina
|
||||
Align to Path Alinea al traçat
|
||||
Align to Selection Alinea a la selecció
|
||||
@@ -764,6 +765,11 @@ antiAlias Sharp Nítid
|
||||
CMYK Equivalents Equivalents CMYK
|
||||
CMYK profile in effect Perfil CMYK en vigor
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Política RGB:
|
||||
CMYK Policy: Política CMYK:
|
||||
Preserve Embedded Profiles Conserva els perfils incrustats
|
||||
Convert to Working Space Converteix a l'espai de treball
|
||||
Preserve Numbers Conserva els números
|
||||
Coarse Dots Punts gruixuts
|
||||
Collapse Panel Group Replega el grup de panells
|
||||
Collapse Panels to Icons Replega els panells a icones
|
||||
@@ -4772,6 +4778,8 @@ digits Malayalam Malaiàlam
|
||||
Kana Kana
|
||||
Numerals Xifres
|
||||
Scale at Center Escala des del centre
|
||||
Delete Set Suprimeix el joc
|
||||
Direct Entry Entrada directa
|
||||
Up/Down: Amunt/avall:
|
||||
Left/Right: Esquerra/dreta:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko amunt/avall
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1005,6 +1005,11 @@
|
||||
NTSC Colors Barvy NTSC
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Zásada RGB:
|
||||
CMYK Policy: Zásada CMYK:
|
||||
Preserve Embedded Profiles Zachovat vložené profily
|
||||
Convert to Working Space Převést do pracovního prostoru
|
||||
Preserve Numbers Zachovat čísla
|
||||
CMYK CMYK
|
||||
Texture Textura
|
||||
Craquelure… Krakelování…
|
||||
@@ -1520,6 +1525,7 @@ lighting Light Světlo
|
||||
Align to Artboard Zarovnat k pracovní ploše
|
||||
Align to Glyph Bounds Zarovnat k hranicím glyfů
|
||||
Align to Key Object Zarovnat ke klíčovému objektu
|
||||
Align to Key Anchor Zarovnat ke klíčovému kotevnímu bodu
|
||||
Align to Selection Zarovnat k výběru
|
||||
Align To: Zarovnat k:
|
||||
Cancel Key Object Zrušit klíčový objekt
|
||||
@@ -1712,6 +1718,8 @@ digits Malayalam Malajálamské
|
||||
Kana Kana
|
||||
Numerals Číslice
|
||||
Scale at Center Měřítko od středu
|
||||
Delete Set Odstranit sadu
|
||||
Direct Entry Přímé zadání
|
||||
Up/Down: Nahoru/dolů:
|
||||
Left/Right: Vlevo/vpravo:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko nahoru/dolů
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1538,6 +1538,11 @@
|
||||
NTSC Colors NTSC-farver
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-politik:
|
||||
CMYK Policy: CMYK-politik:
|
||||
Preserve Embedded Profiles Bevar indlejrede profiler
|
||||
Convert to Working Space Konverter til arbejdsfarverum
|
||||
Preserve Numbers Bevar tal
|
||||
CMYK CMYK
|
||||
Texture Tekstur
|
||||
Craquelure… Krakelering…
|
||||
@@ -2037,6 +2042,7 @@ lighting Light Lys
|
||||
Align to Artboard Juster til tegnebræt
|
||||
Align to Glyph Bounds Juster til glyfafgrænsning
|
||||
Align to Key Object Juster til nøgleobjekt
|
||||
Align to Key Anchor Juster til nøgleankerpunkt
|
||||
Align to Selection Juster til markering
|
||||
Align To: Juster til:
|
||||
Cancel Key Object Annullér nøgleobjekt
|
||||
@@ -2228,6 +2234,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Tal
|
||||
Scale at Center Skalér fra midten
|
||||
Delete Set Slet sæt
|
||||
Direct Entry Direkte indtastning
|
||||
Up/Down: Op/ned:
|
||||
Left/Right: Venstre/højre:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko op/ned
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -135,6 +135,7 @@
|
||||
Align to Artboard An Zeichenfläche ausrichten
|
||||
Align to Glyph Bounds An Glyphenbegrenzung ausrichten
|
||||
Align to Key Object An Basisobjekt ausrichten
|
||||
Align to Key Anchor An Basisankerpunkt ausrichten
|
||||
Align to Page An Seite ausrichten
|
||||
Align to Path An Pfad ausrichten
|
||||
Align to Selection An Auswahl ausrichten
|
||||
@@ -3738,6 +3739,8 @@ effect Points Punkte
|
||||
Kana Kana
|
||||
Numerals Ziffern
|
||||
Scale at Center Von der Mitte aus skalieren
|
||||
Delete Set Satz löschen
|
||||
Direct Entry Direkteingabe
|
||||
Up/Down: Oben/Unten:
|
||||
Left/Right: Links/Rechts:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko oben/unten
|
||||
@@ -5378,6 +5381,11 @@ theme Appearance Erscheinungsbild
|
||||
The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Die Hauptfarbe wird zur Konturfarbe. Die anderen Farben wandern ebenso weit um den Farbkreis wie die Hauptfarbe und behalten ihre Sättigung und Helligkeit.
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-Richtlinie:
|
||||
CMYK Policy: CMYK-Richtlinie:
|
||||
Preserve Embedded Profiles Eingebettete Profile beibehalten
|
||||
Convert to Working Space In Arbeitsfarbraum konvertieren
|
||||
Preserve Numbers Werte beibehalten
|
||||
# PSD files.
|
||||
@msg not a PSD file keine PSD-Datei
|
||||
@msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode PSD-Dateien im Mehrkanalmodus können nicht gelesen werden: Speichern Sie die Datei im RGB-, CMYK- oder Graustufenmodus
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -140,6 +140,7 @@
|
||||
Align to Artboard Στοίχιση ως προς τον πίνακα σχεδίασης
|
||||
Align to Glyph Bounds Στοίχιση στα όρια των γλυφών
|
||||
Align to Key Object Στοίχιση ως προς το βασικό αντικείμενο
|
||||
Align to Key Anchor Στοίχιση ως προς το βασικό σημείο αγκύρωσης
|
||||
Align to Page Στοίχιση ως προς τη σελίδα
|
||||
Align to Path Στοίχιση ως προς τη διαδρομή
|
||||
Align to Selection Στοίχιση ως προς την επιλογή
|
||||
@@ -4273,6 +4274,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
Kana Κάνα
|
||||
Numerals Αριθμοί
|
||||
Scale at Center Κλιμάκωση από το κέντρο
|
||||
Delete Set Διαγραφή συνόλου
|
||||
Direct Entry Άμεση καταχώριση
|
||||
Up/Down: Πάνω/Κάτω:
|
||||
Left/Right: Αριστερά/Δεξιά:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko πάνω/κάτω
|
||||
@@ -5350,6 +5353,11 @@ digits Malayalam Μαλαγιάλαμ
|
||||
@msg Imported library {name} Εισήχθη η βιβλιοθήκη {name}
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Πολιτική RGB:
|
||||
CMYK Policy: Πολιτική CMYK:
|
||||
Preserve Embedded Profiles Διατήρηση ενσωματωμένων προφίλ
|
||||
Convert to Working Space Μετατροπή στον χώρο εργασίας
|
||||
Preserve Numbers Διατήρηση αριθμών
|
||||
System Title Bar Γραμμή τίτλου συστήματος
|
||||
VectorCraft Title Bar on Every Desktop Γραμμή τίτλου του VectorCraft σε κάθε επιφάνεια εργασίας
|
||||
The VECTORCRAFT_TITLEBAR environment variable chooses the title bar while it is set. Όσο είναι ορισμένη, η μεταβλητή περιβάλλοντος VECTORCRAFT_TITLEBAR επιλέγει τη γραμμή τίτλου.
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -160,6 +160,7 @@
|
||||
Align to Artboard Alinear con la mesa de trabajo
|
||||
Align to Glyph Bounds Alinear con los límites del glifo
|
||||
Align to Key Object Alinear con el objeto clave
|
||||
Align to Key Anchor Alinear con el punto de ancla clave
|
||||
Align to Page Alinear con la página
|
||||
Align to Path Alinear con el trazado
|
||||
Align to Selection Alinear con la selección
|
||||
@@ -3787,6 +3788,8 @@ digits Malayalam Malayálam
|
||||
Kana Kana
|
||||
Numerals Números
|
||||
Scale at Center Escalar desde el centro
|
||||
Delete Set Eliminar juego
|
||||
Direct Entry Entrada directa
|
||||
Up/Down: Arriba/abajo:
|
||||
Left/Right: Izquierda/derecha:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko arriba/abajo
|
||||
@@ -5396,6 +5399,11 @@ axis Both Ambos
|
||||
@msg Imported library {name} Biblioteca {name} importada
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Norma RGB:
|
||||
CMYK Policy: Norma CMYK:
|
||||
Preserve Embedded Profiles Conservar perfiles incrustados
|
||||
Convert to Working Space Convertir en espacio de trabajo
|
||||
Preserve Numbers Conservar números
|
||||
Texture Textura
|
||||
Craquelure… Craquelado…
|
||||
Grain… Granulado…
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -989,6 +989,11 @@
|
||||
NTSC Colors NTSC-värit
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-käytäntö:
|
||||
CMYK Policy: CMYK-käytäntö:
|
||||
Preserve Embedded Profiles Säilytä upotetut profiilit
|
||||
Convert to Working Space Muunna työväriavaruuteen
|
||||
Preserve Numbers Säilytä lukuarvot
|
||||
CMYK CMYK
|
||||
Texture Tekstuuri
|
||||
Craquelure… Krakelyyri…
|
||||
@@ -1494,6 +1499,7 @@ lighting Light Valo
|
||||
Align to Artboard Tasaa piirtoalustaan
|
||||
Align to Glyph Bounds Tasaa merkin rajoihin
|
||||
Align to Key Object Tasaa avainobjektiin
|
||||
Align to Key Anchor Tasaa avainankkuripisteeseen
|
||||
Align to Selection Tasaa valintaan
|
||||
Align To: Tasaa:
|
||||
Cancel Key Object Peruuta avainobjekti
|
||||
@@ -1685,6 +1691,8 @@ digits Malayalam Malajalam
|
||||
Kana Kana
|
||||
Numerals Numerot
|
||||
Scale at Center Skaalaa keskeltä
|
||||
Delete Set Poista merkistö
|
||||
Direct Entry Suora syöttö
|
||||
Up/Down: Ylös/alas:
|
||||
Left/Right: Vasen/oikea:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko ylös/alas
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -161,6 +161,7 @@
|
||||
Align to Artboard Aligner sur le plan de travail
|
||||
Align to Glyph Bounds Aligner sur les limites du glyphe
|
||||
Align to Key Object Aligner sur l’objet clé
|
||||
Align to Key Anchor Aligner sur le point d’ancrage clé
|
||||
Align to Page Aligner sur la page
|
||||
Align to Path Aligner sur le tracé
|
||||
Align to Selection Aligner sur la sélection
|
||||
@@ -3779,6 +3780,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Chiffres
|
||||
Scale at Center Mettre à l’échelle depuis le centre
|
||||
Delete Set Supprimer le jeu
|
||||
Direct Entry Saisie directe
|
||||
Up/Down: Haut/bas :
|
||||
Left/Right: Gauche/droite :
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko haut/bas
|
||||
@@ -5401,6 +5404,11 @@ axis Both Les deux
|
||||
@msg Imported library {name} Bibliothèque {name} importée
|
||||
RGB: RVB :
|
||||
CMYK: CMJN :
|
||||
RGB Policy: Règle RVB :
|
||||
CMYK Policy: Règle CMJN :
|
||||
Preserve Embedded Profiles Conserver les profils incorporés
|
||||
Convert to Working Space Convertir en espace de travail
|
||||
Preserve Numbers Conserver les valeurs numériques
|
||||
Texture Texture
|
||||
Craquelure… Craquelure…
|
||||
Grain… Grain…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -188,6 +188,7 @@
|
||||
Align to Artboard આર્ટબોર્ડ પર સંરેખિત કરો
|
||||
Align to Glyph Bounds ગ્લિફ સીમા પર સંરેખિત કરો
|
||||
Align to Key Object કી ઑબ્જેક્ટ પર સંરેખિત કરો
|
||||
Align to Key Anchor કી એન્કર બિંદુ પર સંરેખિત કરો
|
||||
Align to Page પેજ પર સંરેખિત કરો
|
||||
Align to Path પાથ પર સંરેખિત કરો
|
||||
Align to Pixel Grid પિક્સેલ ગ્રિડ પર સંરેખિત કરો
|
||||
@@ -471,6 +472,11 @@
|
||||
CMYK Images CMYK ઇમેજ
|
||||
CMYK colours print with their own values; off, they go through the colour settings too. CMYK રંગો પોતાની કિંમતો સાથે છાપે છે; બંધ હોય ત્યારે તે રંગ સેટિંગમાંથી પણ પસાર થાય છે.
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB નીતિ:
|
||||
CMYK Policy: CMYK નીતિ:
|
||||
Preserve Embedded Profiles એમ્બેડ કરેલી પ્રોફાઇલ જાળવો
|
||||
Convert to Working Space કાર્યકારી સ્પેસમાં રૂપાંતરિત કરો
|
||||
Preserve Numbers સંખ્યાઓ જાળવો
|
||||
CSS Properties CSS ગુણધર્મો
|
||||
Calligraphic Brush કેલિગ્રાફિક બ્રશ
|
||||
Calligraphic Brush Options કેલિગ્રાફિક બ્રશ વિકલ્પો
|
||||
@@ -3299,6 +3305,8 @@
|
||||
Scale Text Attributes ટેક્સ્ટ ગુણધર્મો સ્કેલ કરો
|
||||
Scale Tool સ્કેલ ટૂલ
|
||||
Scale at Center કેન્દ્રથી સ્કેલ કરો
|
||||
Delete Set સેટ કાઢી નાખો
|
||||
Direct Entry સીધી એન્ટ્રી
|
||||
Scale in Perspective પર્સ્પેક્ટિવમાં સ્કેલ કરો
|
||||
Scale to Fit Artboard આર્ટબોર્ડમાં બંધબેસતું સ્કેલ કરો
|
||||
Scale: સ્કેલ:
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -283,6 +283,7 @@
|
||||
Align to Corners and Ends कोनों और सिरों पर संरेखित करें
|
||||
Align to Glyph Bounds ग्लिफ़ की सीमाओं पर संरेखित करें
|
||||
Align to Key Object मुख्य ऑब्जेक्ट पर संरेखित करें
|
||||
Align to Key Anchor मुख्य एंकर पॉइंट पर संरेखित करें
|
||||
Align to Page पेज पर संरेखित करें
|
||||
Align to Path पाथ पर संरेखित करें
|
||||
Align to Selection सिलेक्शन पर संरेखित करें
|
||||
@@ -891,6 +892,11 @@ antiAlias Sharp शार्प
|
||||
CMYK Images CMYK इमेज
|
||||
CMYK profile in effect इफ़ेक्ट में CMYK प्रोफ़ाइल
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB नीति:
|
||||
CMYK Policy: CMYK नीति:
|
||||
Preserve Embedded Profiles एम्बेड की गई प्रोफ़ाइल बनाए रखें
|
||||
Convert to Working Space वर्किंग स्पेस में बदलें
|
||||
Preserve Numbers संख्याएँ बनाए रखें
|
||||
Coarse Dots मोटे बिंदु
|
||||
Coincidence: संयोग:
|
||||
Collapse Panel Group पैनल समूह संक्षिप्त करें
|
||||
@@ -5157,6 +5163,8 @@ antiAlias Sharp शार्प
|
||||
Kana काना
|
||||
Numerals अंक
|
||||
Scale at Center केंद्र से आकार बदलें
|
||||
Delete Set सेट हटाएँ
|
||||
Direct Entry सीधी प्रविष्टि
|
||||
Technical Drawing तकनीकी ड्राइंग
|
||||
Telugu तेलुगु
|
||||
Temperature तापमान
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -229,6 +229,7 @@
|
||||
Align to Artboard Igazítás a rajztáblához
|
||||
Align to Glyph Bounds Igazítás a glifák határaihoz
|
||||
Align to Key Object Igazítás a kulcsobjektumhoz
|
||||
Align to Key Anchor Igazítás a kulcs-horgonyponthoz
|
||||
Align to Page Igazítás az oldalhoz
|
||||
Align to Path Igazítás az útvonalhoz
|
||||
Align to Selection Igazítás a kijelöléshez
|
||||
@@ -695,6 +696,11 @@ font-technology Variable Változó
|
||||
CMYK Equivalents CMYK-megfelelők
|
||||
CMYK profile in effect Érvényes CMYK-profil
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-házirend:
|
||||
CMYK Policy: CMYK-házirend:
|
||||
Preserve Embedded Profiles Beágyazott profilok megtartása
|
||||
Convert to Working Space Konvertálás a munkaszíntérbe
|
||||
Preserve Numbers Számértékek megtartása
|
||||
Coarse Dots Durva pontok
|
||||
Collapse Panels to Icons Panelek ikonná csukása
|
||||
Collapse to Icons Ikonná csukás
|
||||
@@ -4455,6 +4461,8 @@ mark-style Japanese Japán
|
||||
Kana Kana
|
||||
Numerals Számjegyek
|
||||
Scale at Center Méretezés középről
|
||||
Delete Set Készlet törlése
|
||||
Direct Entry Közvetlen bevitel
|
||||
Up/Down: Fel/le:
|
||||
Left/Right: Balra/jobbra:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko fel/le
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -928,6 +928,11 @@
|
||||
NTSC Colors Warna NTSC
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Kebijakan RGB:
|
||||
CMYK Policy: Kebijakan CMYK:
|
||||
Preserve Embedded Profiles Pertahankan Profil Tersemat
|
||||
Convert to Working Space Konversi ke Ruang Kerja
|
||||
Preserve Numbers Pertahankan Angka
|
||||
CMYK CMYK
|
||||
Texture Tekstur
|
||||
Craquelure… Craquelure…
|
||||
@@ -1427,6 +1432,7 @@ lighting Light Cahaya
|
||||
Align to Artboard Ratakan ke artboard
|
||||
Align to Glyph Bounds Ratakan ke batas glif
|
||||
Align to Key Object Ratakan ke objek kunci
|
||||
Align to Key Anchor Ratakan ke titik jangkar kunci
|
||||
Align to Selection Ratakan ke seleksi
|
||||
Align To: Ratakan ke:
|
||||
Cancel Key Object Batalkan objek kunci
|
||||
@@ -1576,6 +1582,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Angka
|
||||
Scale at Center Skalakan dari tengah
|
||||
Delete Set Hapus set
|
||||
Direct Entry Entri langsung
|
||||
Up/Down: Atas/bawah:
|
||||
Left/Right: Kiri/kanan:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko atas/bawah
|
||||
|
||||
|
@@ -160,6 +160,7 @@
|
||||
Align to Artboard Allinea alla tavola da disegno
|
||||
Align to Glyph Bounds Allinea ai limiti del glifo
|
||||
Align to Key Object Allinea all'oggetto chiave
|
||||
Align to Key Anchor Allinea al punto di ancoraggio chiave
|
||||
Align to Page Allinea alla pagina
|
||||
Align to Path Allinea al tracciato
|
||||
Align to Selection Allinea alla selezione
|
||||
@@ -3833,6 +3834,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Numeri
|
||||
Scale at Center Ridimensiona dal centro
|
||||
Delete Set Elimina set
|
||||
Direct Entry Immissione diretta
|
||||
Up/Down: Su/giù:
|
||||
Left/Right: Sinistra/destra:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko su/giù
|
||||
@@ -5446,6 +5449,11 @@ axis Both Entrambi
|
||||
@msg Imported library {name} Libreria {name} importata
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Criterio RGB:
|
||||
CMYK Policy: Criterio CMYK:
|
||||
Preserve Embedded Profiles Mantieni profili incorporati
|
||||
Convert to Working Space Converti nello spazio di lavoro
|
||||
Preserve Numbers Mantieni valori numerici
|
||||
Texture Texture
|
||||
Craquelure… Craquelé…
|
||||
Grain… Granulosità…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1077,6 +1077,7 @@ digits Malayalam マラヤーラム数字
|
||||
Align to Artboard アートボードに整列
|
||||
Align to Glyph Bounds 字形の境界に整列
|
||||
Align to Key Object キーオブジェクトに整列
|
||||
Align to Key Anchor キーアンカーポイントに整列
|
||||
Align to Page ページに沿う
|
||||
Align to Path パスに沿う
|
||||
Align to Selection 選択範囲に整列
|
||||
@@ -4161,6 +4162,8 @@ file-filter Templates テンプレート
|
||||
Kana かな
|
||||
Numerals 数字
|
||||
Scale at Center 中心から拡大・縮小
|
||||
Delete Set セットを削除
|
||||
Direct Entry 直接入力
|
||||
Up/Down: 上下:
|
||||
Left/Right: 左右:
|
||||
Tate-chu-yoko Up/Down 縦中横の上下
|
||||
@@ -5487,6 +5490,11 @@ swatch Bright Violet ビビッドバイオレット
|
||||
@msg Imported library {name} ライブラリ {name} を読み込みました
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB ポリシー:
|
||||
CMYK Policy: CMYK ポリシー:
|
||||
Preserve Embedded Profiles 埋め込まれたプロファイルを保持
|
||||
Convert to Working Space 作業用スペースに変換
|
||||
Preserve Numbers カラー値を保持
|
||||
Texture テクスチャ
|
||||
Craquelure… クラッキング…
|
||||
Grain… 粒状…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -894,6 +894,11 @@
|
||||
NTSC Colors NTSC ფერები
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB წესი:
|
||||
CMYK Policy: CMYK წესი:
|
||||
Preserve Embedded Profiles ჩაშენებული პროფილების შენარჩუნება
|
||||
Convert to Working Space სამუშაო სივრცეში გადაყვანა
|
||||
Preserve Numbers რიცხვების შენარჩუნება
|
||||
CMYK CMYK
|
||||
Texture ტექსტურა
|
||||
Craquelure… კრაკელიური…
|
||||
@@ -1366,6 +1371,7 @@ lighting Light სინათლე
|
||||
Align to Artboard სამუშაო დაფაზე სწორება
|
||||
Align to Glyph Bounds გლიფის საზღვრებზე სწორება
|
||||
Align to Key Object საკვანძო ობიექტზე სწორება
|
||||
Align to Key Anchor საკვანძო საყრდენ წერტილზე სწორება
|
||||
Align to Selection მონიშნულზე სწორება
|
||||
Align To: სწორება:
|
||||
Cancel Key Object საკვანძო ობიექტის გაუქმება
|
||||
@@ -1556,6 +1562,8 @@ digits Malayalam მალაიალამური
|
||||
Kana კანა
|
||||
Numerals ციფრები
|
||||
Scale at Center ცენტრიდან მასშტაბირება
|
||||
Delete Set ნაკრების წაშლა
|
||||
Direct Entry პირდაპირი შეყვანა
|
||||
Up/Down: ზემოთ/ქვემოთ:
|
||||
Left/Right: მარცხნივ/მარჯვნივ:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko ზემოთ/ქვემოთ
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1067,6 +1067,7 @@ digits Malayalam 말라얄람어
|
||||
Align to Artboard 아트보드에 정렬
|
||||
Align to Glyph Bounds 글리프 경계에 정렬
|
||||
Align to Key Object 키 개체에 정렬
|
||||
Align to Key Anchor 키 앵커 포인트에 정렬
|
||||
Align to Page 페이지에 정렬
|
||||
Align to Path 패스에 정렬
|
||||
Align to Selection 선택 영역에 정렬
|
||||
@@ -4149,6 +4150,8 @@ file-filter Templates 템플릿
|
||||
Kana 가나
|
||||
Numerals 숫자
|
||||
Scale at Center 중심에서 크기 조정
|
||||
Delete Set 집합 삭제
|
||||
Direct Entry 직접 입력
|
||||
Up/Down: 위/아래:
|
||||
Left/Right: 왼쪽/오른쪽:
|
||||
Tate-chu-yoko Up/Down 다테추요코 위/아래
|
||||
@@ -5414,6 +5417,11 @@ theme Appearance 외관
|
||||
@msg Imported library {name} 라이브러리 {name}을(를) 가져왔습니다
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB 정책:
|
||||
CMYK Policy: CMYK 정책:
|
||||
Preserve Embedded Profiles 포함된 프로필 유지
|
||||
Convert to Working Space 작업 공간으로 변환
|
||||
Preserve Numbers 숫자 유지
|
||||
Texture 텍스처
|
||||
Craquelure… 크랙…
|
||||
Grain… 그레인…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1446,6 +1446,11 @@
|
||||
NTSC Colors NTSC-kleuren
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-beleid:
|
||||
CMYK Policy: CMYK-beleid:
|
||||
Preserve Embedded Profiles Ingesloten profielen behouden
|
||||
Convert to Working Space Omzetten naar werkruimte
|
||||
Preserve Numbers Waarden behouden
|
||||
CMYK CMYK
|
||||
Texture Textuur
|
||||
Craquelure… Craquelure…
|
||||
@@ -1945,6 +1950,7 @@ lighting Light Licht
|
||||
Align to Artboard Uitlijnen op tekengebied
|
||||
Align to Glyph Bounds Uitlijnen op glyphbegrenzing
|
||||
Align to Key Object Uitlijnen op sleutelobject
|
||||
Align to Key Anchor Uitlijnen op sleutelankerpunt
|
||||
Align to Selection Uitlijnen op selectie
|
||||
Align To: Uitlijnen op:
|
||||
Cancel Key Object Sleutelobject annuleren
|
||||
@@ -2136,6 +2142,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Cijfers
|
||||
Scale at Center Schalen vanuit het midden
|
||||
Delete Set Set verwijderen
|
||||
Direct Entry Directe invoer
|
||||
Up/Down: Omhoog/omlaag:
|
||||
Left/Right: Links/rechts:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko omhoog/omlaag
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -946,6 +946,11 @@
|
||||
NTSC Colors Kolory NTSC
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Zasada RGB:
|
||||
CMYK Policy: Zasada CMYK:
|
||||
Preserve Embedded Profiles Zachowaj osadzone profile
|
||||
Convert to Working Space Konwertuj do przestrzeni roboczej
|
||||
Preserve Numbers Zachowaj wartości liczbowe
|
||||
CMYK CMYK
|
||||
Texture Tekstura
|
||||
Craquelure… Spękania…
|
||||
@@ -1433,6 +1438,7 @@ lighting Light Światło
|
||||
Align to Artboard Wyrównaj do obszaru kompozycji
|
||||
Align to Glyph Bounds Wyrównaj do granic glifów
|
||||
Align to Key Object Wyrównaj do obiektu kluczowego
|
||||
Align to Key Anchor Wyrównaj do kluczowego punktu kontrolnego
|
||||
Align to Selection Wyrównaj do zaznaczenia
|
||||
Align To: Wyrównaj do:
|
||||
Cancel Key Object Anuluj obiekt kluczowy
|
||||
@@ -1624,6 +1630,8 @@ digits Malayalam Malajalam
|
||||
Kana Kana
|
||||
Numerals Cyfry
|
||||
Scale at Center Skaluj od środka
|
||||
Delete Set Usuń zestaw
|
||||
Direct Entry Wprowadzanie bezpośrednie
|
||||
Up/Down: W górę/w dół:
|
||||
Left/Right: W lewo/w prawo:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko w górę/w dół
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -164,6 +164,7 @@
|
||||
Align to Artboard Alinhar à Mesa de Trabalho
|
||||
Align to Glyph Bounds Alinhar aos Limites do Glifo
|
||||
Align to Key Object Alinhar ao Objeto-Chave
|
||||
Align to Key Anchor Alinhar ao Ponto de Ancoragem-Chave
|
||||
Align to Page Alinhar à Página
|
||||
Align to Path Alinhar ao Caminho
|
||||
Align to Selection Alinhar à Seleção
|
||||
@@ -3505,6 +3506,11 @@ imageTrace Outline Contorno
|
||||
NTSC Colors Cores NTSC
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Política RGB:
|
||||
CMYK Policy: Política CMYK:
|
||||
Preserve Embedded Profiles Preservar perfis incorporados
|
||||
Convert to Working Space Converter para espaço de trabalho
|
||||
Preserve Numbers Preservar números
|
||||
Texture Textura
|
||||
Craquelure… Craquelê…
|
||||
Grain… Granulação…
|
||||
@@ -5353,6 +5359,8 @@ axis Both Ambos
|
||||
Kana Kana
|
||||
Numerals Números
|
||||
Scale at Center Dimensionar a partir do centro
|
||||
Delete Set Excluir conjunto
|
||||
Direct Entry Entrada direta
|
||||
Up/Down: Para Cima/Para Baixo:
|
||||
Left/Right: Esquerda/Direita:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko Para Cima/Para Baixo
|
||||
|
||||
|
Can't render this file because it is too large.
|
File diff suppressed because it is too large
Load Diff
@@ -148,6 +148,7 @@
|
||||
Align to Artboard Justera mot rityta
|
||||
Align to Glyph Bounds Justera mot glyfgränser
|
||||
Align to Key Object Justera mot nyckelobjekt
|
||||
Align to Key Anchor Justera mot nyckelankarpunkt
|
||||
Align to Page Justera mot sida
|
||||
Align to Path Justera mot bana
|
||||
Align to Selection Justera mot markering
|
||||
@@ -3709,6 +3710,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Siffror
|
||||
Scale at Center Skala från mitten
|
||||
Delete Set Ta bort uppsättning
|
||||
Direct Entry Direktinmatning
|
||||
Up/Down: Upp/ned:
|
||||
Left/Right: Vänster/höger:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko upp/ned
|
||||
@@ -5303,6 +5306,11 @@ axis Both Båda
|
||||
@msg Imported library {name} Importerade biblioteket {name}
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB-princip:
|
||||
CMYK Policy: CMYK-princip:
|
||||
Preserve Embedded Profiles Behåll inbäddade profiler
|
||||
Convert to Working Space Konvertera till arbetsfärgrymd
|
||||
Preserve Numbers Behåll värden
|
||||
Texture Textur
|
||||
Craquelure… Krakelering…
|
||||
Grain… Korn…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4041,6 +4041,27 @@ fn dataset_import_cell_errors_are_translated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Russian shows command, script and file messages in Russian: a whole message, a message that
|
||||
/// begins with a feature name, messages with a name, a number or a command id filled in, and the
|
||||
/// two messages whose catalog rows escape a backslash.
|
||||
#[test]
|
||||
fn russian_translates_command_script_and_file_messages() {
|
||||
let ru = Lang::from_code("ru").expect("registered");
|
||||
for (english, russian) in [
|
||||
("CSV is empty", "CSV пуст"),
|
||||
("Offset Path: the path is too complex to offset", "Смещение контура: контур слишком сложен для смещения"),
|
||||
("no swatch named `Gold`", "нет образца с именем `Gold`"),
|
||||
("object 12 is not an Intertwine group", "объект 12 не является группой переплетения"),
|
||||
("no slice 4 in the image (see slice.list)", "в изображении нет фрагмента 4 (см. slice.list)"),
|
||||
("give origin: [x, y], or reset: true", "укажите origin: [x, y] или reset: true"),
|
||||
("`kinsoku` must be \"none\", \"hard\" or \"soft\"", "`kinsoku` должно быть \"none\", \"hard\" или \"soft\""),
|
||||
("\\ at end of pattern", "\\ в конце шаблона"),
|
||||
("a \\u escape needs four hexadecimal digits", "после \\u нужны четыре шестнадцатеричные цифры"),
|
||||
] {
|
||||
assert_eq!(message(ru, english), russian, "{english}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The errors of the parameter checks that many commands share (a number given as text, a missing
|
||||
/// number or index, a fraction for a whole number, `ids` that aren't a list of object ids, an
|
||||
/// `ids` entry or an `id` that is negative, an object id that names no object, a date that isn't
|
||||
|
||||
@@ -145,6 +145,7 @@
|
||||
Align to Artboard Çalışma Yüzeyine Hizala
|
||||
Align to Glyph Bounds Glif Sınırlarına Hizala
|
||||
Align to Key Object Anahtar Nesneye Hizala
|
||||
Align to Key Anchor Anahtar Bağlantı Noktasına Hizala
|
||||
Align to Page Sayfaya Hizala
|
||||
Align to Path Yola Hizala
|
||||
Align to Selection Seçime Hizala
|
||||
@@ -3573,6 +3574,8 @@ digits Malayalam Malayalam
|
||||
Kana Kana
|
||||
Numerals Rakamlar
|
||||
Scale at Center Merkezden Ölçekle
|
||||
Delete Set Seti Sil
|
||||
Direct Entry Doğrudan Giriş
|
||||
Up/Down: Yukarı/Aşağı:
|
||||
Left/Right: Sol/Sağ:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko Yukarı/Aşağı
|
||||
@@ -5201,6 +5204,11 @@ axis Both Her İkisi
|
||||
@msg Imported library {name} İçe aktarılan kitaplık {name}
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB İlkesi:
|
||||
CMYK Policy: CMYK İlkesi:
|
||||
Preserve Embedded Profiles Gömülü Profilleri Koru
|
||||
Convert to Working Space Çalışma Alanına Dönüştür
|
||||
Preserve Numbers Sayıları Koru
|
||||
Texture Doku
|
||||
Craquelure… Küçük çatlak…
|
||||
Grain… Tahıl…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -154,6 +154,7 @@
|
||||
Align to Artboard Вирівняти по монтажній області
|
||||
Align to Glyph Bounds Вирівняти за межами гліфа
|
||||
Align to Key Object Вирівняти за ключовим об’єктом
|
||||
Align to Key Anchor Вирівняти за ключовою опорною точкою
|
||||
Align to Page Вирівняти за сторінкою
|
||||
Align to Path Вирівняти за контуром
|
||||
Align to Selection Вирівняти за виділенням
|
||||
@@ -3826,6 +3827,8 @@ effect Points Точки
|
||||
Kana Кана
|
||||
Numerals Цифри
|
||||
Scale at Center Масштабувати від центру
|
||||
Delete Set Видалити набір
|
||||
Direct Entry Пряме введення
|
||||
Up/Down: Вгору/вниз:
|
||||
Left/Right: Ліворуч/праворуч:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko вгору/вниз
|
||||
@@ -5430,6 +5433,11 @@ axis Both Обидві
|
||||
@msg Imported library {name} Імпортовано бібліотеку {name}
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Правило RGB:
|
||||
CMYK Policy: Правило CMYK:
|
||||
Preserve Embedded Profiles Зберігати вбудовані профілі
|
||||
Convert to Working Space Перетворювати в робочий простір
|
||||
Preserve Numbers Зберігати числа
|
||||
Texture Текстура
|
||||
Craquelure… Кракелюри…
|
||||
Grain… Зерно…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -175,6 +175,7 @@
|
||||
Align to Artboard Căn theo bảng vẽ
|
||||
Align to Glyph Bounds Căn theo giới hạn glyph
|
||||
Align to Key Object Căn theo đối tượng chính
|
||||
Align to Key Anchor Căn theo điểm neo chính
|
||||
Align to Page Căn theo trang
|
||||
Align to Path Căn theo đường dẫn
|
||||
Align to Selection Căn theo vùng chọn
|
||||
@@ -607,6 +608,11 @@ font-technology Variable Biến thiên
|
||||
CMYK Equivalents Tương đương CMYK
|
||||
CMYK profile in effect Hồ sơ CMYK đang có hiệu lực
|
||||
CMYK: CMYK:
|
||||
RGB Policy: Chính sách RGB:
|
||||
CMYK Policy: Chính sách CMYK:
|
||||
Preserve Embedded Profiles Giữ cấu hình nhúng
|
||||
Convert to Working Space Chuyển sang không gian làm việc
|
||||
Preserve Numbers Giữ giá trị số
|
||||
Coarse Dots Chấm thô
|
||||
Collapse Panels to Icons Thu gọn bảng thành biểu tượng
|
||||
Collapse to Icons Thu gọn thành biểu tượng
|
||||
@@ -4172,6 +4178,8 @@ mark-style Japanese Kiểu Nhật
|
||||
Kana Kana
|
||||
Numerals Chữ số
|
||||
Scale at Center Co giãn từ tâm
|
||||
Delete Set Xóa bộ
|
||||
Direct Entry Nhập trực tiếp
|
||||
Up/Down: Lên/Xuống:
|
||||
Left/Right: Trái/Phải:
|
||||
Tate-chu-yoko Up/Down Tate-chu-yoko lên/xuống
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 205 and column 5.
|
@@ -109,6 +109,7 @@
|
||||
Align to Artboard 对齐画板
|
||||
Align to Glyph Bounds 对齐到字形边界
|
||||
Align to Key Object 对齐关键对象
|
||||
Align to Key Anchor 对齐关键锚点
|
||||
Align to Page 对齐页面
|
||||
Align to Path 对齐路径
|
||||
Align to Selection 对齐选区
|
||||
@@ -3646,6 +3647,8 @@ digits Malayalam 马拉雅拉姆数字
|
||||
Kana 假名
|
||||
Numerals 数字
|
||||
Scale at Center 从中心缩放
|
||||
Delete Set 删除集
|
||||
Direct Entry 直接输入
|
||||
Up/Down: 上/下:
|
||||
Left/Right: 左/右:
|
||||
Tate-chu-yoko Up/Down 纵中横上/下
|
||||
@@ -5332,6 +5335,11 @@ imageTrace Outline 轮廓
|
||||
None (Color Preview) 无 (颜色预览)
|
||||
Preserve 保留
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB 策略:
|
||||
CMYK Policy: CMYK 策略:
|
||||
Preserve Embedded Profiles 保留嵌入的配置文件
|
||||
Convert to Working Space 转换为工作空间
|
||||
Preserve Numbers 保留数值
|
||||
Art & Illustration 艺术和插画
|
||||
Branding 品牌
|
||||
Film & Video 影片和视频
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -118,6 +118,7 @@
|
||||
Align to Artboard 對齊工作區域
|
||||
Align to Glyph Bounds 對齊字符邊界
|
||||
Align to Key Object 對齊關鍵物件
|
||||
Align to Key Anchor 對齊關鍵錨點
|
||||
Align to Page 對齊頁面
|
||||
Align to Path 對齊路徑
|
||||
Align to Selection 對齊選取範圍
|
||||
@@ -4908,6 +4909,8 @@ digits Malayalam 馬來亞拉姆數字
|
||||
Kana 假名
|
||||
Numerals 數字
|
||||
Scale at Center 從中心縮放
|
||||
Delete Set 刪除集
|
||||
Direct Entry 直接輸入
|
||||
Up/Down: 上/下:
|
||||
Left/Right: 左/右:
|
||||
Tate-chu-yoko Up/Down 縱中橫上/下
|
||||
@@ -5564,6 +5567,11 @@ axis Both 兩者
|
||||
Interpolation 內插
|
||||
RGB: RGB:
|
||||
CMYK: CMYK:
|
||||
RGB Policy: RGB 原則:
|
||||
CMYK Policy: CMYK 原則:
|
||||
Preserve Embedded Profiles 保留內嵌描述檔
|
||||
Convert to Working Space 轉換為工作空間
|
||||
Preserve Numbers 保留數值
|
||||
Texture 紋理
|
||||
Craquelure… 龜裂紋…
|
||||
Grain… 顆粒…
|
||||
|
||||
|
Can't render this file because it is too large.
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user