Merge main into feat/plugin-api-javascript-runtime

This commit is contained in:
dotCooCoo committed 2026-11-23 23:44:07 -08:00
commit 696bff8a42
1034 files changed
+156043 -265948

No files matched your search

+8 -5
View File
@@ -880,7 +880,7 @@ fn image_and_fill_doc(fill: Paint) -> Document {
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
d
}
@@ -974,7 +974,10 @@ fn images_can_be_left_out_with_their_files() {
assert_eq!(out.setting_notes, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
broken.images.insert(
"raster-1".into(),
ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None, file_font: Default::default() },
);
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
@@ -1379,7 +1382,7 @@ fn images_link_png_or_jpeg_files() {
};
vec![Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
});
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
let out = export(&d, &opts(&d)).unwrap();
let e = entities(&out);
assert_eq!(kind(&e[0]), "IMAGE");
@@ -1422,7 +1425,7 @@ fn images_without_pixels_are_left_out_with_one_note() {
})
.collect()
});
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None });
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None, file_font: Default::default() });
let out = export(&d, &opts(&d)).unwrap();
assert!(entities(&out).is_empty() && out.images.is_empty());
assert_eq!(out.warnings, ["an image has no pixels and was left out"]);
@@ -1583,7 +1586,7 @@ fn drawings_doc() -> Document {
});
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
d
}
+3
View File
@@ -10,6 +10,9 @@ workspace = true
[dependencies]
craft-cms = { workspace = true }
# The harmony rules, their settings and their colour math (`harmony`), and their colour type.
craft-color-ui = { workspace = true }
craft-theme = { workspace = true }
kurbo = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+1 -2
View File
@@ -3,7 +3,7 @@
//!
//! * **RGB working spaces** are ICC matrix/shaper profiles via [`moxcms`] (sRGB, Wide Gamut RGB
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last ([`display`]).
//! the desktop canvas converts it into the display's own profile last, in the app.
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
@@ -13,7 +13,6 @@
//! thread, as for a document drawn through its own profiles ([`for_document`]). Code that needs
//! deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod display;
pub mod generic;
pub mod icc;
pub mod lab;
-327
View File
@@ -1,327 +0,0 @@
//! The canvas's last step before the screen: the sRGB the canvas draws, converted into a display's
//! ICC profile (Preferences › Performance › Use Monitor Profile for Canvas).
//!
//! The display profile is a destination only. Document colors, proofs, exports and the web build
//! keep their sRGB output; a soft proof is applied first, then this conversion.
//!
//! [`DisplayTransform::from_icc`] accepts an RGB display-class (`mntr`) profile of at most
//! [`MAX_PROFILE_BYTES`] whose declared length fits the data and from which a transform can be built.
//! The conversion is relative colorimetric, sampled once into a [`LUT_N`]³ table, so drawing a frame
//! costs a table lookup per pixel and never builds a transform.
use std::hash::{Hash, Hasher};
use super::{Intent, ProfileKind, icc::IccProfile};
/// The largest display profile read: VectorCraft's own limit. Display profiles are a few kilobytes
/// (matrix/shaper) to a few hundred (table-based).
pub const MAX_PROFILE_BYTES: usize = 1 << 20;
/// Grid points per channel of the conversion table.
const LUT_N: usize = 33;
/// Why a display profile can't be used. The canvas then stays sRGB.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProfileError {
/// More bytes than [`MAX_PROFILE_BYTES`].
TooLarge(usize),
/// No ICC header (`acsp` signature) or a header cut short.
NotIcc,
/// The header's length is shorter than a header or longer than the data.
BadLength { declared: usize, len: usize },
/// The profile class isn't a display's (`mntr`): an input, output or other profile.
NotDisplay(String),
/// The profile's data color space isn't RGB.
NotRgb(String),
/// The profile doesn't parse.
Unreadable(String),
/// No conversion from sRGB into the profile can be built.
NoTransform,
}
impl std::fmt::Display for ProfileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooLarge(n) => write!(f, "the profile is {n} bytes, more than the {MAX_PROFILE_BYTES} a display profile may have"),
Self::NotIcc => f.write_str("the file is not an ICC profile"),
Self::BadLength { declared, len } => write!(f, "the profile's header gives a length of {declared} bytes for {len} bytes of data"),
Self::NotDisplay(class) => write!(f, "the profile's class is `{class}`, not a display profile (`mntr`)"),
Self::NotRgb(space) => write!(f, "the profile's color space is `{space}`, not RGB"),
Self::Unreadable(e) => write!(f, "the profile can't be read: {e}"),
Self::NoTransform => f.write_str("no conversion into the profile can be built"),
}
}
}
/// Four header bytes as text, for an error message.
fn signature(b: &[u8]) -> String {
String::from_utf8_lossy(b).trim_end().to_string()
}
/// sRGB → a display profile, as a table.
pub struct DisplayTransform {
name: String,
fingerprint: u64,
/// `LUT_N`³ display values, red slowest; `None` when the profile shows sRGB unchanged (every
/// grid point within half an 8-bit step of itself).
table: Option<Vec<[f32; 3]>>,
}
impl std::fmt::Debug for DisplayTransform {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DisplayTransform").field("name", &self.name).field("identity", &self.is_identity()).finish()
}
}
impl DisplayTransform {
/// Checks `bytes` as a display profile, as [`Self::from_icc`] does, without building the
/// conversion table.
pub fn check(bytes: &[u8]) -> Result<(), ProfileError> {
Self::parse(bytes).map(|_| ())
}
/// Checks `bytes` as a display profile and builds the conversion into it.
pub fn from_icc(bytes: &[u8]) -> Result<Self, ProfileError> {
let (profile, bytes) = Self::parse(bytes)?;
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
let s = (LUT_N - 1) as f32;
let mut table = Vec::with_capacity(LUT_N.pow(3));
for r in 0..LUT_N {
for g in 0..LUT_N {
for b in 0..LUT_N {
let rgb = [r as f32 / s, g as f32 / s, b as f32 / s];
table.push(to_display(rgb).ok_or(ProfileError::NoTransform)?);
}
}
}
let grid = |i: usize| [i / (LUT_N * LUT_N), i / LUT_N % LUT_N, i % LUT_N].map(|v| v as f32 / s);
let identity = table.iter().enumerate().all(|(i, v)| v.iter().zip(grid(i)).all(|(a, b)| (a - b).abs() <= 0.5 / 255.0));
let mut h = std::collections::hash_map::DefaultHasher::new();
bytes.hash(&mut h);
Ok(Self { name: profile.name.clone(), fingerprint: h.finish(), table: (!identity).then_some(table) })
}
/// The parsed profile and its bytes up to its declared length, when `bytes` is an RGB display
/// profile from which a conversion can be built.
fn parse(bytes: &[u8]) -> Result<(IccProfile, &[u8]), ProfileError> {
if bytes.len() > MAX_PROFILE_BYTES {
return Err(ProfileError::TooLarge(bytes.len()));
}
if bytes.len() < 132 || bytes.get(36..40) != Some(b"acsp") {
return Err(ProfileError::NotIcc);
}
let declared = bytes.get(0..4).map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
if declared < 132 || declared > bytes.len() {
return Err(ProfileError::BadLength { declared, len: bytes.len() });
}
let bytes = &bytes[..declared];
if &bytes[12..16] != b"mntr" {
return Err(ProfileError::NotDisplay(signature(&bytes[12..16])));
}
if &bytes[16..20] != b"RGB " {
return Err(ProfileError::NotRgb(signature(&bytes[16..20])));
}
let profile = IccProfile::from_bytes(None, bytes).map_err(|e| ProfileError::Unreadable(e.to_string()))?;
if profile.kind != ProfileKind::Rgb {
return Err(ProfileError::NotRgb(format!("{:?}", profile.kind)));
}
let to_display =
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
if to_display([0.5; 3]).is_none() {
return Err(ProfileError::NoTransform);
}
Ok((profile, bytes))
}
/// The profile's description.
pub fn name(&self) -> &str {
&self.name
}
/// A hash of the profile's bytes, which tells two profiles with the same name apart.
pub fn fingerprint(&self) -> u64 {
self.fingerprint
}
/// The profile shows sRGB unchanged, so nothing is converted.
pub fn is_identity(&self) -> bool {
self.table.is_none()
}
/// One sRGB color (0..1) in the display profile.
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
let Some(table) = &self.table else { return rgb.map(|v| v.clamp(0.0, 1.0)) };
let n = LUT_N;
let s = (n - 1) as f32;
let p = rgb.map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) * s });
let i = p.map(|v| (v.floor() as usize).min(n - 2));
let t = [p[0] - i[0] as f32, p[1] - i[1] as f32, p[2] - i[2] as f32];
let mut out = [0.0f32; 3];
for (dr, wr) in [(0, 1.0 - t[0]), (1, t[0])] {
for (dg, wg) in [(0, 1.0 - t[1]), (1, t[1])] {
for (db, wb) in [(0, 1.0 - t[2]), (1, t[2])] {
let w = wr * wg * wb;
if w == 0.0 {
continue;
}
let v = table[((i[0] + dr) * n + i[1] + dg) * n + i[2] + db];
for c in 0..3 {
out[c] += w * v[c];
}
}
}
}
out.map(|v| v.clamp(0.0, 1.0))
}
/// One 8-bit sRGB color in the display profile.
pub fn apply8(&self, rgb: [u8; 3]) -> [u8; 3] {
if self.table.is_none() {
return rgb;
}
self.apply(rgb.map(|v| f32::from(v) / 255.0)).map(|v| (v * 255.0).round() as u8)
}
/// Premultiplied RGBA8 pixels, converted in place. Alpha is kept, and fully transparent
/// pixels are left as they are.
pub fn apply_premultiplied(&self, pixels: &mut [u8]) {
if self.table.is_none() {
return;
}
let mut last_in = [0u8; 4];
let mut last_out = [0u8; 4];
for px in pixels.as_chunks_mut::<4>().0 {
let a = px[3];
if a == 0 {
continue;
}
if *px == last_in {
*px = last_out;
continue;
}
last_in = *px;
let un = |c: u8| if a == 255 { c } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 };
let out = self.apply8([un(px[0]), un(px[1]), un(px[2])]);
for (c, o) in px.iter_mut().zip(out) {
*c = if a == 255 { o } else { ((u32::from(o) * u32::from(a) + 127) / 255) as u8 };
}
last_out = *px;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cms::{DISPLAY_P3, GENERIC_CMYK, SRGB, icc_bytes};
/// `name`'s ICC file, marked as a display profile.
fn display(name: &str) -> Vec<u8> {
let mut b = icc_bytes(name).unwrap().to_vec();
b[12..16].copy_from_slice(b"mntr");
b
}
#[test]
fn a_wide_gamut_display_shows_srgb_red_less_saturated_and_srgb_is_left_alone() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
assert!(!p3.is_identity());
assert_eq!(p3.name(), DISPLAY_P3);
// sRGB red is inside Display P3: its display values have green and blue above 0 and less red.
let [r, g, b] = p3.apply8([255, 0, 0]);
assert!(r < 245 && g > 40 && b > 10, "{:?}", [r, g, b]);
// White and black stay where they are (relative colorimetric).
assert_eq!(p3.apply8([255; 3]), [255; 3]);
assert_eq!(p3.apply8([0; 3]), [0; 3]);
let srgb = DisplayTransform::from_icc(&display(SRGB)).unwrap();
assert!(srgb.is_identity());
assert_eq!(srgb.apply8([255, 0, 0]), [255, 0, 0]);
assert_ne!(srgb.fingerprint(), p3.fingerprint());
}
#[test]
fn the_table_matches_the_profile_between_its_grid_points() {
let bytes = display(DISPLAY_P3);
let p3 = DisplayTransform::from_icc(&bytes).unwrap();
let profile = IccProfile::from_bytes(None, &bytes).unwrap();
for rgb in [[0.1, 0.7, 0.33], [0.9, 0.05, 0.6], [0.47, 0.47, 0.47], [0.0, 0.2, 1.0]] {
let want = profile.from_srgb(rgb, Intent::RelativeColorimetric).unwrap();
let got = p3.apply(rgb);
for c in 0..3 {
assert!((got[c] - want[c]).abs() < 1.0 / 255.0, "{rgb:?}: {got:?} vs {want:?}");
}
}
}
#[test]
fn premultiplied_pixels_keep_their_alpha_and_transparent_ones_stay_empty() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
let mut px = vec![255, 0, 0, 255, 128, 0, 0, 128, 0, 0, 0, 0, 255, 0, 0, 255];
p3.apply_premultiplied(&mut px);
let opaque = p3.apply8([255, 0, 0]);
assert_eq!(&px[0..4], &[opaque[0], opaque[1], opaque[2], 255]);
assert_eq!(&px[12..16], &px[0..4], "a repeated pixel converts the same");
assert_eq!(px[7], 128);
// Half-covered red: the same color at half coverage, within rounding.
for c in 0..3 {
assert!((i32::from(px[4 + c]) - i32::from(opaque[c]) / 2).abs() <= 1, "{:?}", &px[4..8]);
}
assert_eq!(&px[8..12], &[0, 0, 0, 0]);
}
#[test]
fn profiles_that_are_not_rgb_display_profiles_are_refused() {
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert!(matches!(DisplayTransform::from_icc(&cmyk), Err(ProfileError::NotDisplay(_))));
let mut cmyk_display = cmyk.clone();
cmyk_display[12..16].copy_from_slice(b"mntr");
assert!(matches!(DisplayTransform::from_icc(&cmyk_display), Err(ProfileError::NotRgb(s)) if s == "CMYK"));
let mut input = display(DISPLAY_P3);
input[12..16].copy_from_slice(b"scnr");
assert_eq!(DisplayTransform::from_icc(&input).unwrap_err(), ProfileError::NotDisplay("scnr".into()));
}
#[test]
fn malformed_short_and_oversized_data_is_refused() {
assert_eq!(DisplayTransform::from_icc(&[]).unwrap_err(), ProfileError::NotIcc);
assert_eq!(DisplayTransform::from_icc(&[0; 132]).unwrap_err(), ProfileError::NotIcc);
let good = display(DISPLAY_P3);
assert_eq!(DisplayTransform::from_icc(&good[..100]).unwrap_err(), ProfileError::NotIcc);
let mut long = good.clone();
long[0..4].copy_from_slice(&(good.len() as u32 + 1).to_be_bytes());
assert_eq!(DisplayTransform::from_icc(&long).unwrap_err(), ProfileError::BadLength { declared: good.len() + 1, len: good.len() });
let mut short = good.clone();
short[0..4].copy_from_slice(&64u32.to_be_bytes());
assert!(matches!(DisplayTransform::from_icc(&short), Err(ProfileError::BadLength { declared: 64, .. })));
// Trailing bytes past the declared length are not part of the profile.
let mut padded = good.clone();
padded.extend([0xAB; 16]);
let a = DisplayTransform::from_icc(&padded).unwrap();
assert_eq!(a.fingerprint(), DisplayTransform::from_icc(&good).unwrap().fingerprint());
let mut garbage_tags = good.clone();
for b in &mut garbage_tags[128..] {
*b = 0xFF;
}
assert!(matches!(DisplayTransform::from_icc(&garbage_tags), Err(ProfileError::Unreadable(_) | ProfileError::NoTransform)));
let huge = vec![0u8; MAX_PROFILE_BYTES + 1];
assert_eq!(DisplayTransform::from_icc(&huge).unwrap_err(), ProfileError::TooLarge(MAX_PROFILE_BYTES + 1));
}
#[test]
fn check_accepts_and_refuses_what_from_icc_does() {
assert_eq!(DisplayTransform::check(&display(DISPLAY_P3)), Ok(()));
assert_eq!(DisplayTransform::check(&display(SRGB)), Ok(()));
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
assert_eq!(DisplayTransform::check(&cmyk), Err(DisplayTransform::from_icc(&cmyk).unwrap_err()));
assert_eq!(DisplayTransform::check(&[1, 2, 3]), Err(ProfileError::NotIcc));
}
#[test]
fn nan_and_out_of_range_values_stay_in_range() {
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
for v in p3.apply([f32::NAN, -1.0, 9.0]) {
assert!((0.0..=1.0).contains(&v));
}
}
}
-15
View File
@@ -909,21 +909,6 @@ pub fn duplicate_stop(stops: &[GradientStop], i: usize, offset: f32) -> (Vec<Gra
(v, ni)
}
/// Swap the colours of stops `a` and `b` (Alt-dropping one stop on another), with their swatch
/// links and tints; offsets, opacities and midpoints stay. Out-of-range indices leave the stops
/// unchanged.
pub fn swap_stop_colors(stops: &[GradientStop], a: usize, b: usize) -> Vec<GradientStop> {
let mut v = stops.to_vec();
if a < v.len() && b < v.len() && a != b {
let (lo, hi) = v.split_at_mut(a.max(b));
let (x, y) = (&mut lo[a.min(b)], &mut hi[0]);
std::mem::swap(&mut x.color, &mut y.color);
std::mem::swap(&mut x.swatch, &mut y.swatch);
std::mem::swap(&mut x.tint, &mut y.tint);
}
v
}
/// Set the midpoint between stop `i` and `i + 1` (clamped to the diamond's 13–87 %).
pub fn set_midpoint(stops: &[GradientStop], i: usize, m: f32) -> Vec<GradientStop> {
let mut v = stops.to_vec();
-10
View File
@@ -308,16 +308,6 @@ fn duplicate_copies_the_stop_to_a_new_offset() {
assert_eq!(duplicate_stop(&g.stops, 7, 0.5).0, g.stops);
}
#[test]
fn swap_exchanges_only_the_colours() {
let mut g = g3();
g.stops[0].opacity = 0.25;
let v = swap_stop_colors(&g.stops, 0, 1);
assert_eq!((v[0].color.to_hex(), v[1].color.to_hex()), ("#ff0000".to_string(), "#ffffff".to_string()));
assert_eq!((v[0].offset, v[0].opacity, v[1].offset, v[1].opacity), (0.0, 0.25, 0.5, 1.0));
assert_eq!(swap_stop_colors(&g.stops, 0, 9), g.stops);
}
#[test]
fn midpoint_math() {
let g = g3();
+98 -354
View File
@@ -1,340 +1,112 @@
//! Colour harmony rules, the variation grid of the Color Guide panel and the five-colour themes of
//! the Color Themes panel (our own colour math).
//! the Color Themes panel, over document colours. The rules, their options and their colour math are
//! the framework's (`craft_color_ui::harmony`); these keep every colour in the model of the colour
//! it came from.
use serde::{Deserialize, Serialize};
use craft_color_ui::harmony as rules;
pub use craft_color_ui::harmony::{GuideOptions, Harmony, THEME_SIZE, Variation};
use craft_theme::Srgba;
use crate::recolor::Palette;
use crate::{Color, keep_model};
/// A harmony rule: a group of colours built from a base colour, base first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Harmony {
Complementary,
Complementary2,
SplitComplementary,
LeftComplement,
RightComplement,
Analogous,
Analogous2,
Monochromatic,
Shades,
Triad,
Triad2,
Triad3,
Tetrad,
Tetrad2,
Tetrad3,
Compound,
Compound2,
HighContrast,
HighContrast2,
HighContrast3,
Pentagram,
/// The framework's colour for `c` (display sRGB).
fn srgba(c: Color) -> Srgba {
let [r, g, b] = c.to_rgb();
Srgba::rgb(r, g, b)
}
/// One colour of a rule: the base turned by `turn` degrees of hue, its saturation scaled by `sat`
/// and its brightness by `bright` (or flipped to the contrasting brightness).
#[derive(Clone, Copy)]
struct Tone {
turn: f32,
sat: f32,
bright: Bright,
/// `c` in the model of `orig`: how [`move_on_wheel`] writes a moved colour.
pub fn in_model_of(orig: Color, c: Srgba) -> Color {
keep_model(orig, Color::rgb(c.r, c.g, c.b))
}
#[derive(Clone, Copy)]
enum Bright {
Times(f32),
/// Dark for a light base, light for a dark one ([`contrast`]).
Contrast,
}
const fn sv(turn: f32, sat: f32, bright: f32) -> Tone {
Tone { turn, sat, bright: Bright::Times(bright) }
}
/// The base's hue turned by `turn`.
const fn t(turn: f32) -> Tone {
sv(turn, 1.0, 1.0)
}
/// A softer (half as saturated) partner.
const fn soft(turn: f32) -> Tone {
sv(turn, 0.5, 1.0)
}
/// A deeper (darker) partner.
const fn deep(turn: f32) -> Tone {
sv(turn, 1.0, 0.6)
}
/// A partner of contrasting brightness.
const fn hc(turn: f32) -> Tone {
Tone { turn, sat: 1.0, bright: Bright::Contrast }
}
/// The brightness that contrasts with `v`.
fn contrast(v: f32) -> f32 {
if v >= 0.5 { v * 0.3 } else { 0.7 + 0.3 * v }
}
impl Harmony {
pub const ALL: [Harmony; 21] = [
Harmony::Complementary,
Harmony::Complementary2,
Harmony::SplitComplementary,
Harmony::LeftComplement,
Harmony::RightComplement,
Harmony::Analogous,
Harmony::Analogous2,
Harmony::Monochromatic,
Harmony::Shades,
Harmony::Triad,
Harmony::Triad2,
Harmony::Triad3,
Harmony::Tetrad,
Harmony::Tetrad2,
Harmony::Tetrad3,
Harmony::Compound,
Harmony::Compound2,
Harmony::HighContrast,
Harmony::HighContrast2,
Harmony::HighContrast3,
Harmony::Pentagram,
];
pub fn label(self) -> &'static str {
match self {
Harmony::Complementary => "Complementary",
Harmony::Complementary2 => "Complementary 2",
Harmony::SplitComplementary => "Split Complementary",
Harmony::LeftComplement => "Left Complement",
Harmony::RightComplement => "Right Complement",
Harmony::Analogous => "Analogous",
Harmony::Analogous2 => "Analogous 2",
Harmony::Monochromatic => "Monochromatic",
Harmony::Shades => "Shades",
Harmony::Triad => "Triad",
Harmony::Triad2 => "Triad 2",
Harmony::Triad3 => "Triad 3",
Harmony::Tetrad => "Tetrad",
Harmony::Tetrad2 => "Tetrad 2",
Harmony::Tetrad3 => "Tetrad 3",
Harmony::Compound => "Compound",
Harmony::Compound2 => "Compound 2",
Harmony::HighContrast => "High Contrast",
Harmony::HighContrast2 => "High Contrast 2",
Harmony::HighContrast3 => "High Contrast 3",
Harmony::Pentagram => "Pentagram",
}
}
/// The rule's id in commands: its label in camelCase ("splitComplementary", "triad2").
pub fn id(self) -> String {
let mut out = String::new();
for (i, w) in self.label().split(' ').enumerate() {
let mut c = w.chars();
if let Some(f) = c.next() {
if i == 0 {
out.extend(f.to_lowercase());
} else {
out.extend(f.to_uppercase());
}
out.push_str(c.as_str());
}
}
out
}
/// A rule from its id or label (case and spaces ignored).
pub fn parse(s: &str) -> Option<Self> {
let key = |x: &str| x.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_ascii_lowercase();
let want = key(s);
Self::ALL.into_iter().find(|h| key(h.label()) == want)
}
fn tones(self) -> &'static [Tone] {
match self {
Harmony::Complementary => const { &[t(0.0), t(180.0)] },
Harmony::Complementary2 => const { &[t(0.0), soft(0.0), t(180.0), soft(180.0)] },
Harmony::SplitComplementary => const { &[t(0.0), t(150.0), t(210.0)] },
Harmony::LeftComplement => const { &[t(0.0), t(-30.0), t(150.0)] },
Harmony::RightComplement => const { &[t(0.0), t(30.0), t(210.0)] },
Harmony::Analogous => const { &[t(0.0), t(30.0), t(-30.0)] },
Harmony::Analogous2 => const { &[t(0.0), t(30.0), t(60.0), t(-30.0), t(-60.0)] },
Harmony::Monochromatic => const { &[t(0.0), sv(0.0, 0.5, 1.0), sv(0.0, 1.0, 0.6), sv(0.0, 0.25, 1.0), sv(0.0, 1.0, 0.35)] },
Harmony::Shades => const { &[t(0.0), sv(0.0, 1.0, 0.8), sv(0.0, 1.0, 0.6), sv(0.0, 1.0, 0.4), sv(0.0, 1.0, 0.2)] },
Harmony::Triad => const { &[t(0.0), t(120.0), t(240.0)] },
Harmony::Triad2 => const { &[t(0.0), t(120.0), soft(120.0), t(240.0), soft(240.0)] },
Harmony::Triad3 => const { &[t(0.0), t(120.0), deep(120.0), t(240.0), deep(240.0)] },
Harmony::Tetrad => const { &[t(0.0), t(60.0), t(180.0), t(240.0)] },
Harmony::Tetrad2 => const { &[t(0.0), t(90.0), t(180.0), t(270.0)] },
Harmony::Tetrad3 => const { &[t(0.0), t(30.0), t(180.0), t(210.0)] },
Harmony::Compound => const { &[t(0.0), t(40.0), t(160.0), t(200.0)] },
Harmony::Compound2 => const { &[t(0.0), t(-40.0), t(160.0), t(200.0)] },
Harmony::HighContrast => const { &[t(0.0), hc(180.0)] },
Harmony::HighContrast2 => const { &[t(0.0), hc(0.0), t(180.0), hc(180.0)] },
Harmony::HighContrast3 => const { &[t(0.0), hc(120.0), hc(240.0)] },
Harmony::Pentagram => const { &[t(0.0), t(72.0), t(144.0), t(216.0), t(288.0)] },
}
}
/// The rule's colours in the base colour's model, the base colour itself first.
pub fn apply(self, base: Color) -> Vec<Color> {
let rest = self.apply_hsb(base.to_hsb()).into_iter().skip(1);
std::iter::once(base).chain(rest.map(|[h, s, v]| keep_model(base, Color::from_hsb(h, s, v)))).collect()
}
/// The rule's colours as HSB from base HSB `hsb`, the base first: hue in degrees from 0 to 360,
/// saturation and brightness from 0 to 1. A gray base keeps its hue, so the colours keep their
/// places around a hue wheel.
pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> {
self.tones()
.iter()
.map(|tone| {
let b = match tone.bright {
Bright::Times(f) => v * f,
Bright::Contrast => contrast(v),
};
[(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)]
})
.collect()
}
/// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or
/// Monochromatic), so that each can sit on a hue ring apart from the others.
pub fn hues_differ(self) -> bool {
let turns: Vec<f32> = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect();
turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b))
}
/// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or
/// darker variations of it that fill the remaining places (the rule's first colours get them
/// first). The base colour comes first, every colour in its model.
pub fn theme(self, base: Color) -> Vec<Color> {
let colors = self.apply(base);
let n = colors.len();
let mut rows: Vec<Vec<Color>> = colors.iter().map(|c| vec![*c]).collect();
let opts = GuideOptions::default();
for k in 0..THEME_SIZE.saturating_sub(n) {
let (i, pass) = (k % n, k / n);
// Alternate lighter and darker along the rule and from one pass to the next.
let step = if (i + pass) % 2 == 0 { 3 } else { -3 };
rows[i].push(variation(colors[i], &opts, step));
}
rows.into_iter().flatten().take(THEME_SIZE).collect()
/// The rule's name as the interface shows it.
pub fn label(rule: Harmony) -> &'static str {
match rule {
Harmony::Complementary => "Complementary",
Harmony::Complementary2 => "Complementary 2",
Harmony::SplitComplementary => "Split Complementary",
Harmony::LeftComplement => "Left Complement",
Harmony::RightComplement => "Right Complement",
Harmony::Analogous => "Analogous",
Harmony::Analogous2 => "Analogous 2",
Harmony::Monochromatic => "Monochromatic",
Harmony::Shades => "Shades",
Harmony::Triad => "Triad",
Harmony::Triad2 => "Triad 2",
Harmony::Triad3 => "Triad 3",
Harmony::Tetrad => "Tetrad",
Harmony::Tetrad2 => "Tetrad 2",
Harmony::Tetrad3 => "Tetrad 3",
Harmony::Compound => "Compound",
Harmony::Compound2 => "Compound 2",
Harmony::HighContrast => "High Contrast",
Harmony::HighContrast2 => "High Contrast 2",
Harmony::HighContrast3 => "High Contrast 3",
Harmony::Pentagram => "Pentagram",
}
}
/// The number of colours in a colour theme.
pub const THEME_SIZE: usize = 5;
/// A rule from its id or its label (case and spaces ignored).
pub fn parse(s: &str) -> Option<Harmony> {
let key: String = s.chars().filter(|c| !c.is_whitespace()).collect();
Harmony::ALL.into_iter().find(|h| h.id().eq_ignore_ascii_case(&key))
}
/// The rule's colours in the base colour's model, the base colour itself first.
pub fn apply(rule: Harmony, base: Color) -> Vec<Color> {
let rest = rule.apply(srgba(base)).into_iter().skip(1);
std::iter::once(base).chain(rest.map(|c| in_model_of(base, c))).collect()
}
/// A [`THEME_SIZE`]-colour theme from `base` (the framework's `Harmony::theme`): the base colour
/// first, every colour in its model.
pub fn theme(rule: Harmony, base: Color) -> Vec<Color> {
let rest = rule.theme(srgba(base)).into_iter().skip(1);
std::iter::once(base).chain(rest.map(|c| in_model_of(base, c))).collect()
}
/// Move colour `i` of a harmony on the hue and saturation wheel to `hsb` (hue in degrees,
/// saturation and brightness 0..1), keeping its model. With `linked` the other colours keep their
/// relation to it: they turn by the same hue, scale their saturation alike and shift their
/// brightness by as much.
/// saturation and brightness 0..1), as the framework's `move_on_wheel` does; each colour that moves
/// keeps its model and the others keep their values.
pub fn move_on_wheel(colors: &mut [Color], i: usize, hsb: [f32; 3], linked: bool) {
let Some(&old) = colors.get(i) else { return };
let [h0, s0, v0] = old.to_hsb();
let (dh, ratio, dv) = (hsb[0] - h0, if s0 > 0.01 { hsb[1] / s0 } else { 1.0 }, hsb[2] - v0);
for (j, c) in colors.iter_mut().enumerate() {
let new = if j == i {
hsb
} else if linked {
let [h, s, v] = c.to_hsb();
[h + dh, (s * ratio).clamp(0.0, 1.0), (v + dv).clamp(0.0, 1.0)]
} else {
continue;
};
*c = keep_model(*c, Color::from_hsb(new[0], new[1], new[2]));
}
}
/// What the variation grid varies: towards black and white, towards cool and warm, or towards
/// grey and full saturation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Variation {
#[default]
TintsShades,
WarmCool,
VividMuted,
}
impl Variation {
pub const ALL: [Variation; 3] = [Variation::TintsShades, Variation::WarmCool, Variation::VividMuted];
pub fn id(self) -> &'static str {
match self {
Variation::TintsShades => "tintsShades",
Variation::WarmCool => "warmCool",
Variation::VividMuted => "vividMuted",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|v| v.id().eq_ignore_ascii_case(s))
}
/// The ends of the grid: (left, right).
pub fn sides(self) -> (&'static str, &'static str) {
match self {
Variation::TintsShades => ("Shades", "Tints"),
Variation::WarmCool => ("Cool", "Warm"),
Variation::VividMuted => ("Muted", "Vivid"),
let mut moved: Vec<Srgba> = colors.iter().map(|c| srgba(*c)).collect();
rules::move_on_wheel(&mut moved, i, hsb, linked);
for (c, m) in colors.iter_mut().zip(moved) {
if m != srgba(*c) {
*c = in_model_of(*c, m);
}
}
}
/// The Color Guide's options: variation kind, steps on each side and how far they reach.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct GuideOptions {
pub variation: Variation,
/// Variations on each side of the harmony colour (1..=20).
pub steps: u32,
/// How far the outermost variations go, 0..=100 (Less … More).
pub amount: f32,
}
impl Default for GuideOptions {
fn default() -> Self {
Self { variation: Variation::TintsShades, steps: 4, amount: 50.0 }
/// The id of a variation in commands.
fn variation_id(v: Variation) -> &'static str {
match v {
Variation::TintsShades => "tintsShades",
Variation::WarmCool => "warmCool",
Variation::VividMuted => "vividMuted",
}
}
impl GuideOptions {
pub const MAX_STEPS: u32 = 20;
/// The options with `steps` and `amount` clamped to their ranges.
pub fn clamped(self) -> Self {
Self { steps: self.steps.clamp(1, Self::MAX_STEPS), amount: self.amount.clamp(0.0, 100.0), ..self }
}
/// The share of the way to the target that the outermost steps reach (10% … 90%).
fn reach(&self) -> f32 {
0.1 + 0.8 * self.amount.clamp(0.0, 100.0) / 100.0
}
/// A variation from its id ("tintsShades", "warmCool" or "vividMuted"; case ignored).
pub fn parse_variation(s: &str) -> Option<Variation> {
Variation::ALL.into_iter().find(|v| variation_id(*v).eq_ignore_ascii_case(s))
}
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
/// variation at `step` goes: 0 at the center, the options' reach (10% … 90%) at the outermost steps.
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
let reach = 0.1 + 0.8 * opts.amount.clamp(0.0, 100.0) / 100.0;
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * reach
}
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
/// Variation of `c` at `step` (the framework's `variation`), in `c`'s model; step 0 is `c` itself.
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
if step == 0 {
return c;
}
let f = step_fraction(opts, step);
let v = match opts.variation {
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
Variation::WarmCool => {
let target = if step < 0 { Color::rgb(0.2, 0.45, 1.0) } else { Color::rgb(1.0, 0.55, 0.1) };
c.lerp(&target, f * 0.6)
}
Variation::VividMuted => {
let [h, s, b] = c.to_hsb();
let s2 = if step < 0 { s * (1.0 - f) } else { s + (1.0 - s) * f };
Color::from_hsb(h, s2.clamp(0.0, 1.0), b)
}
};
keep_model(c, v)
in_model_of(c, rules::variation(srgba(c), opts, step))
}
/// The Color Guide for a base colour: the harmony colours and, per colour, its row of variations
@@ -349,7 +121,7 @@ impl Guide {
pub fn new(base: Color, rule: Harmony, opts: &GuideOptions) -> Self {
let opts = opts.clamped();
let n = opts.steps as i32;
let colors = rule.apply(base);
let colors = apply(rule, base);
let grid = colors.iter().map(|c| (-n..=n).map(|step| variation(*c, &opts, step)).collect()).collect();
Self { colors, grid }
}
@@ -382,10 +154,10 @@ mod tests {
#[test]
fn complementary_red() {
let c = Harmony::Complementary.apply(Color::rgb(1.0, 0.0, 0.0));
let c = apply(Harmony::Complementary, Color::rgb(1.0, 0.0, 0.0));
assert_eq!(c[1].to_hex(), "#00ffff");
assert_eq!(Harmony::Triad.apply(Color::rgb(1.0, 0.0, 0.0))[1].to_hex(), "#00ff00");
assert_eq!(Harmony::Pentagram.apply(Color::rgb(1.0, 0.0, 0.0))[1].to_hsb()[0].round(), 72.0);
assert_eq!(apply(Harmony::Triad, Color::rgb(1.0, 0.0, 0.0))[1].to_hex(), "#00ff00");
assert_eq!(apply(Harmony::Pentagram, Color::rgb(1.0, 0.0, 0.0))[1].to_hsb()[0].round(), 72.0);
}
#[test]
@@ -394,9 +166,9 @@ mod tests {
assert_eq!(Harmony::ALL.len(), counts.len());
for base in [Color::rgb8(230, 120, 40), Color::cmyk(0.1, 0.8, 0.3, 0.05), Color::gray(0.4)] {
for (h, n) in Harmony::ALL.into_iter().zip(counts) {
let c = h.apply(base);
assert_eq!(c.len(), n, "{}", h.label());
assert_eq!(c[0], base, "{}: the base comes first, in its own model", h.label());
let c = apply(h, base);
assert_eq!(c.len(), n, "{}", label(h));
assert_eq!(c[0], base, "{}: the base comes first, in its own model", label(h));
}
}
}
@@ -405,9 +177,9 @@ mod tests {
fn harmonies_keep_the_base_model() {
let base = Color::cmyk(0.0, 1.0, 1.0, 0.0);
for h in Harmony::ALL {
assert!(h.apply(base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", h.label());
assert!(apply(h, base).iter().all(|c| matches!(c, Color::Cmyk { .. })), "{}", label(h));
}
let Color::Cmyk { c, m, y, .. } = Harmony::Complementary.apply(base)[1] else { panic!("a CMYK complement") };
let Color::Cmyk { c, m, y, .. } = apply(Harmony::Complementary, base)[1] else { panic!("a CMYK complement") };
assert!(c > m && c > y, "the complement of red is a cyan: {c} {m} {y}");
let g = Guide::new(Color::gray(0.4), Harmony::Triad, &GuideOptions::default());
assert!(g.grid.iter().flatten().all(|c| matches!(c, Color::Gray { .. })));
@@ -416,47 +188,19 @@ mod tests {
#[test]
fn rules_parse_by_id_and_label() {
for h in Harmony::ALL {
assert_eq!(Harmony::parse(&h.id()), Some(h));
assert_eq!(Harmony::parse(h.label()), Some(h));
assert_eq!(parse(h.id()), Some(h));
assert_eq!(parse(label(h)), Some(h));
}
assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary");
assert_eq!(Harmony::HighContrast3.id(), "highContrast3");
assert_eq!(Harmony::parse("square"), None);
}
/// A rule's HSB colours match the colours `apply` gives, and a gray base keeps its hue, so its
/// colours turn around the hue ring from it.
#[test]
fn hsb_colours_match_and_keep_a_grays_hue() {
for h in Harmony::ALL {
let base = Color::rgb8(230, 120, 40);
let hsb = h.apply_hsb(base.to_hsb());
let colors = h.apply(base);
assert_eq!(hsb.len(), colors.len(), "{}", h.label());
for (a, c) in hsb.iter().zip(&colors).skip(1) {
assert_eq!(Color::from_hsb(a[0], a[1], a[2]).to_hex(), c.to_hex(), "{}", h.label());
}
}
let gray = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]);
assert_eq!(gray.iter().map(|c| c[0]).collect::<Vec<_>>(), [40.0, 160.0, 280.0]);
assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360");
}
/// Fifteen rules give every colour its own hue; the six that repeat a hue are left out.
#[test]
fn rules_whose_colours_all_have_their_own_hue() {
let differ: Vec<Harmony> = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect();
assert_eq!(differ.len(), 15);
for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] {
assert!(!h.hues_differ(), "{}", h.label());
}
assert_eq!(parse("square"), None);
}
#[test]
fn high_contrast_flips_brightness() {
let light = Harmony::HighContrast.apply(Color::rgb(0.9, 0.8, 0.2));
let light = apply(Harmony::HighContrast, Color::rgb(0.9, 0.8, 0.2));
assert!(light[1].to_hsb()[2] < 0.5);
let dark = Harmony::HighContrast.apply(Color::rgb(0.2, 0.1, 0.05));
let dark = apply(Harmony::HighContrast, Color::rgb(0.2, 0.1, 0.05));
assert!(dark[1].to_hsb()[2] > 0.5);
}
@@ -499,9 +243,9 @@ mod tests {
let palette = Palette::new(lib);
for rule in Harmony::ALL {
let g = Guide::new(Color::rgb8(200, 60, 40), rule, &GuideOptions::default()).limited(&palette);
assert!(g.grid.iter().flatten().chain(&g.colors).all(|c| lib.contains(c)), "{}", rule.label());
assert!(g.grid.iter().flatten().chain(&g.colors).all(|c| lib.contains(c)), "{}", label(rule));
for (row, c) in g.grid.iter().zip(&g.colors) {
assert_eq!(row[g.centre()], *c, "{}: the harmony colour stays in the centre", rule.label());
assert_eq!(row[g.centre()], *c, "{}: the harmony colour stays in the centre", label(rule));
}
}
// The nearest colour wins: a pale yellow snaps to the cream and its darkest shade to the grey.
@@ -517,15 +261,15 @@ mod tests {
fn themes_have_five_colours_base_first() {
for base in [Color::rgb8(230, 120, 40), Color::cmyk(0.1, 0.8, 0.3, 0.05)] {
for rule in Harmony::ALL {
let t = rule.theme(base);
assert_eq!(t.len(), THEME_SIZE, "{}", rule.label());
assert_eq!(t[0], base, "{}", rule.label());
assert!(t.iter().all(|c| c.model() == base.model()), "{}: colours keep the base model", rule.label());
let t = theme(rule, base);
assert_eq!(t.len(), THEME_SIZE, "{}", label(rule));
assert_eq!(t[0], base, "{}", label(rule));
assert!(t.iter().all(|c| c.model() == base.model()), "{}: colours keep the base model", label(rule));
}
}
// A two-colour rule fills in variations next to the colour they vary.
let red = Color::rgb(1.0, 0.0, 0.0);
let t = Harmony::Complementary.theme(red);
let t = theme(Harmony::Complementary, red);
assert_eq!(t[3].to_hex(), "#00ffff", "the complement follows the base's variations");
let l = |c: &Color| c.to_lab().l;
assert!(l(&t[1]) > l(&t[0]) && l(&t[2]) < l(&t[0]), "the base, a lighter and a darker red");
@@ -534,7 +278,7 @@ mod tests {
assert!(t[i + 1..].iter().all(|b| b.to_hex() != a.to_hex()), "{} repeats", a.to_hex());
}
// Five-colour rules are themes as they are.
assert_eq!(Harmony::Pentagram.theme(red), Harmony::Pentagram.apply(red));
assert_eq!(theme(Harmony::Pentagram, red), apply(Harmony::Pentagram, red));
}
#[test]
+3 -4
View File
@@ -629,16 +629,15 @@ fn perceptual() -> (Vec<Swatch>, Vec<SwatchGroup>) {
/// Colour-wheel harmonies of a few base colours (the Color Guide's rules).
fn harmony_sets() -> (Vec<Swatch>, Vec<SwatchGroup>) {
use crate::harmony::Harmony;
use crate::harmony::{self, Harmony};
let bases = [("Coral", Color::from_hsb(8.0, 0.68, 0.94)), ("Teal", Color::from_hsb(176.0, 0.72, 0.62))];
let rules = [Harmony::Complementary, Harmony::SplitComplementary, Harmony::Analogous, Harmony::Triad, Harmony::Tetrad, Harmony::Pentagram];
let mut groups = vec![];
for (bn, base) in bases {
for rule in rules {
let name = format!("{} {bn}", rule.label());
let name = format!("{} {bn}", harmony::label(rule));
// Rounded to 8 bits like the other libraries.
let swatches = rule
.apply(base)
let swatches = harmony::apply(rule, base)
.into_iter()
.enumerate()
.map(|(i, c)| {
+4 -4
View File
@@ -134,10 +134,10 @@ pub use text::GlyphForm;
pub use text::PATH_LEAD_MAX;
pub use text::WarichuAlign;
pub use text::{
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
VerticalAlign, WrapShape,
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FILE_FONT_MIME, FileFont, FileFontFace, FileFonts,
FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection,
ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind,
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
pub use trace::TraceView;
+1 -1
View File
@@ -130,7 +130,7 @@ pub fn hash_reader_within(r: impl std::io::Read, max: u64) -> std::io::Result<(S
impl ImageBlob {
/// A blob of encoded image `bytes` of type `mime`, without a preview.
pub fn new(mime: impl Into<String>, bytes: Vec<u8>) -> Self {
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None }
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None, file_font: Default::default() }
}
/// This blob with a preview of at most [`PROXY_SIZE`] pixels a side (PNG), when the image is
+4 -1
View File
@@ -461,7 +461,7 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
doc.layers.clear();
doc.swatches.clear();
let mime = if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { "image/png" };
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None });
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None, file_font: Default::default() });
let xf = Affine::scale_non_uniform(frame.width() / w as f64, frame.height() / h as f64);
let im = ImageObject { key: "preview".into(), width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
let art = Node::new(art_id(), NodeKind::Group { children: vec![Arc::new(Node::new(art_id(), NodeKind::Image(Box::new(im))))], clip: false });
@@ -519,6 +519,9 @@ fn rename(n: &mut Node, prefix: &str) {
paint(&mut r.style.fill);
paint(&mut r.style.stroke);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| *key = format!("{prefix}{key}"));
}
}
NodeKind::Image(im) => {
im.key = format!("{prefix}{}", im.key);
+31 -2
View File
@@ -154,8 +154,9 @@ pub struct Symbol {
pub dynamic: bool,
}
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects, and the fonts files carried for
/// type ([`crate::FileFonts`], MIME [`crate::FILE_FONT_MIME`]), which save and travel the same way.
#[derive(Serialize, Deserialize)]
pub struct ImageBlob {
pub mime: String,
#[serde(skip)]
@@ -164,4 +165,32 @@ pub struct ImageBlob {
/// linked images show this blob, and what `bytes` hold while the linked file can't be read.
#[serde(skip)]
pub proxy: Option<Arc<Vec<u8>>>,
/// Runtime ownership of an admitted font face. Image resources (including undo and clipboard
/// copies) own it; cached text nodes carry only weak references.
#[serde(skip)]
pub file_font: std::sync::Mutex<Option<Arc<dyn crate::FileFontFace>>>,
}
impl std::fmt::Debug for ImageBlob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImageBlob").field("mime", &self.mime).field("bytes", &self.bytes).field("proxy", &self.proxy).finish()
}
}
impl Clone for ImageBlob {
fn clone(&self) -> Self {
let mut owner = self.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if owner.as_ref().is_some_and(|face| {
self.mime != crate::FILE_FONT_MIME || (!std::ptr::eq(face.bytes(), self.bytes.as_slice()) && face.bytes() != self.bytes.as_slice())
}) {
*owner = None;
}
Self { mime: self.mime.clone(), bytes: self.bytes.clone(), proxy: self.proxy.clone(), file_font: std::sync::Mutex::new(owner.clone()) }
}
}
impl PartialEq for ImageBlob {
fn eq(&self, other: &Self) -> bool {
self.mime == other.mime && self.bytes == other.bytes && self.proxy == other.proxy
}
}
+6
View File
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
mod area;
mod char_style;
mod composite;
mod file_fonts;
mod kinsoku_set;
mod object;
mod para_style;
@@ -26,6 +27,7 @@ pub use composite::{
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 file_fonts::{FILE_FONT_MIME, FileFont, FileFontFace, FileFonts, MAX_FILE_FONTS, text_hash};
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
pub use para_style::{
@@ -131,6 +133,10 @@ pub struct TextObject {
/// file saves the count only when it is not 0.
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
pub list_count: u32,
/// The fonts the file this type came from carried for fonts that aren't available here,
/// which draw it until its text is edited ([`FileFonts`]); `None` for other type.
#[serde(default, rename = "fileFonts", skip_serializing_if = "Option::is_none")]
pub file_fonts: Option<Box<FileFonts>>,
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
+4
View File
@@ -7,6 +7,9 @@ pub struct CharStyle {
pub font_family: String,
#[serde(default = "regular")]
pub font_style: String,
/// Internal layout selection from a validated file-font binding, never read from a file.
#[serde(skip)]
pub file_font_id: Option<u32>,
/// Which installed version of the font (its version string) when several versions of the
/// family and style are installed and the text was set in one the family and style alone
/// wouldn't pick (an imported file's type matched to it); None = the one they pick.
@@ -656,6 +659,7 @@ impl Default for CharStyle {
Self {
font_family: "Source Sans 3".into(),
font_style: "Regular".into(),
file_font_id: None,
font_version: None,
font_axes: std::collections::BTreeMap::new(),
size: 12.0,
+105
View File
@@ -0,0 +1,105 @@
use std::sync::Arc;
use serde::{Deserialize, Serialize};
/// The MIME type of a font a file carried ([`FileFonts`]), kept among the document's image blobs
/// ([`crate::Document::images`]).
pub const FILE_FONT_MIME: &str = "font/ttf";
/// The most fonts of [`FileFonts`] that draw one type object (a file's list may be longer: the rest
/// are left out).
pub const MAX_FILE_FONTS: usize = 64;
/// The fonts a file carried for type whose fonts aren't available here (a PDF's embedded fonts),
/// kept with the document among its image blobs ([`crate::Document::images`], MIME
/// [`FILE_FONT_MIME`]). A file embeds its fonts so that readers see its text in its own fonts
/// rather than substitutes (Acrobat Help, PDF fonts,
/// <https://helpx.adobe.com/acrobat/using/pdf-fonts.html>); editing text in a font that isn't
/// installed sets it in a substitute (Acrobat Help, Edit text in PDFs,
/// <https://helpx.adobe.com/acrobat/using/edit-text-pdfs1.html>). So the type is drawn in these,
/// as the file drew it, while its text is the one the file had and a font it names isn't
/// available: once its text is edited (or that font is installed) it takes the font it names, or
/// its substitute. Its runs keep naming the file's fonts, so they stay listed as missing.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileFonts {
/// The font kept for each family and style the runs name.
pub fonts: Vec<FileFont>,
/// The text as the file had it ([`text_hash`] of the plain text).
pub text: u64,
/// Validated runtime resources; serialized keys alone never authorize a font lookup.
#[serde(skip)]
resources: Vec<(String, u32, std::sync::Weak<dyn FileFontFace>)>,
}
impl FileFonts {
/// `fonts` for type whose text is `text`.
pub fn new(fonts: Vec<FileFont>, text: &str) -> Self {
Self { fonts, text: text_hash([text]), resources: vec![] }
}
/// The runtime face bound to this reference by its owning document.
pub fn face(&self, key: &str) -> Option<Arc<dyn FileFontFace>> {
self.resources.iter().find(|(k, _, _)| k == key).and_then(|(_, _, face)| face.upgrade())
}
/// Replace validated bindings, returning whether their runtime identity changed.
pub fn bind(&mut self, resources: Vec<(String, Arc<dyn FileFontFace>)>) -> bool {
let changed = self.resources.len() != resources.len()
|| self.resources.iter().zip(&resources).any(|((a, id, _), (b, face))| a != b || *id != face.id());
self.resources = resources.into_iter().map(|(key, face)| (key, face.id(), Arc::downgrade(&face))).collect();
changed
}
/// Remap serialized and validated runtime resource keys together when art changes namespaces.
/// The callback applies the same mapping to each occurrence of an original key.
pub fn map_keys(&mut self, mut map: impl FnMut(&mut String)) {
for font in &mut self.fonts {
map(&mut font.key);
}
for (key, _, _) in &mut self.resources {
map(key);
}
}
}
impl PartialEq for FileFonts {
fn eq(&self, other: &Self) -> bool {
self.fonts == other.fonts
&& self.text == other.text
&& self.resources.len() == other.resources.len()
&& self.resources.iter().zip(&other.resources).all(|((a, aid, _), (b, bid, _))| a == b && aid == bid)
}
}
/// A runtime file-font resource owned by image blobs, undo snapshots and clipboard resources.
/// The text engine implements this interface without making the document depend on it.
pub trait FileFontFace: Send + Sync {
fn id(&self) -> u32;
fn bytes(&self) -> &[u8];
}
impl std::fmt::Debug for dyn FileFontFace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FileFontFace").field("id", &self.id()).finish()
}
}
/// One font of [`FileFonts`]: the family and style type names it by, and its blob.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileFont {
pub family: String,
pub style: String,
/// The font's blob among the document's image blobs.
pub key: String,
}
/// A hash of the text `parts` make one after another (64-bit FNV-1a of its UTF-8 bytes): the same
/// on every machine and in every version, as a saved [`FileFonts::text`] needs.
pub fn text_hash<'a>(parts: impl IntoIterator<Item = &'a str>) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in parts.into_iter().flat_map(str::bytes) {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
+13
View File
@@ -1,5 +1,6 @@
use super::area::{AreaOptions, PathAlign, PathEffect};
use super::char_style::CharStyle;
use super::file_fonts::{FileFont, MAX_FILE_FONTS, text_hash};
use super::para_style::{JustificationOptions, ParaStyle};
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
use super::tabs_lists::{ListCounts, ParaList};
@@ -126,6 +127,7 @@ impl TextObject {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -144,6 +146,17 @@ impl TextObject {
pub fn plain_text(&self) -> String {
self.runs.iter().map(|r| r.text.as_str()).collect()
}
/// The fonts the file this type came from carried ([`FileFonts`]) while its text is still the
/// file's (at most [`MAX_FILE_FONTS`]); none once it was edited, and for other type.
pub fn file_fonts_in_use(&self) -> &[FileFont] {
match self.file_fonts.as_deref() {
Some(f) if f.text == text_hash(self.runs.iter().map(|r| r.text.as_str())) => {
f.fonts.get(..f.fonts.len().min(MAX_FILE_FONTS)).unwrap_or_default()
}
_ => &[],
}
}
/// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not
/// on a path, which sets them as they are. Exports that write live text write such type as
/// outlines, as they do ruby: their text can't place the stacked lines.
+27
View File
@@ -801,3 +801,30 @@ fn auto_alignment_saves_readable_by_older_builds() {
// Files from before the flag keep their alignment.
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
}
#[test]
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
use super::file_fonts::*;
use super::*;
// The hash is the same everywhere and in every version (saved files carry it).
assert_eq!(text_hash([""]), 0xcbf2_9ce4_8422_2325);
assert_eq!(text_hash(["Ham", "burg"]), text_hash(["Hamburg"]));
assert_ne!(text_hash(["Hamburg"]), text_hash(["Hamburh"]));
let font = FileFont { family: "Source Serif 9".into(), style: "Regular".into(), key: "k".into() };
let mut t = TextObject::point(Point::ZERO, "Ham", CharStyle::default());
t.runs.push(TextRun::new("burg", CharStyle::default()));
assert!(t.file_fonts_in_use().is_empty());
t.file_fonts = Some(Box::new(FileFonts::new(vec![font.clone()], "Hamburg")));
assert_eq!(t.file_fonts_in_use(), std::slice::from_ref(&font));
// Saved and read back.
let json = serde_json::to_string(&t).unwrap();
assert!(json.contains(r#""fileFonts":{"fonts":[{"family":"Source Serif 9","style":"Regular","key":"k"}]"#), "{json}");
assert_eq!(serde_json::from_str::<TextObject>(&json).unwrap(), t);
// Edited: none.
t.runs[1].text.push('s');
assert!(t.file_fonts_in_use().is_empty());
// A file's list past the cap: the first ones.
t.runs[1].text.pop();
t.file_fonts.as_mut().unwrap().fonts = vec![font; MAX_FILE_FONTS + 5];
assert_eq!(t.file_fonts_in_use().len(), MAX_FILE_FONTS);
}
+1
View File
@@ -19,6 +19,7 @@ bundled-fonts = ["vectorcraft-text/bundled-fonts"]
heif = ["dep:heic-rs", "dep:rayon"]
[dependencies]
craft-codepage = { workspace = true }
# Which paths stored in documents may be opened.
craft-docpath = { workspace = true }
craft-proof = { workspace = true }
+1
View File
@@ -94,6 +94,7 @@ pub(crate) mod slices;
pub mod spelling;
mod stroke;
mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
mod swatch;
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
#[test]
fn color_mask_refuses_previews_and_images_too_large() {
let preview = std::sync::Arc::new(framed());
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
let (mut s, id) =
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
assert_eq!(mask_of(doc(&s), id), None);
+6 -1
View File
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
let preview = Arc::new(bytes);
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
let missing = place_linked(
&mut s,
"missing",
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
(12, 10),
);
let before = (image_of(&s, missing), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
+1 -1
View File
@@ -135,7 +135,7 @@ impl Session {
/// Whether `name` is a built-in preset's, "Custom" (changed settings, as the panel and a traced
/// object show them), or a saved preset's other than the one at `except`.
fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
pub fn trace_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
tr::preset(name).is_some() || name.trim().eq_ignore_ascii_case("Custom") || self.trace_preset_index(name).is_some_and(|i| Some(i) != except)
}
+17 -2
View File
@@ -159,6 +159,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The fonts its file carried travel with it, as images do.
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
f(Ref::Name(Res::Image, &ff.key));
}
}
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
@@ -807,6 +811,9 @@ impl Relink {
if relaid {
refresh_bounds(t);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| self.name(Res::Image, key));
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
@@ -1134,6 +1141,8 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// File-font resources refused while binding pasted type.
pub warnings: Vec<String>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
@@ -1158,13 +1167,18 @@ impl Imported {
}
}
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
/// other darkness take the contrast a redraw sets there.
pub(crate) fn apply(&self, n: &mut Node) {
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
if self.relinks {
let shades = super::super::graph::wedge_shades(n);
self.relink.node(n);
super::super::graph::follow_wedge_shades(n, &shades);
}
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
if !self.warnings.contains(&note) {
self.warnings.push(note);
}
}
}
}
@@ -1462,6 +1476,7 @@ impl Clipboard {
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
Ok(out)
}
+4 -4
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation};
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
@@ -962,8 +962,8 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.harmony";
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
let rule = Harmony::parse(rule).ok_or_else(|| {
let ids: Vec<String> = Harmony::ALL.iter().map(|h| h.id()).collect();
let rule = harmony::parse(rule).ok_or_else(|| {
let ids: Vec<&str> = Harmony::ALL.iter().map(|h| h.id()).collect();
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
})?;
check_numbers(p, &["steps", "amount"], C)?;
@@ -972,7 +972,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
opts.steps = n.min(u32::MAX as u64) as u32;
}
if let Some(v) = text_param(p, "variation", C)? {
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
opts.variation = harmony::parse_variation(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
}
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
opts.amount = a as f32;
@@ -26,6 +26,7 @@ pub const MAX_FILE: usize = 64 << 10;
/// The most setups `view.proofSetup.list` lists.
pub const MAX_LISTED: usize = 100;
/// The most folder entries `view.proofSetup.list` looks at, setup files or not.
#[cfg(not(target_arch = "wasm32"))]
const MAX_SCANNED: usize = 100_000;
/// The longest `name`, in characters.
const MAX_NAME: usize = 100;
+4 -4
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::{Harmony, THEME_SIZE};
use vectorcraft_color::harmony::{self, THEME_SIZE};
use vectorcraft_color::recolor::ColorKey;
use vectorcraft_tools::params::color_json;
@@ -98,7 +98,7 @@ fn next_name(s: &Session) -> String {
fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "colorTheme.save";
let rule = match str_param(p, "rule") {
Some(r) => Some(Harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
Some(r) => Some(harmony::parse(r).ok_or_else(|| bad(C, format!("unknown rule `{r}` (see color.harmony)")))?),
None => None,
};
let colors: Vec<Color> = match (p.get("colors"), p.get("color")) {
@@ -107,7 +107,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, Some(c)) => {
let base = color_value(c).ok_or_else(|| bad(C, "invalid `color`"))?;
rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?.theme(base)
harmony::theme(rule.ok_or_else(|| bad(C, "`color` needs a `rule` to make the theme from"))?, base)
}
_ => return Err(bad(C, "give `colors`, or `color` and `rule`")),
};
@@ -123,7 +123,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
if s.prefs.color_themes.iter().enumerate().any(|(i, t)| Some(i) != replace && t.name.eq_ignore_ascii_case(&name)) {
return Err(bad(C, format!("a theme is already called {name} (replace: \"{name}\" overwrites it)")));
}
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(Harmony::id) };
let theme = ColorTheme { name: name.clone(), colors, rule: rule.map(|h| h.id().to_owned()) };
match replace {
Some(i) => s.prefs.color_themes[i] = theme,
None => s.prefs.color_themes.push(theme),
+20 -9
View File
@@ -23,6 +23,9 @@ use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_par
/// The extension of the files Export writes and Import reads.
pub const EXTS: &[&str] = &["vccomposite"];
/// The id of the export command.
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
@@ -271,7 +274,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.compositeFonts.export";
const C: &str = EXPORT;
let path = text_param(p, "path", C)?;
if path.is_some_and(|p| p.trim().is_empty()) {
return Err(bad(C, "path is empty"));
@@ -306,21 +309,29 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
if fonts.is_empty() {
return Err(bad(C, "no composite fonts to export"));
}
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"));
}
let bytes = file_bytes(&fonts)?;
match path {
Some(path) => {
write_file(path, text.as_bytes())?;
write_file(path, &bytes)?;
Ok(json!({ "path": path, "count": fonts.len() }))
}
None => Ok(json!({ "data": text, "count": fonts.len() })),
// The bytes are UTF-8 JSON text, so the lossy conversion changes nothing.
None => Ok(json!({ "data": String::from_utf8_lossy(&bytes), "count": fonts.len() })),
}
}
/// The bytes of an export file holding `fonts`: what [`import`] reads. Refused when they would make a
/// file larger than Import reads.
pub fn file_bytes(fonts: &[CompositeFont]) -> Result<Vec<u8>> {
let mut file = Map::new();
file.insert("compositeFonts".into(), json!(fonts));
let text = serde_json::to_string_pretty(&file).map_err(|e| bad(EXPORT, e.to_string()))?;
if text.len() > MAX_FILE_BYTES {
return Err(bad(EXPORT, "the composite fonts make a file larger than 4 MB, which Import can't read; export fewer of them"));
}
Ok(text.into_bytes())
}
/// The composite fonts in the bytes of an exported file.
fn read_fonts(bytes: &[u8], c: &str) -> Result<Vec<CompositeFont>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| bad(c, format!("not a composite fonts file: {e}")))?;
+3 -2
View File
@@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
// Converted colors are compared with the document's resources, as another document's are
// (`Clipboard::import_into`); its images are still the document's own.
let imported = clip.import_into(d, choices, same_doc)?;
let mut imported = clip.import_into(d, choices, same_doc)?;
// Draw Inside: the clip group of the object drawn into, made on the first paste.
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
let artboards: Vec<usize> = boards
@@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
imported.apply(&mut c, d);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
// A cross-document drag carries the graphic's appearance with it,
@@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
"added": imported.added,
"merged": imported.merged,
"renamed": imported.renamed,
"warnings": imported.warnings,
}))
}
+1 -1
View File
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
pub(crate) use export::with_artboard_fills;
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
pub(crate) use load::decode_native_file;
use load::err;
pub(crate) use load::import_svg;
pub(crate) use load::is_placeholder;
pub(crate) use load::native_file;
pub(crate) use load::page_or_editing_data;
pub(crate) use load::source;
pub use load::{
+19 -11
View File
@@ -140,9 +140,8 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
if let Some(f) = craft_image_codecs::detect(bytes).and_then(image_format) {
return Some(f);
}
// A version 2 PICT is known by its version opcodes after the picture's frame, at byte 522 of a
// file or byte 10 of a bare picture (version 1 by its file's name), so a format whose
// signature starts the file is checked first.
// A PICT is known by its version opcodes after the picture's frame, at byte 522 of a file or
// byte 10 of a bare picture, so a format whose signature starts the file is checked first.
if vectorcraft_metafile::is_pict(bytes) {
return format("pict");
}
@@ -193,8 +192,11 @@ fn restore_or_import(
let mut fallback = None;
if let Some((intact, bytes)) = editing {
let native = if intact { bytes() } else { None };
match native.and_then(|b| native_file(&b).ok()) {
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
match native.and_then(|b| decode_native_file(&b).ok()) {
Some((mut doc, _, mut warnings)) => {
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
return Ok((doc, warnings, true));
}
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
}
}
@@ -205,9 +207,9 @@ fn restore_or_import(
Ok((doc, warnings, false))
}
/// A native file's document and details, the colour profiles it carries installed where missing
/// (with a warning for each that can't be used).
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
/// The caller must assemble any external resources and bind file fonts before layout.
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
let mut warnings = super::native::install_profiles(f.profiles);
warnings.extend(f.depth_notes);
@@ -424,7 +426,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
})?
}
"vectorcraft" | "template" => {
let (d, info, warnings) = native_file(bytes)?;
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
native_pdf_compatible = Some(info.pdf_compatible);
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
(d, warnings, false)
@@ -688,7 +691,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
let update_links = s.prefs.update_links == "automatically";
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
let p = s.prefs.with_pdf_font_choice(p);
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
}
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
@@ -860,7 +864,11 @@ impl ReadFile {
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
Session::refresh_text_bounds(&mut self.loaded.doc);
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
if !self.loaded.warnings.contains(&note) {
self.loaded.warnings.push(note);
}
}
}
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
+17 -16
View File
@@ -8,7 +8,10 @@ use std::sync::Arc;
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail};
use vectorcraft_pdf::{
APP, ActiveProfiles, Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, Standard, THUMBNAIL_SIZE, Thumbnail, default_preset_name,
leaves_out_bleed, page_bleed,
};
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
@@ -17,9 +20,6 @@ use crate::EngineError;
const C: &str = "document.exportPdf";
/// The built-in preset every PDF export starts from.
pub use vectorcraft_pdf::DEFAULT_PRESET;
/// The PDF options `document.formats` lists; `document.exportPdf` documents every field.
pub(crate) const OPTIONS: &[FormatOption] = &[
super::ARTBOARD,
@@ -151,13 +151,13 @@ pub fn presets(s: &Session) -> Vec<String> {
/// The built-in preset names, then those of `saved`.
fn names(saved: &[PdfPreset]) -> Vec<String> {
vectorcraft_pdf::builtin_presets().into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
vectorcraft_pdf::builtin_presets(APP).into_iter().map(|p| p.name).chain(saved.iter().map(|p| p.name.clone())).collect()
}
/// The preset `name` names: a built-in one (any case; `default` is the app default) or one of
/// `saved`.
pub fn find_preset(name: &str, saved: &[PdfPreset]) -> Option<PdfPreset> {
vectorcraft_pdf::builtin_preset(name).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
vectorcraft_pdf::builtin_preset(name, APP).or_else(|| saved.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).cloned())
}
fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
@@ -166,9 +166,10 @@ fn preset(cmd: &str, name: &str, saved: &[PdfPreset]) -> Result<PdfSettings> {
.ok_or_else(|| bad(cmd, format!("unknown PDF preset `{name}` (presets: {})", names(saved).join(", "))))
}
/// The settings of the preset `p` names (default: [`DEFAULT_PRESET`]), before `p`'s options.
/// The settings of the preset `p` names (default: [`default_preset_name`]), before `p`'s options.
pub fn preset_settings(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
preset(cmd, str_param(p, "preset").unwrap_or(DEFAULT_PRESET), saved)
let default = default_preset_name(APP);
preset(cmd, str_param(p, "preset").unwrap_or(&default), saved)
}
/// Merge `over` into `base`: objects key by key (recursively), `null` keeps the base (the
@@ -194,7 +195,7 @@ pub(crate) fn pdf_error(cmd: &str, e: PdfError) -> EngineError {
}
/// The settings `p` asks for: its preset (built-in or one of `saved`; default
/// [`DEFAULT_PRESET`]) with `p`'s options applied over it. Choosing another standard turns
/// [`default_preset_name`]) with `p`'s options applied over it. Choosing another standard turns
/// Preserve Editing off, the layers off where it has none, and sets the latest compatibility it
/// allows, unless `p` asks for those. Checked as a preset is
/// ([`PdfSettings::check_values`]): profiles that aren't there pass. Keys that aren't PDF options
@@ -219,14 +220,14 @@ pub fn resolve(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings>
s.compatibility = s.standard.version();
}
}
s.check_values().map_err(|e| pdf_error(cmd, e))?;
s.check_values().map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
/// [`resolve`], refusing what the writer can't honour ([`PdfSettings::check`]).
pub fn settings_with(cmd: &str, p: &Value, saved: &[PdfPreset]) -> Result<PdfSettings> {
let s = resolve(cmd, p, saved)?;
s.check().map_err(|e| pdf_error(cmd, e))?;
s.check(&ActiveProfiles::default()).map_err(|e| pdf_error(cmd, e.into()))?;
Ok(s)
}
@@ -240,7 +241,7 @@ pub fn settings(cmd: &str, p: &Value) -> Result<PdfSettings> {
/// built-in presets. Params naming none come back as they are.
pub fn expand_preset<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Value>> {
let expanded = match str_param(p, "preset") {
Some(name) if vectorcraft_pdf::builtin_preset(name).is_none() => {
Some(name) if vectorcraft_pdf::builtin_preset(name, APP).is_none() => {
let set = settings_with(cmd, p, &s.prefs.pdf_presets)?;
let mut q = p.clone();
merge(&mut q, &serde_json::to_value(set).map_err(|e| EngineError::Other(e.to_string()))?);
@@ -316,7 +317,7 @@ pub(super) fn art_page(cmd: &str, doc: &Document, p: &Value) -> Result<Option<(D
}
/// The warning for a PDF/X file that leaves out the document's bleed
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
/// ([`vectorcraft_pdf::leaves_out_bleed`]).
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
/// How far, in points, an object's edge may sit inside the trim edge, or short of the bleed edge,
@@ -579,7 +580,7 @@ fn encode_carrying_at(
// createLayers writes non-printing layers with /PrintState /OFF, so they count only with
// includeNonPrinting, which writes them as printing art.
let set = &opts.settings;
let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
let short = if bleed_check { short_of_bleed(doc, page_bleed(&set.bleed, doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 };
// The pages' background colors, behind the art (the editing data keeps them as colors).
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?;
@@ -592,7 +593,7 @@ fn encode_carrying_at(
let mut notes = vec![];
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
// Setup gives.
if opts.settings.leaves_out_bleed(doc) {
if leaves_out_bleed(&opts.settings, doc) {
notes.push(Note::loss(BLEED_LEFT_OUT));
}
// Art that reaches the trim edge but leaves part of the page's bleed empty.
@@ -760,7 +761,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
};
note_texts(&notes)
}
_ => set.warnings(),
_ => set.warnings(&ActiveProfiles::default()).into_iter().map(|w| w.message).collect(),
};
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
Ok(json!({ "settings": v, "presets": presets(s), "changed": diff, "warnings": warnings }))
+21 -2
View File
@@ -47,6 +47,10 @@ pub struct LoadOptions {
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
/// (which can be older than it), with a warning, instead of from the PDF part.
pub trust_editing_data: bool,
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
/// imported PDFs for opens and places that give none).
pub embedded_fonts: bool,
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
/// (`legacyNameEncoding`).
pub legacy_names: vectorcraft_eps::NameEncoding,
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
editing_data: true,
trust_editing_data: false,
legacy_names: vectorcraft_eps::NameEncoding::default(),
embedded_fonts: true,
native: true,
link_pages: false,
}
@@ -84,7 +89,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -135,6 +140,10 @@ impl LoadOptions {
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
};
Ok(Self {
pages,
crop,
@@ -148,6 +157,7 @@ impl LoadOptions {
dxf,
editing_data,
trust_editing_data,
embedded_fonts,
legacy_names,
native: true,
link_pages,
@@ -177,6 +187,7 @@ impl LoadOptions {
text_as: self.text_as,
layers: self.layers,
uncalibrated_rgb: editor_document,
embedded_fonts: self.embedded_fonts,
..Default::default()
})
}
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
/// The import options of [`page_document`].
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
ImportOptions {
pages: Some(vec![page]),
crop: o.crop,
password: o.password.clone(),
text_as: o.text_as,
layers: false,
embedded_fonts: o.embedded_fonts,
..Default::default()
}
}
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
+5 -4
View File
@@ -2,7 +2,8 @@
use serde_json::{Value, json};
use super::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
use super::*;
fn session(artboards: usize) -> Session {
@@ -310,7 +311,7 @@ fn bad_options_are_refused() {
#[test]
fn options_apply_over_the_preset() {
let mut s = session(1);
let a = b64(&export(&mut s, json!({"preset": DEFAULT_PRESET, "compression": {"compressText": false}})));
let a = b64(&export(&mut s, json!({"preset": default_preset_name(APP), "compression": {"compressText": false}})));
let b = b64(&export(&mut s, json!({"preset": "default"})));
assert!(a.len() > b.len(), "content streams left uncompressed");
assert!(String::from_utf8_lossy(&a).contains(" re") || String::from_utf8_lossy(&a).contains(" l"));
@@ -499,7 +500,7 @@ fn pdf_settings_summarise_changes_and_warnings() {
let mut s = Session::new();
let v = s.execute("document.pdfSettings", &json!({})).unwrap();
assert_eq!(v["settings"]["compatibility"], "1.7");
assert_eq!(v["presets"][0], DEFAULT_PRESET);
assert_eq!(v["presets"][0], default_preset_name(APP));
assert_eq!(v["changed"], json!([]));
assert_eq!(v["warnings"], json!([]));
let p = json!({"compatibility": "1.5", "compression": {"compressText": false}, "createLayers": true, "security": {"copy": false, "openPassword": ""}});
@@ -544,5 +545,5 @@ fn formats_list_the_pdf_options() {
assert!(pdf["options"].get(k).is_some(), "{k}");
}
assert_eq!(pdf["options"]["compatibility"]["default"], "1.7");
assert_eq!(pdf["options"]["preset"]["default"], DEFAULT_PRESET);
assert_eq!(pdf["options"]["preset"]["default"], default_preset_name(APP));
}
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_pdf::TextAs;
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
use super::*;
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
#[test]
fn load_options_read_text_and_layers() {
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
let d = LoadOptions::default();
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
let n = LoadOptions { native: false, ..Default::default() };
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
}
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
}
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
widths.join(" "),
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file], None)
}
/// The glyphs of the active document's type (document space origins) and how many come from fonts
/// files carried.
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
let db = vectorcraft_text::FontDb::global();
let (mut at, mut carried) = (vec![], 0);
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
at.push(t.xf * g.origin);
carried += usize::from(db.is_file_font(g.font_id));
}
}
});
(at, carried)
}
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
/// it takes the substitute, which exports then name.
#[test]
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
let mut s = Session::new();
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
let fonts = s.execute("text.fonts", &json!({})).unwrap();
let family = fonts[0]["family"].as_str().unwrap().to_string();
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
let (at, carried) = glyphs(&s);
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
// Saved and opened again: the same.
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
assert_eq!(glyphs(&s), (at.clone(), carried));
// Edited: the substitute, which exports name, and the font still missing.
let mut id = None;
s.doc().unwrap().doc.walk(|n| {
if matches!(n.kind, NodeKind::Text(_)) {
id = Some(n.id);
}
});
let id = id.unwrap();
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
assert!(warned(&mut s), "edited: substituted");
let findings = preflight(&mut s);
assert!(
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
"preflight identifies the substituted text owner: {findings}"
);
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
// Undone: the file's look again.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s), (at, carried));
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
}
#[test]
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
let db = vectorcraft_text::FontDb::global();
let serif = db.face("Source Serif 4", "Regular").unwrap();
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
let bytes = carried_font_pdf(content, 200.0);
let mut reference = Session::new();
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
let want = glyph_ink(&reference, false);
assert_eq!(want.len(), 3);
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
let compare = |s: &Session| {
let mut areas = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
areas += 1;
}
});
assert_eq!(areas, 1);
let got = glyph_ink(s, false);
assert_eq!(got.len(), want.len());
for (got, want) in got.iter().zip(&want) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
}
};
compare(&s);
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
compare(&s);
}
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::{Point, Rect, Shape};
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
let mut doc = Document::new(100.0, 100.0);
doc.images.insert("chosen".into(), blob.clone());
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
(doc, blob, id)
}
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
/// the same key. Paste must relink its own bytes, including after closing the source tab.
#[test]
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Native Owned File Font Regression";
let open_native = |s: &mut Session, doc: &Document| {
let bytes = vectorcraft_format::save_file(doc);
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
};
let face_of = |s: &Session, id| {
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
FontDb::global().face_by_id(g.font_id).unwrap()
};
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
let mut s = Session::new();
open_native(&mut s, &a);
let a_index = s.active_index().unwrap();
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
open_native(&mut s, &b);
let b_index = s.active_index().unwrap();
let carried = face_of(&s, b_id).id();
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
assert!(s.close_document(b_index));
assert!(s.set_active(a_index));
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
assert_eq!(face_of(&s, id).id(), carried);
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
let svg = options["format"] == "svg";
let exported = s.execute("document.serialize", &options).unwrap();
if svg {
let text = exported["text"].as_str().unwrap();
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
} else {
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
assert!(bytes.starts_with(b"%PDF-"));
}
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
}
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
let mut unowned = b.clone();
unowned.images.clear();
let report = open_native(&mut s, &unowned);
assert!(report["warnings"].to_string().contains(FAMILY));
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
}
/// Place owns its carried font even after the decoded source is dropped, whether the destination
/// reuses an equal unbound blob or renames a key occupied by another font.
#[test]
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
use vectorcraft_doc::Document;
use vectorcraft_text::FontDb;
const FAMILY: &str = "Placed Owned Font Regression";
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
for same_bytes in [true, false] {
let mut host = Document::new(100.0, 100.0);
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
host.images.insert("chosen".into(), blob);
let mut s = Session::new();
s.add_document(host, None);
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
let check = |s: &Session| {
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
drawn += 1;
}
}
});
assert_eq!(drawn, 1);
};
check(&s);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(glyphs(&s).1, 0);
s.execute("edit.redo", &json!({})).unwrap();
check(&s);
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
check(&s);
}
}
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
use kurbo::Affine;
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
let (source, expected, _) = owned_font_document(family, 200.0);
let bytes = vectorcraft_format::save_file(&source);
let blob = ImageBlob::new("application/json", bytes);
let key = format!("placed-font-{}", blob.content_key());
let mut host = Document::new(100.0, 100.0);
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
host.images.insert(key.clone(), blob);
let placed = PlacedDocument {
key,
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
bounding: false,
page_box: Default::default(),
width: 100.0,
height: 100.0,
xf: Affine::IDENTITY,
placement: Default::default(),
};
let id = host.alloc_id();
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
(host, expected, id)
}
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
/// text to the host's unrelated font under the same key when reopened.
#[test]
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
use vectorcraft_text::FontDb;
for break_link in [true, false] {
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
let (host, expected, id) = linked_owned_font_document(family);
let mut s = Session::new();
s.add_document(host, None);
if break_link {
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
assert_eq!(glyphs(&s).1, 1);
}
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
let db = FontDb::global();
let mut drawn = 0;
s.doc().unwrap().doc.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
for g in vectorcraft_text::layout(db, t).glyphs {
assert!(db.is_file_font(g.font_id));
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
drawn += 1;
}
}
});
assert_eq!(drawn, 1, "{family}");
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
}
}
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
let widths: Vec<String> =
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
widths.join(" "),
n + 1,
n + 3
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
}
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
use kurbo::Shape;
let db = vectorcraft_text::FontDb::global();
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
let mut add = |path: &kurbo::BezPath| {
let els = path.elements();
let mut start = 0;
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
let line = if across {
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
} else {
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
};
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
start = end;
}
};
s.doc().unwrap().doc.walk(|n| match &n.kind {
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
_ => {}
});
lines.into_iter().flatten().collect()
}
/// Two different glyphs of a carried font for one character can't both go into the font kept with
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
/// where it draws it: the same page opened as outlines is the reference.
#[test]
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
assert_carried_glyph_roundtrip(content, false);
}
#[test]
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
assert_carried_glyph_roundtrip(content, true);
}
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
let bytes = two_glyphs_for_one_character_pdf(content);
let mut reference_session = Session::new();
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
let reference = glyph_ink(&reference_session, across);
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
let mut s = Session::new();
open(&mut s, &bytes, json!({})).unwrap();
assert!(
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
"some glyphs stay type, the other is outlines: {:?}",
live_texts(&s)
);
let close = |s: &Session, what: &str| {
let got = glyph_ink(s, across);
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
for (got, want) in got.iter().zip(&reference) {
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
}
};
close(&s, "opened");
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
close(&s, "saved and reopened");
}
@@ -405,9 +405,9 @@ fn zipped_and_32_bit_layers_read() {
/// A layer without a Unicode name takes the name its Pascal string holds, read as Mac Roman.
#[test]
fn names_without_a_unicode_name_read_as_mac_roman() {
let l = L { legacy: Some(b"Caf\x8E \xD2Old\xD3"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let l = L { legacy: Some(b"Caf\x8E\xCA\xD2Old\xD3\xDB"), ..layer("", [0, 0, 1, 1], [0, 0, 0, 255]) };
let (s, r) = open(&file(1, 1, &[l], 8, false, false), json!({}));
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café “Old”", "{r}");
assert_eq!(name(&s.doc().unwrap().doc.layers[0]), "Café\u{a0}“Old”€", "{r}");
}
#[test]
+29 -9
View File
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
/// pattern being edited is read from the editing layer only.
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
fonts_of(d, art, false)
}
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
/// their file carried ([`in_file_fonts`]).
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
let mut fonts = BTreeSet::new();
let mut add = |n: &Node| {
if let NodeKind::Text(t) = &n.kind {
fonts.extend(t.runs.iter().flat_map(run_fonts));
let file = if drawn { in_file_fonts(t) } else { vec![] };
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
}
};
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
}
}
match &n.kind {
NodeKind::Text(_) => {
NodeKind::Text(t) => {
if overflows && self.own {
self.overflow.insert(n.id);
}
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
p.overflow.insert(owner);
}
let file = in_file_fonts(t);
for r in runs {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
// Drawn in a font its file carried: printed as the file drew it.
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
let fonts = run_fonts(r);
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
for font in &fonts {
p.fonts.entry(font.clone()).or_default().insert(owner);
}
}
self.fonts.extend(fonts);
}
self.fonts.extend(fonts);
// Inline graphics draw their symbols' art.
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
self.symbol(&art.symbol);
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
/// families that aren't available (their type is drawn in the fallback font, not the font it
/// names) or styles that its family doesn't have (the closest style is drawn).
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
/// font its file carried isn't substituted.
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
substitution_warning_of(used_fonts(d))
substitution_warning_of(fonts_of(d, &[], true))
}
/// The families and styles of the runs of `t` drawn in a font its file carried
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
/// though the font they name isn't available.
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
let faces = vectorcraft_text::FontDb::global().file_faces(t);
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
}
/// [`substitution_warning`] for type set in `fonts`.
+1 -1
View File
@@ -447,7 +447,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
}
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
st.layer_rows = vec![row];
st.locate_reveal = Some(row);
st.layers_reveal = Some(crate::LayersReveal::Row(row));
st.revision += 1;
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
+1 -1
View File
@@ -563,7 +563,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
_ => img.blob.mime.clone(),
};
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
}
let mut warnings = vec![];
match previews.len() {
+2 -1
View File
@@ -960,10 +960,11 @@ impl Session {
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
// The color profiles the file carries are installed where missing, as opening it installs
// them, so the new document's assigned profiles draw and are saved with it.
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
// Linked images in its symbols, patterns and brushes are read from their files, as placing
// a document reads them.
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
Ok(Some(ReadProfile { doc, file, warnings }))
}
}
+7 -7
View File
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_pdf::{PdfPreset, builtin_preset, builtin_presets};
use vectorcraft_pdf::{APP, ActiveProfiles, PdfPreset, builtin_preset, builtin_presets};
use super::fileio::pdf::{find_preset, resolve};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, str_param};
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
impl Session {
/// Every PDF preset: the built-in ones, then the saved ones.
pub fn pdf_presets(&self) -> Vec<PdfPreset> {
let mut v = builtin_presets();
let mut v = builtin_presets(APP);
v.extend(self.prefs.pdf_presets.iter().cloned());
v
}
@@ -93,16 +93,16 @@ impl Session {
/// Whether `name` is taken by a built-in PDF preset or a saved one other than the one at
/// `except`.
fn pdf_preset_taken(&self, name: &str, except: Option<usize>) -> bool {
builtin_preset(name).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
builtin_preset(name, APP).is_some() || self.pdf_saved_index(name).is_some_and(|i| Some(i) != except)
}
}
fn row(p: PdfPreset, built_in: bool) -> Value {
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check().is_ok(), "description": p.description, "settings": p.settings })
json!({ "name": p.name, "builtIn": built_in, "supported": p.settings.check(&ActiveProfiles::default()).is_ok(), "description": p.description, "settings": p.settings })
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let rows = builtin_presets().into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
let rows = builtin_presets(APP).into_iter().map(|p| row(p, true)).chain(s.prefs.pdf_presets.iter().cloned().map(|p| row(p, false)));
Ok(json!({ "presets": rows.collect::<Vec<_>>() }))
}
@@ -113,7 +113,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Some(n) => n.to_string(),
None => s.new_pdf_preset_name(),
};
if builtin_preset(&name).is_some() {
if builtin_preset(&name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and is read-only: save it under another name")));
}
let at = s.pdf_saved_index(&name);
@@ -145,7 +145,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "pdf.preset.delete";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
if builtin_preset(name).is_some() {
if builtin_preset(name, APP).is_some() {
return Err(bad(C, format!("`{name}` is a built-in preset and stays")));
}
let i = s.pdf_saved_index(name).ok_or_else(|| bad(C, format!("no saved PDF preset named `{name}`")))?;
+1 -1
View File
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
+16
View File
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
}
}
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.images.insert(new.to_string(), blob.clone());
}
}
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
// Transfer the validated source lease too: cached text nodes hold only weak references.
for (old, (new, copy)) in &images {
if *copy {
continue;
}
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
}
}
for (old, new) in copies(&symbols) {
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
def.name = new.to_string();
+5 -2
View File
@@ -333,7 +333,7 @@ fn read_source(
}
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
let shown = PlacedDocument {
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
key: key.clone(),
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
let Some(blob) = out.images.get(&p.key) else { continue };
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
Some(bytes) => {
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
out.images.insert(
p.key.clone(),
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
);
}
None => {
previews.insert(p.key);
+2 -2
View File
@@ -651,8 +651,8 @@ mod tests {
let s = read(concat!(r"{\rtf1\ansi\uc1 caf\u233?\uc2 \u", "8364", r"\'80\'80 \uc1\u-10179?\u-8704? end\'93q\'94}"));
assert_eq!(text_of(&s), "café€ 😀 end“q”");
assert_eq!(text_of(&read(r"{\rtf1\uc1\u233\bin1 ?X}")), "éX", "binary data is one fallback character");
let mac = read(r"{\rtf1\mac \'8e\'a5}");
assert_eq!(text_of(&mac), "é•", "Mac Roman");
let mac = read(r"{\rtf1\mac \'8e\'ca\'a5\'db\'de}");
assert_eq!(text_of(&mac), "é\u{a0}•€fi", "Mac Roman");
}
#[test]
+2 -15
View File
@@ -185,20 +185,7 @@ pub(in crate::cmd) fn windows_1252(b: u8) -> char {
/// Byte `b` of Mac Roman.
pub(in crate::cmd) fn mac_roman(b: u8) -> char {
const HIGH: [char; 128] = [
'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', //
'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', //
'†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', //
'∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', //
'¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', //
'–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', //
'‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', //
'\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ',
];
match b {
0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER),
_ => char::from(b),
}
craft_codepage::windows_byte(craft_codepage::MAC_ROMAN_CODE_PAGE, b)
}
/// `text` with its line breaks (CR LF, CR or LF) as paragraph breaks, cleaned up as `o` says:
@@ -344,7 +331,7 @@ mod tests {
let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() };
assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é");
let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() };
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€");
assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xCA, 0xA5, 0xDB, 0xDE, 0xF0], mac), "“q”é\u{a0}•€fi\u{f8ff}");
}
/// The other character sets decode by their Encoding Standard decoders: the platform matters
+1
View File
@@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
p!(
"updateLinks",
+1 -1
View File
@@ -67,7 +67,7 @@ fn drop_guides(nodes: &mut Vec<Arc<Node>>) {
/// nothing is drawn get none.
fn bitmap_document(cmd: &str, doc: &Document, set: &PrintSettings, rich_black: bool) -> Result<Document> {
let regions = vectorcraft_pdf::print_regions(doc, set).map_err(|e| pdf_error(cmd, e))?;
let bleed = set.bleed.of(doc);
let bleed = vectorcraft_pdf::page_bleed(&set.bleed, doc);
let mut art = doc.clone();
drop_guides(&mut art.layers);
let anti_alias = if doc.raster_effects.anti_alias { AntiAlias::Art } else { AntiAlias::None };
+4 -2
View File
@@ -1458,7 +1458,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
super::threads::mark_continued(&mut doc);
@@ -1473,7 +1473,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
};
match read {
Ok(data) => {
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if r.proxy {
blob.proxy = Some(blob.bytes.clone());
@@ -1510,6 +1510,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
let base = super::links::LinkBase::file(links_from.as_deref());
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
// Bind only after the copy's external resources and linked files have been restored.
warnings.extend(Session::refresh_text_bounds(&mut doc));
let index = s.add_document(doc, meta.path.clone());
let st = s.doc_mut()?;
st.recovered = true;
+1 -1
View File
@@ -121,7 +121,7 @@ fn two_words_keep_their_space() {
#[test]
fn craft_fonts_glyphs_retype_too() {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else {
let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.has_script("Jpan")) else {
eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)");
return;
};
+8 -7
View File
@@ -329,14 +329,15 @@ impl Session {
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it (Override Character
/// Color as set): the Graphic Styles panel's previews.
pub fn styled(&self, n: &Node, g: &GraphicStyle) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, self.prefs.override_char_color);
n
}
/// A copy of `n` with style `g` applied as `graphicStyle.apply` applies it, type's characters too
/// with `override_char_color` (the preference Override Character Color): the Graphic Styles
/// panel's previews.
pub fn styled_node(n: &Node, g: &GraphicStyle, override_char_color: bool) -> Node {
let mut n = n.clone();
style_node(&mut n, g, &mut None, override_char_color);
n
}
// ---------- commands ----------
+7 -1
View File
@@ -97,6 +97,8 @@ pub fn specs() -> Vec<CommandSpec> {
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
/// How many times a library was set; the next library's [`DesignLibrary::generation`].
loads: u64,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
@@ -108,6 +110,9 @@ pub struct DesignLibrary {
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
/// Which load of the library this is: it differs from every other load's, so a picture of a design of
/// this library is stale once the library is loaded again.
pub generation: u64,
}
impl DesignLibraries {
@@ -125,8 +130,9 @@ impl DesignLibraries {
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
self.loads += 1;
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc), generation: self.loads });
}
}
}
+2
View File
@@ -1850,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
system_layout: false,
fractional_widths: true,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
@@ -2158,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
system_layout: t.system_layout,
fractional_widths: t.fractional_widths,
list_count: 0,
file_fonts: None,
list_level_counts: Vec::new(),
cached_bounds: None,
cached_baselines: Vec::new(),
+98 -5
View File
@@ -25,10 +25,11 @@ pub struct DocState {
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
/// `layer.highlight`).
pub layer_rows: Vec<NodeId>,
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
/// when the row was already highlighted. Panel state: not saved, not undoable.
pub locate_reveal: Option<NodeId>,
/// What the Layers panel reveals at its next pass, until the panel takes it: the panel opens
/// the layers around the row and scrolls to it, also when the row was already highlighted.
/// Set by `layer.locate` and, for what a top-level command, an interaction's commit or a
/// selection changed, by [`DocState::request_reveal`]. Panel state: not saved, not undoable.
pub layers_reveal: Option<LayersReveal>,
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
@@ -179,6 +180,30 @@ thread_local! {
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// What the Layers panel is asked to reveal ([`DocState::layers_reveal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayersReveal {
/// Open the layers around this row and scroll to it: it was highlighted, located or isolated.
Row(NodeId),
/// The current layer changed with no row highlighted: reveal that layer.
Current(NodeId),
/// The last selected object changed: reveal its row when Panel Options › Locate Selected
/// Objects is on.
Selected(NodeId),
}
/// What decides a [`LayersReveal`], as of one moment: the isolation, the highlighted rows, the
/// current layer and the last selected object of one document, with the request pending then.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayersView {
uid: u64,
isolation: Option<NodeId>,
rows: Vec<NodeId>,
active_layer: Option<NodeId>,
last_selected: Option<NodeId>,
reveal: Option<LayersReveal>,
}
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
/// its top-level layers open (a `.ai` another app wrote opens with none open).
@@ -326,7 +351,7 @@ impl DocState {
revision: 1,
active_layer,
layer_rows: vec![],
locate_reveal: None,
layers_reveal: None,
variables_highlight: None,
variables_sort: Default::default(),
isolation: None,
@@ -657,6 +682,74 @@ impl DocState {
pub fn highlighted_rows(&self) -> Vec<NodeId> {
self.layer_rows.iter().copied().filter(|id| self.doc.node(*id).is_some()).collect()
}
/// What decides the Layers panel's reveal request now.
pub(crate) fn layers_view(&self) -> LayersView {
LayersView {
uid: self.uid,
isolation: self.isolation,
rows: self.layer_rows.clone(),
active_layer: self.active_layer,
last_selected: self.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// [`DocState::layers_view`] as it was when interaction `it` began: what a commit of the
/// interaction changed is compared with that, since the previews changed the state meanwhile.
pub(crate) fn layers_view_before(&self, it: &Interaction) -> LayersView {
LayersView {
uid: self.uid,
isolation: it.isolation,
rows: it.layer_rows.clone(),
active_layer: it.active_layer,
last_selected: it.selection.objects.last().copied(),
reveal: self.layers_reveal,
}
}
/// Ask the Layers panel to reveal what changed since `before`, in this order: isolation entered
/// or left, the highlighted rows, the last selected object, the current layer. A request made
/// meanwhile (`layer.locate`) stands, and nothing is asked while an interaction is open, so a
/// drag's previews reveal nothing and its commit does.
pub(crate) fn request_reveal(&mut self, before: &LayersView) {
if self.uid != before.uid || self.layers_reveal != before.reveal || self.interaction.is_some() {
return;
}
let now = self.layers_view();
let mut request = None;
if now.isolation != before.isolation {
request = self.reveal_isolation(now.isolation, before.isolation);
}
if request.is_none() && now.rows != before.rows {
request = self.highlighted_rows().first().copied().map(LayersReveal::Row);
}
// A new selection asks for its object even when it changed the current layer too: the panel
// falls back to the current layer when it does not locate the object.
if request.is_none() && now.last_selected != before.last_selected {
request = now.last_selected.map(LayersReveal::Selected);
// An emptied selection leaves no object to locate.
if request.is_none() && matches!(self.layers_reveal, Some(LayersReveal::Selected(_))) {
self.layers_reveal = None;
}
}
if request.is_none() && now.active_layer != before.active_layer {
request = self.current_layer().map(LayersReveal::Current);
}
if request.is_some() {
self.layers_reveal = request;
}
}
/// The request for isolation moving from `before` to `now`: entering opens the isolated row,
/// leaving opens the layers around the row that was isolated.
fn reveal_isolation(&mut self, now: Option<NodeId>, before: Option<NodeId>) -> Option<LayersReveal> {
if let Some(root) = now.filter(|r| self.doc.node(*r).is_some()) {
self.layers_open.set(root, true);
return Some(LayersReveal::Row(root));
}
let former = before?;
for around in self.doc.ancestry(former)?.into_iter().filter(|a| *a != former) {
self.layers_open.set(around, true);
}
Some(LayersReveal::Row(former))
}
/// The object whose opacity mask View Opacity Mask shows ([`DocState::mask_view`]): only while
/// its mask is being edited, so leaving editing by any route (undo, deleting the object) ends it.
pub fn shown_mask(&self) -> Option<NodeId> {
+3
View File
@@ -33,6 +33,9 @@ pub struct Interaction {
/// The bounding box of `selection` in `doc`, measured once for a move drag
/// ([`crate::Session::move_drag_box`]): each step offsets it by the drag's move.
pub(crate) move_box: std::sync::OnceLock<Option<vectorcraft_doc::OrientedBox>>,
/// A switch to another document keeps the previews as one undo step in this one, as a panel field's scrub keeps
/// its edits; otherwise the switch cancels the interaction, as it does a drag.
pub keep_on_switch: bool,
}
/// What Object → Transform → Transform Again (⌘D) repeats ([`SessionState::last_transform`]).
+1 -1
View File
@@ -433,7 +433,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
#[cfg(test)]
use command_sets::given_ids;
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
pub use doc_state::{DocState, OpenRows, RecalledSelection};
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
#[cfg(test)]
use history::history_budget_for;
+16
View File
@@ -281,6 +281,10 @@ pub struct Prefs {
pub recovery_off_for_complex: bool,
pub recent_files_count: u32,
pub low_res_proxy_eps: bool,
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
/// fallback font with the missing-font warning (#4568).
pub pdf_import_embedded_fonts: bool,
pub anti_aliased_bitmaps: bool,
pub update_links: String,
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
@@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
impl Prefs {
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
return p.clone();
}
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
out["embeddedFonts"] = serde_json::json!(false);
out
}
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
/// checked against the range, so a value outside it is brought inside, and one that is not a
/// number gives the default.
@@ -592,6 +607,7 @@ impl Default for Prefs {
recovery_off_for_complex: false,
recent_files_count: 20,
low_res_proxy_eps: false,
pdf_import_embedded_fonts: true,
anti_aliased_bitmaps: false,
update_links: s("askWhenModified"),
pdf_text_as: s("text"),
+13 -3
View File
@@ -218,9 +218,14 @@ impl Session {
let _ = self.give_back_tool(view);
let _ = self.deactivate_tool(view);
// A batch leaves its interaction open in the document it leaves, to keep or roll back with
// the rest of the batch; anything else in progress (a drag) is cancelled.
// the rest of the batch; one that keeps on a switch is kept; anything else in progress (a
// drag) is cancelled.
if self.batch_stash.is_none() {
let _ = self.cancel_interaction();
let _ = if self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.keep_on_switch) {
self.commit_interaction()
} else {
self.cancel_interaction()
};
}
self.keep_tool_settings();
self.tool = self.make_tool(self.tool.id());
@@ -293,7 +298,9 @@ impl Session {
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
/// not only in the layers (#1738).
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
// Inline graphics in text take their size from their symbols' art (not saved either).
doc.resolve_inline_art();
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
@@ -303,6 +310,7 @@ impl Session {
// The symbols' type is measured now: the inline graphics showing those symbols take their
// art's measured size, a symbol's type before the type that shows that symbol inline.
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
warnings
}
/// Measure the type in open document `index` that `stale` picks (in its trees as
@@ -344,6 +352,8 @@ impl Session {
// (importers and the native reader have seen to theirs already, with a warning).
doc.limit_depth();
cmd::compositefonts::filter_loaded(&mut doc);
// Importers report binding failures; programmatic additions still need owned resources.
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
// Inline graphics in text take their size from their symbols' art (not saved).
doc.resolve_inline_art();
// Ruler guides a reader left in the saved list become nodes on their layers.
+20
View File
@@ -7,6 +7,10 @@ impl Session {
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
self.revealing(|s| s.edit_unwatched(label, f))
}
fn edit_unwatched<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
if self.script_running() {
return Err(EngineError::Busy);
}
@@ -197,6 +201,10 @@ impl Session {
/// Change only the selection (not an undo step).
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.revealing(|s| s.select_unwatched(f))
}
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
self.active_appearance_item = None;
let menu = self.menu.clone();
let st = self.doc_mut()?;
@@ -312,6 +320,7 @@ impl Session {
plane_placed: false,
copies: None,
move_box: std::sync::OnceLock::new(),
keep_on_switch: false,
});
Ok(())
}
@@ -390,6 +399,17 @@ impl Session {
}
pub fn commit_interaction(&mut self) -> Result<()> {
// The interaction is taken below, so its starting state is read first: the commit is what
// the previews that came before it changed.
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
let r = self.commit_interaction_unwatched();
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
fn commit_interaction_unwatched(&mut self) -> Result<()> {
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
+24
View File
@@ -59,6 +59,30 @@ impl Session {
/// Execute a command by id. This is THE entry point for every frontend.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
self.revealing(|s| s.execute_unwatched(id, params))
}
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
/// selection, then ask the Layers panel to reveal what it changed ([`DocState::request_reveal`]).
/// Nothing is asked inside a command, while an interaction is open or while a tool is busy: the
/// entry that ends them asks.
pub(super) fn revealing<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let before = (self.depth == 0 && !self.tool_busy()).then(|| self.active().map(crate::DocState::layers_view)).flatten();
let r = f(self);
if let Some(before) = before {
self.reveal_since(&before);
}
r
}
/// Ask the Layers panel of the active document to reveal what changed since `before`.
pub(super) fn reveal_since(&mut self, before: &crate::doc_state::LayersView) {
if let Some(st) = self.active_mut() {
st.request_reveal(before);
}
}
fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
+2 -2
View File
@@ -42,7 +42,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::SystemTime;
use vectorcraft_pdf::{PdfPreset, builtin_preset};
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
use vectorcraft_plugins::permissions::GrantToken;
use vectorcraft_plugins::safe_mode;
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
@@ -1555,7 +1555,7 @@ fn load_presets(dir: &Path) -> Vec<PdfPreset> {
for mut preset in file.presets {
let name = preset.name.trim().to_string();
let usable = !name.is_empty()
&& builtin_preset(&name).is_none()
&& builtin_preset(&name, APP).is_none()
&& !presets.iter().any(|q| q.name.eq_ignore_ascii_case(&name))
&& preset.settings.check_values().is_ok()
&& presets.len() < MAX_STORE_FILES;
+3 -3
View File
@@ -1,7 +1,7 @@
//! The Color Guide: `color.harmony` and saving several colours as swatches at once.
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::{Color, harmony};
use crate::*;
@@ -38,9 +38,9 @@ fn harmony_query_returns_the_group_and_its_grid() {
assert_eq!(r2["rule"], "splitComplementary");
assert_eq!(r2["grid"][0].as_array().unwrap().len(), 9, "4 steps by default");
// Every rule answers, base first.
for h in vectorcraft_color::harmony::Harmony::ALL {
for h in harmony::Harmony::ALL {
let r = s.execute("color.harmony", &json!({"color": "#3366cc", "rule": h.id()})).unwrap();
assert_eq!(r["colors"][0], "#3366cc", "{}", h.label());
assert_eq!(r["colors"][0], "#3366cc", "{}", harmony::label(h));
}
assert!(s.execute("color.harmony", &json!({"color": "#ff0000", "rule": "square"})).is_err());
assert!(s.execute("color.harmony", &json!({"rule": "triad"})).is_err());
+3 -3
View File
@@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
fn a_colorized_missing_link_placeholder_is_not_flattened() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() {
fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.edit("Colorize", |d, _| {
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
Ok(())
@@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() {
let mut s = session();
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.edit("Colorize", |d, _| {
let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
+2 -2
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::harmony::Harmony;
use vectorcraft_color::harmony::{self, Harmony};
use crate::*;
@@ -31,7 +31,7 @@ fn themes_save_list_edit_and_delete() {
let r = run(&mut s, "colorTheme.save", json!({"color": "#3366cc", "rule": "Triad", "name": " Sea "}));
assert_eq!(r["name"], "Sea");
let t = &run(&mut s, "colorTheme.list", json!({}))["themes"][1];
let want: Vec<String> = Harmony::Triad.theme(Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
let want: Vec<String> = harmony::theme(Harmony::Triad, Color::from_hex("#3366cc").unwrap()).iter().map(Color::to_hex).collect();
assert_eq!(t["colors"], json!(want));
assert_eq!(t["rule"], "triad");
// Names stay unique (ignoring case); replace edits a theme in place, renaming it if asked.
-10
View File
@@ -238,16 +238,6 @@ fn a_typed_closing_double_quote_opens_where_a_quote_opens() {
// More than one character is pasted text, not a typed quote.
let id = type_at(&mut s, 50.0, 300.0, &["”a”"]);
assert_eq!(text(&s, id).plain_text(), "”a”");
// An IME commit of a lone `”` that will open is not verbatim (it is rewritten); from the Glyphs
// panel it would be inserted as it is.
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 312.0), v).unwrap();
}
assert!(!s.tool_typed_text_is_verbatim("”", v));
assert!(s.tool_text_is_verbatim("”", v));
s.tool_key(ToolKey::Escape, Default::default(), v).unwrap();
// A `”` inserted from the Glyphs panel or pasted alone stays as inserted.
let id = enter_at(&mut s, 50.0, 325.0, &["”", "a"], false);
assert_eq!(text(&s, id).plain_text(), "”a");
+2 -4
View File
@@ -5107,10 +5107,8 @@ fn the_pen_continues_any_open_path_and_joins_another() {
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::PenJoin);
assert_eq!(s.cursor(Point::new(350.0, 200.0), none, v), Cursor::PenDrawing, "the middle of the other path");
// #1009: Use Precise Cursors makes the join pointer a crosshair too.
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v), Cursor::Crosshair);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
// #1009: Use Precise Cursors makes the join pointer a crosshair too (the canvas applies `Cursor::precise`).
assert_eq!(s.cursor(Point::new(300.0, 200.0), none, v).precise(), Cursor::Crosshair);
assert_eq!(gesture(&mut s, &[(300.0, 200.0)], none), 1);
let pts = |s: &Session, id| path(s, id).subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|x| (x.p.x, x.p.y))).collect::<Vec<_>>();
assert_eq!(pts(&s, a), [(100.0, 100.0), (200.0, 100.0), (300.0, 200.0), (400.0, 200.0)]);
-16
View File
@@ -302,19 +302,3 @@ fn ime_target_survives_edits_and_changes_with_the_document() {
let second = s.tool_ime_target(v).expect("the new document's type has a target");
assert_ne!(first.0, second.0, "a document replacement is a new IME owner");
}
/// The outgoing surrounding-text source excludes the pre-edit and reports UTF-8 byte offsets.
#[test]
fn ime_surrounding_excludes_the_preedit_and_remaps_offsets() {
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
click(&mut s, 100.0, 100.0);
s.tool_text("Hé", v).unwrap();
s.tool_preedit("xy", None, v).unwrap();
let vectorcraft_tools::ImeSurrounding::Available { text, cursor, anchor } = s.tool_ime_surrounding(4000, v) else {
panic!("type editing has a context");
};
assert_eq!(text, "Hé");
assert_eq!((cursor, anchor), (3, 3), "the caret sits after the committed text, before the pre-edit");
}
+52 -4
View File
@@ -1326,11 +1326,11 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
s.doc_mut().unwrap().locate_reveal = None;
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "the Layers panel reveals the located row");
s.doc_mut().unwrap().layers_reveal = None;
let undo = s.doc().unwrap().history.undo.len();
run(&mut s, "layer.locate", json!({"layersOnly": true}));
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "again for a row already highlighted");
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
@@ -1342,12 +1342,60 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(g)), "{p}");
}
run(&mut s, "select.none", json!({}));
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
}
/// The session asks the Layers panel to reveal what a top-level command changed: isolation, then
/// the highlighted rows, the last selected object and the current layer. An open interaction asks
/// for nothing, and a failed command changes nothing.
#[test]
fn the_layers_panel_is_asked_to_reveal_what_a_command_changed() {
use crate::LayersReveal::{Current, Row, Selected};
let mut s = session();
let (layer, sub, _, g, b, c) = tree(&mut s);
let take = |s: &mut Session| s.doc_mut().unwrap().layers_reveal.take();
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
run(&mut s, "layer.highlight", highlight_params([g], "set"));
assert_eq!(take(&mut s), Some(Row(g)), "a highlighted row");
// The current layer changes with the selection of art in another layer: the new selection asks
// for its object, and the panel falls back to the current layer when it does not locate it.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [c.0]}));
assert_eq!(take(&mut s), Some(Selected(c)), "a new selection wins over a new current layer");
// A new current layer alone asks for it: the highlighted row made current again.
run(&mut s, "layer.highlight", highlight_params([c], "set"));
take(&mut s);
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "layer.setCurrent", json!({"id": c.0}));
assert_eq!(take(&mut s), Some(Current(layer)), "a new current layer alone");
// Within the current layer only the last selected object changes.
s.doc_mut().unwrap().active_layer = Some(sub);
run(&mut s, "select.set", json!({"ids": [b.0]}));
take(&mut s);
run(&mut s, "select.set", json!({"ids": [g.0]}));
assert_eq!(take(&mut s), Some(Selected(g)), "the last selected object");
// Isolation entered and left reveals the isolated row.
run(&mut s, "object.isolate", json!({"id": g.0}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation entered");
run(&mut s, "object.exitIsolation", json!({}));
assert_eq!(take(&mut s), Some(Row(g)), "isolation left");
// A failed command asks for nothing.
assert!(s.execute("layer.locate", &json!({"id": 999_999})).is_err());
assert_eq!(take(&mut s), None);
// A command inside an open interaction asks for nothing either.
run(&mut s, "select.set", json!({"ids": [g.0]}));
take(&mut s);
s.begin_interaction("Drag").unwrap();
run(&mut s, "select.set", json!({"ids": [b.0]}));
assert_eq!(take(&mut s), None, "a preview");
s.cancel_interaction().unwrap();
}
#[test]
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
let mut s = session();
+9 -2
View File
@@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n
im.link.as_mut().unwrap().path = logo_ai.clone();
im.link.as_mut().unwrap().relative = None;
let key = im.key.clone();
d.images
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
d.images.insert(
key,
vectorcraft_doc::ImageBlob {
mime: "application/postscript".into(),
bytes: std::sync::Arc::new(eps.to_vec()),
proxy: None,
file_font: Default::default(),
},
);
Ok(())
})
.unwrap();
+23 -17
View File
@@ -1667,21 +1667,31 @@ fn mirror_axis(s: &Session) -> vectorcraft_tools::mirror::MirrorAxis {
vectorcraft_tools::mirror::MirrorAxis::of(&st.doc, &st.selection, 1.0).unwrap()
}
/// A press on the mirror axis at `at`, as the canvas's selection widgets take it.
fn mirror_press(s: &mut Session, at: Point) -> vectorcraft_tools::mirror::MirrorDrag {
s.with_tool_context(ViewInfo::default(), |cx| vectorcraft_tools::mirror::MirrorDrag::hit(cx, at, Mods::default())).expect("a press on the axis")
}
/// The mirror axis drag `d` moved to `to`, its actions applied as the canvas's selection widgets apply them.
fn mirror_drag(s: &mut Session, d: &mut vectorcraft_tools::mirror::MirrorDrag, to: Point, mods: Mods) {
let acts = s.with_tool_context(ViewInfo::default(), |cx| d.drag(cx, to, mods));
s.apply_actions(acts).unwrap();
}
#[test]
fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let before = node(&s, id);
let axis = mirror_axis(&s);
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let h = crate::tests::history(&s);
for (kind, dx) in [(PointerKind::Down, 0.0), (PointerKind::Drag, 20.0), (PointerKind::Drag, 30.0), (PointerKind::Up, 40.0)] {
s.pointer(&PointerEvent::new(kind, axis.center.x + dx, axis.center.y), v).unwrap();
let mut d = mirror_press(&mut s, axis.center);
for dx in [20.0, 30.0, 40.0] {
mirror_drag(&mut s, &mut d, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0), Mods::default());
assert!(close(mirror_axis(&s).center, axis.center + vectorcraft_geom::Vec2::new(dx, 0.0)));
}
s.apply_actions(d.finish()).unwrap();
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
let after = node(&s, id);
let (NodeKind::Repeat(a), NodeKind::Repeat(b)) = (&before.kind, &after.kind) else { panic!() };
@@ -1695,33 +1705,29 @@ fn mirror_axis_drag_previews_once_and_undo_redo_preserve_source() {
#[test]
fn mirror_axis_rotation_snaps_and_escape_restores_document_and_history() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
rect(&mut s, 100.0, 100.0, 60.0, 80.0);
let id = id_of(&s.execute("object.repeat.mirror", &json!({})).unwrap());
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
let before = node(&s, id);
let h = crate::tests::history(&s);
let axis = mirror_axis(&s);
let end = axis.ends[1];
let destination = axis.center + vectorcraft_geom::Vec2::new(70.0, 60.0);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Drag, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(mirror_axis(&s).center, axis.center);
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y), v).unwrap();
s.apply_actions(d.cancel()).unwrap();
assert_eq!(node(&s, id), before);
assert_eq!(crate::tests::history(&s), h);
// A click is not an edit, and a subsequent real drag still works after cancellation.
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y), v).unwrap();
let click = mirror_press(&mut s, end).finish();
s.apply_actions(click).unwrap();
assert_eq!(crate::tests::history(&s), h);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, destination.x, destination.y).with_mods(shift), v).unwrap();
let mut d = mirror_press(&mut s, end);
mirror_drag(&mut s, &mut d, destination, shift);
s.apply_actions(d.finish()).unwrap();
assert!((mirror_axis(&s).angle - 45.0).abs() < 1e-6);
assert_eq!(crate::tests::history(&s).0, h.0 + 1);
}
+5 -4
View File
@@ -4,7 +4,7 @@
use serde_json::{Value, json};
use crate::Session;
use crate::cmd::fileio::pdf::DEFAULT_PRESET;
use vectorcraft_pdf::{APP, default_preset_name};
fn session() -> Session {
let mut s = Session::new();
@@ -31,14 +31,15 @@ fn built_in_presets_are_listed_and_read_only() {
let mut s = session();
let v = s.execute("pdf.preset.list", &json!({})).unwrap();
let rows = v["presets"].as_array().unwrap();
assert_eq!(rows[0]["name"], DEFAULT_PRESET);
let default = default_preset_name(APP);
assert_eq!(rows[0]["name"], default);
assert!(rows.iter().all(|r| r["builtIn"] == true && !r["description"].as_str().unwrap().is_empty()));
let row = |n: &str| rows.iter().find(|r| r["name"] == n).unwrap_or_else(|| panic!("{n}"));
for n in ["High Quality Print", "Press Quality", "Smallest File Size", "PDF/X-1a:2001", "PDF/X-3:2002", "PDF/X-4:2010"] {
assert_eq!(row(n)["builtIn"], true);
}
assert!(rows.iter().all(|r| r["supported"] == true), "every built-in standard is written");
assert_eq!(row(DEFAULT_PRESET)["settings"]["preserveEditing"], true);
assert_eq!(row(&default)["settings"]["preserveEditing"], true);
// Read-only: neither changed nor deleted, in any case.
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "press quality", "compatibility": "1.4"}))));
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "default"}))));
@@ -96,7 +97,7 @@ fn presets_export_and_import_round_trip() {
let r = s.execute("pdf.preset.import", &json!({"data": text})).unwrap();
assert_eq!(r["imported"], json!(["Proof", "Press Quality 2"]), "a built-in name gets a number");
assert_eq!(s.prefs.pdf_presets[0], saved[0], "the same preset comes back");
let press = vectorcraft_pdf::builtin_preset("Press Quality").unwrap();
let press = vectorcraft_pdf::builtin_preset("Press Quality", APP).unwrap();
assert_eq!(s.prefs.pdf_presets[1].settings, press.settings);
// replace: saved presets of the same names are overwritten.
let r = s.execute("pdf.preset.import", &json!({"data": text, "replace": true})).unwrap();
+4 -1
View File
@@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
s.edit("Brush", |d, _| {
d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d.images.insert(
"k".into(),
vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() },
);
let im = vectorcraft_doc::ImageObject {
key: "k".into(),
width: 2,
+50 -31
View File
@@ -699,7 +699,8 @@ fn double_clicking_a_single_object_isolates_it() {
}
/// General › Use Precise Cursors (#394): the Pen's pointer becomes a crosshair; the Selection
/// tool's arrow stays.
/// tool's arrow stays. The canvas applies the preference to the tool's own pointer
/// (`Cursor::precise`).
#[test]
fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
use vectorcraft_tools::{Cursor, Mods};
@@ -712,41 +713,31 @@ fn use_precise_cursors_makes_drawing_cursors_crosshairs() {
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(cursor(&mut s, "pen").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper").precise(), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection").precise(), Cursor::Arrow);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
}
/// Caps Lock gives the drawing tools the precise crosshair while it is on, and leaves the saved
/// Use Precise Cursors preference as it was.
/// Caps Lock is reported and set through `view.capsLock`, and leaves the saved Use Precise
/// Cursors preference as it was; the canvas gives the drawing tools the crosshair while it is on.
#[test]
fn caps_lock_gives_drawing_tools_the_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let cursor = |s: &mut Session, tool: &str| {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.cursor(vectorcraft_geom::Point::new(300.0, 300.0), Mods::default(), ViewInfo::default())
};
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
assert_eq!(s.execute("view.capsLock", &json!({"on": true})).unwrap(), json!({"on": true}));
assert!(!s.prefs.use_precise_cursors, "Caps Lock leaves the preference off");
assert_eq!(cursor(&mut s, "pen"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "lasso"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Crosshair);
assert_eq!(cursor(&mut s, "selection"), Cursor::Arrow);
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": true}));
assert_eq!(s.execute("view.capsLock", &json!({"on": false})).unwrap(), json!({"on": false}));
assert_eq!(cursor(&mut s, "pen"), Cursor::Pen);
assert_eq!(cursor(&mut s, "eyedropper"), Cursor::Eyedropper);
assert!(s.execute("view.capsLock", &json!({"on": 1})).is_err());
assert_eq!(s.execute("view.capsLock", &json!({})).unwrap(), json!({"on": false}));
}
/// Use Precise Cursors changes the pointer of the tools that have one of their own: off, each shows its own
/// pointer; on, a crosshair. Every other drawing tool shows a crosshair either way, and the Type tool and the
/// Scissors over no path keep theirs.
/// pointer; on, a crosshair (the canvas applies `Cursor::precise` to it). Every other drawing tool shows a
/// crosshair either way, and the Type tool and the Scissors over no path keep theirs.
#[test]
fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
use vectorcraft_tools::{Cursor, Mods};
@@ -804,13 +795,13 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": true})).unwrap();
for (tool, _) in own {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
for tool in always {
assert_eq!(cursor(&mut s, tool), Cursor::Crosshair, "{tool} on");
assert_eq!(cursor(&mut s, tool).precise(), Cursor::Crosshair, "{tool} on");
}
assert_eq!(cursor(&mut s, "type"), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors"), Cursor::ScissorsNotAllowed);
assert_eq!(cursor(&mut s, "type").precise(), Cursor::Text);
assert_eq!(cursor(&mut s, "scissors").precise(), Cursor::ScissorsNotAllowed);
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": false})).unwrap();
for (tool, c) in own {
assert_eq!(cursor(&mut s, tool), c, "{tool} off again");
@@ -818,7 +809,8 @@ fn use_precise_cursors_swaps_the_tools_own_pointers_for_a_crosshair() {
}
/// With no selected path, the Smooth tool shows Not Allowed, and Use Precise Cursors leaves it so; with a
/// selected path, it shows its own pointer, or a crosshair with the preference on.
/// selected path, it shows its own pointer, or a crosshair with the preference on (the canvas applies
/// `Cursor::precise`).
#[test]
fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
use vectorcraft_tools::{Cursor, Mods};
@@ -826,20 +818,21 @@ fn use_precise_cursors_keeps_the_smooth_tools_not_allowed_pointer() {
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let at = vectorcraft_geom::Point::new(300.0, 300.0);
s.select_tool("smooth", ViewInfo::default()).unwrap();
let shown = |c: Cursor, precise: bool| if precise { c.precise() } else { c };
for precise in [false, true] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), Cursor::NotAllowed, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), Cursor::NotAllowed, "precise {precise}");
}
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for (precise, c) in [(false, Cursor::Smooth), (true, Cursor::Crosshair)] {
s.execute("prefs.set", &json!({"key": "usePreciseCursors", "value": precise})).unwrap();
assert_eq!(s.cursor(at, Mods::default(), ViewInfo::default()), c, "precise {precise}");
assert_eq!(shown(s.cursor(at, Mods::default(), ViewInfo::default()), precise), c, "precise {precise}");
}
}
/// With Alt held while drawing, the Pencil and the Paintbrush show their closing cursors, and Use Precise Cursors
/// turns those into a crosshair too.
/// turns those into a crosshair too (the canvas applies `Cursor::precise`).
#[test]
fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind};
@@ -853,7 +846,9 @@ fn alt_shows_the_pencil_and_paintbrush_closing_cursors() {
s.select_tool(tool, ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0), ViewInfo::default()).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), ViewInfo::default()).unwrap();
assert_eq!(s.cursor(at, alt, ViewInfo::default()), if precise { Cursor::Crosshair } else { c }, "{tool}, precise {precise}");
let shown = s.cursor(at, alt, ViewInfo::default());
assert_eq!(shown, c, "{tool}, precise {precise}");
assert_eq!(shown.precise(), Cursor::Crosshair, "{tool}");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), ViewInfo::default()).unwrap();
}
}
@@ -2167,10 +2162,14 @@ fn real_time_drawing_off_still_shows_a_dragged_nine_slice_guide() {
let left = |s: &Session| s.doc().unwrap().doc.symbol_nine_slice("Box").unwrap().left;
assert_eq!(left(&s), 0.25);
let steps = s.doc().unwrap().history.undo.len();
s.pointer(&PointerEvent::new(PointerKind::Down, 125.0, 150.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 110.0, 150.0), v).unwrap();
let drag = crate::tests::symbol_nine_slice::guide_drag(
&mut s,
v,
vectorcraft_geom::Point::new(125.0, 150.0),
vectorcraft_geom::Point::new(110.0, 150.0),
);
assert!((left(&s) - 0.1).abs() < 1e-9, "the guide moves while dragged: {}", left(&s));
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 150.0), v).unwrap();
s.apply_actions(drag.finish()).unwrap();
let d = s.doc().unwrap();
assert!((left(&s) - 0.1).abs() < 1e-9);
assert_eq!((d.history.undo.len(), d.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Symbol Options")));
@@ -2979,6 +2978,26 @@ fn snap_to_glyph_options_read_set_and_reset() {
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
}
/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default)
/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568).
#[test]
fn the_embedded_fonts_preference_reaches_the_import_options() {
use crate::cmd::fileio::LoadOptions;
let mut s = Session::new();
assert!(s.prefs.pdf_import_embedded_fonts, "on by default");
let on = s.prefs.with_pdf_font_choice(&json!({}));
assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts);
s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap();
let off = s.prefs.with_pdf_font_choice(&json!({"page": 2}));
assert_eq!(off["page"], 2, "the call's own params stay");
assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts);
assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts);
// A call that says so wins over the preference.
let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true}));
assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts);
assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err());
}
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
/// values change nothing, preferences saved without the group read it as all on, and resetting the
+71
View File
@@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() {
assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count());
}
const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression";
const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
fn carried_font_copy() -> (Arc<MemoryStore>, vectorcraft_doc::NodeId) {
use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject};
let (mut s, store) = session();
let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec()));
// An uninstalled family ensures the fixture must be read from the recovered resource.
let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() };
let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style);
text.file_fonts = Some(Box::new(FileFonts::new(
vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }],
"x",
)));
let id = doc.alloc_id();
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
let saved = s.execute("file.recovery.save", &json!({})).unwrap();
let file = saved["saved"][0]["file"].as_str().unwrap();
let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap();
assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry");
drop(s);
(store, id)
}
#[test]
fn recovered_carried_fonts_bind_after_their_resources_are_restored() {
use vectorcraft_doc::NodeKind;
use vectorcraft_text::FontDb;
let (store, id) = carried_font_copy();
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}");
let doc = &s.doc().unwrap().doc;
assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES);
let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") };
let db = FontDb::global();
let laid = vectorcraft_text::layout(db, text);
assert_eq!(laid.glyphs.len(), 1);
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes");
}
#[test]
fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() {
for missing in [true, false] {
let (store, id) = carried_font_copy();
let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap();
if missing {
store.remove(&blob).unwrap();
} else {
store.write(&blob, b"not a font").unwrap();
}
let mut s = relaunch(&store);
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
let warnings = reply["restored"][0]["warnings"].as_array().unwrap();
assert!(
warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))),
"missing={missing}: {reply}"
);
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}");
}
}
#[test]
fn restored_recovery_copies_keep_the_original_pdf_preference() {
let dir = crate::tests_links::Folder::new("recovered-pdf-preference");
+8 -2
View File
@@ -366,12 +366,18 @@ fn shaper_widget_switches_between_face_selection_and_construction_mode() {
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
}
};
// A click on the widget, as the canvas's selection widgets run it before the tool.
let widget_click = |s: &mut Session, p: Point| {
let acts: Vec<_> = s.with_tool_context(v, |cx| vectorcraft_tools::shaperwidget::click(cx, p).into_iter().collect());
assert!(!acts.is_empty(), "the click is on the widget");
s.apply_actions(acts).unwrap();
};
for tool in ["shaper", "selection"] {
s.select_tool(tool, v).unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let w = widget(&s);
assert!(!w.construction);
click(&mut s, w.at);
widget_click(&mut s, w.at);
assert_eq!(s.doc().unwrap().isolation, Some(sources), "{tool}");
assert!(widget(&s).construction);
if tool == "shaper" {
@@ -388,7 +394,7 @@ fn shaper_widget_switches_between_face_selection_and_construction_mode() {
assert_eq!(fill(&s, g, 15.0, 50.0).as_deref(), Some("#ff0000"));
let w = widget(&s);
assert!(w.construction);
click(&mut s, w.at);
widget_click(&mut s, w.at);
assert_eq!(s.doc().unwrap().isolation, None, "{tool}");
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
s.execute("object.move", &json!({"dx": -10, "dy": 0})).unwrap();
+14 -6
View File
@@ -220,6 +220,16 @@ fn a_dynamic_instance_keeps_its_changes_through_the_guides() {
assert_ne!(fills[0].as_deref(), Some("#ff0000"), "only the changed object");
}
/// A press on the edited symbol's 9-slice guide at `from` dragged to `to`, run as the canvas's
/// selection widgets run it; the caller ends it with `finish` or `cancel`.
pub(super) fn guide_drag(s: &mut Session, v: ViewInfo, from: Point, to: Point) -> vectorcraft_tools::nineslice::GuideDrag {
let press = PointerEvent::new(PointerKind::Down, from.x, from.y);
let mut d = s.with_tool_context(v, |cx| vectorcraft_tools::nineslice::GuideDrag::hit(cx, &press)).expect("a guide at the press");
let acts = s.with_tool_context(v, |cx| d.drag(cx, to));
s.apply_actions(acts).unwrap();
d
}
/// The boxes of the paths a symbol instance `id` draws, placed through its symbol's guides.
fn placed_boxes(s: &Session, id: NodeId) -> Vec<Rect> {
let d = &s.doc().unwrap().doc;
@@ -247,9 +257,8 @@ fn a_guide_dragged_on_the_canvas_changes_how_a_scaled_instance_draws() {
// that span to the left of the left guide.
let (from, right) = (mid(&e, NineSliceGuide::Left), mid(&e, NineSliceGuide::Right));
let to = from + (from - right) * 0.4;
s.pointer(&PointerEvent::new(PointerKind::Down, from.x + 1.0, from.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to.x, to.y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to.x, to.y), v).unwrap();
let d = guide_drag(&mut s, v, Point::new(from.x + 1.0, from.y), to);
s.apply_actions(d.finish()).unwrap();
s.execute("symbol.exitEditing", &json!({})).unwrap();
let boxes = placed_boxes(&s, id);
assert_eq!(boxes.len(), 3, "{boxes:?}");
@@ -316,9 +325,8 @@ fn a_guide_dragged_past_the_arts_edge_lies_outside_it() {
// The guides lie a quarter in from each edge, so the art's left edge lies half the guides'
// distance to the left of the left guide, and 25 % outside it lies as far again.
let to = l - (r - l);
s.pointer(&PointerEvent::new(PointerKind::Down, l + 1.0, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, to, y), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, to, y), v).unwrap();
let d = guide_drag(&mut s, v, Point::new(l + 1.0, y), Point::new(to, y));
s.apply_actions(d.finish()).unwrap();
let g = s.doc().unwrap().doc.symbol_nine_slice("Panel").unwrap();
assert!((g.left + 0.25).abs() < 1e-9, "{g:?}");
let e = s.doc().unwrap().doc.edited_nine_slice().unwrap();
+16 -44
View File
@@ -6,7 +6,7 @@ use vectorcraft_geom::Point;
use vectorcraft_tools::distort::perspective::widget::WidgetPlace;
use vectorcraft_tools::draw2::FEEDBACK;
use vectorcraft_tools::shape::MAX_CORNER_RADIUS;
use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, settings};
use crate::{EngineError, Prefs, Result, Session};
@@ -42,6 +42,9 @@ pub struct ViewInfo {
pub screen: Option<vectorcraft_tools::ScreenFrame>,
/// The view's active artboard (an index): artboard rulers measure from it.
pub artboard: usize,
/// Precise cursors in this call: the canvas's `CanvasSpace::precise`, the preference toggled by
/// Caps Lock. The one source for the tools' crosshair and for hiding the brush tip.
pub precise: bool,
}
impl Default for ViewInfo {
@@ -61,6 +64,7 @@ impl Default for ViewInfo {
shape_widgets: true,
screen: None,
artboard: 0,
precise: false,
}
}
}
@@ -501,7 +505,7 @@ impl Session {
screen: view.screen,
plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position),
plane_targets: self.prefs.perspective_widget.targets(),
precise_cursors: self.precise_cursors(),
precise_cursors: view.precise,
global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()),
interaction_doc: st.interaction.as_ref().map(|it| &*it.doc),
};
@@ -519,6 +523,13 @@ impl Session {
}
}
/// Runs `f` with the context the tools read for the active document seen through `view`, for code
/// outside the engine that draws on the tools' geometry (the canvas's selection widgets).
/// `R::default()` with no document open.
pub fn with_tool_context<R: Default>(&mut self, view: ViewInfo, f: impl FnOnce(&ToolContext) -> R) -> R {
self.with_tool_cx(view, |_, cx| f(cx))
}
/// The error of a tool that panicked in the last [`Self::with_tool_cx`] call, if any.
fn take_tool_panic(&mut self) -> Result<()> {
self.tool_panic.take().map_or(Ok(()), Err)
@@ -1094,30 +1105,6 @@ impl Session {
r
}
/// Would [`Session::tool_text`] insert `text` unchanged (no control-character filtering,
/// newline normalization or document formatting such as Typographer's Quotes)? An IME commit
/// the application rewrites is an application edit, not an accepted IME insertion.
pub fn tool_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.text_input_is_verbatim(cx, text))
}
/// [`Session::tool_text_is_verbatim`] for text typed on the keyboard, as
/// [`Session::tool_typed_text`] would insert it: a lone typed `”` that Typographer's Quotes
/// turns into an opening quote is not verbatim.
pub fn tool_typed_text_is_verbatim(&mut self, text: &str, view: ViewInfo) -> bool {
self.keyboard_text = true;
let v = self.tool_text_is_verbatim(text, view);
self.keyboard_text = false;
v
}
/// Does the active tool's open typing session still match the document? An IME commit after
/// an external edit starts a fresh session (an application-side reset), so its receipt must
/// not be accepted as an unchanged IME insertion.
pub fn tool_ime_session_matches(&mut self, view: ViewInfo) -> bool {
self.with_tool_cx(view, |t, cx| t.ime_session_matches_document(cx))
}
/// Whether the active tool currently owns keyboard text input, as the Type tool does while editing.
pub fn tool_wants_text(&self) -> bool {
self.tool.wants_text()
@@ -1154,14 +1141,6 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.ime_target(cx))
}
/// The committed logical text around the IME cursor (UTF-8 byte offsets), with any pre-edit
/// removed and at most `max_bytes` bytes copied: the app's outgoing surrounding-text producer
/// (egui E21b) reads it. An explicit [`ImeSurrounding::Unavailable`] carries the narrow reason
/// (no editor, invalid offsets, or a selection wider than the limit).
pub fn tool_ime_surrounding(&mut self, max_bytes: usize, view: ViewInfo) -> ImeSurrounding {
self.with_tool_cx(view, |t, cx| t.ime_surrounding(cx, max_bytes))
}
/// Is the active tool showing uncommitted IME text?
pub fn tool_composing(&self) -> bool {
self.tool.composing()
@@ -1322,13 +1301,12 @@ impl Session {
v
}
/// The pointer the active tool shows at `p` (General › Use Precise Cursors, or Caps Lock while
/// it is on, makes the drawing tools' a crosshair, [`Cursor::precise`]). With Cmd held, the pointer of the selection tool a
/// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
let c = match lent {
match lent {
Some(id) => {
let lent = self.make_tool(id);
let own = std::mem::replace(&mut self.tool, lent);
@@ -1337,13 +1315,7 @@ impl Session {
c
}
None => self.with_tool_cx(view, |t, cx| t.cursor(cx, p, mods)),
};
if self.precise_cursors() { c.precise() } else { c }
}
/// General › Use Precise Cursors is on, or Caps Lock is.
fn precise_cursors(&self) -> bool {
self.prefs.use_precise_cursors || self.caps_lock
}
}
pub fn tool_options(&self) -> Value {
+2 -2
View File
@@ -662,7 +662,7 @@ impl<'a> Reader<'a> {
};
// The placeholder is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
let key = linked_key(&blob, &path);
self.doc.images.entry(key.clone()).or_insert(blob);
self.warn(LINKED_PLACEHOLDERS);
@@ -905,7 +905,7 @@ impl<'a> Reader<'a> {
}
// The preview is all the document has of the file: what a missing link shows.
let bytes = Arc::new(png);
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
let key = linked_key(&blob, &path);
let fresh = !self.doc.images.contains_key(&key);
self.doc.images.entry(key.clone()).or_insert(blob);
+1 -1
View File
@@ -586,7 +586,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
let mut doc = f.document;
for (k, img) in f.images {
let bytes = bytes_of(&img).ok_or_else(|| FormatError::BadImage(k.clone()))?;
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None };
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None, file_font: Default::default() };
// Until the linked file is read, the preview stands in for it.
if img.proxy {
blob.proxy = Some(blob.bytes.clone());
+3 -1
View File
@@ -57,7 +57,9 @@ fn include_linked_files_keeps_the_files_bytes() {
// Only the preview loaded (the file was never found): the preview is all there is to write.
let mut missing = linked_doc();
let preview = Arc::new(vec![9, 9]);
missing.images.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
missing
.images
.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
let out = save_with(&missing, &SaveOptions { include_linked: true, ..SaveOptions::default() }).unwrap();
assert_eq!(json_of(&out)["images"]["k"]["proxy"], true);
}
-1
View File
@@ -11,7 +11,6 @@ workspace = true
[dependencies]
kurbo = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
vectorcraft-testkit = { workspace = true }
+1
View File
@@ -22,6 +22,7 @@ vectorcraft-format = { workspace = true }
vectorcraft-tools = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-doc = { workspace = true }
craft = { workspace = true, features = ["automation"] }
serde_json = { workspace = true }
log = { workspace = true }
+57 -148
View File
@@ -1,10 +1,10 @@
//! Where MCP tool calls end up: a control-channel method call.
use std::io::{BufReader, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use std::net::{SocketAddr, ToSocketAddrs};
use serde_json::{Value, json};
use craft::automation::args::{ControlOptions, EnvNames};
use craft::automation::client::ControlClient;
use serde_json::Value;
/// Something that answers control-channel methods (`engine.execute`, `document.inspect`,
/// `ui.pointer`, `ui.render`, `app.export`, …). See `vectorcraft_ui_egui::control` for the list.
@@ -17,25 +17,40 @@ pub trait Backend {
fn describe(&self) -> String;
}
/// The control token a running app was started with: `VECTORCRAFT_CONTROL_TOKEN`, else the
/// trimmed content of the file `VECTORCRAFT_CONTROL_TOKEN_FILE` names. One place reads it, for
/// MCP and the CLI alike.
pub fn control_token() -> Result<String, String> {
let names = EnvNames::for_app("VECTORCRAFT");
let options = ControlOptions::from_env(&names).map_err(|e| e.to_string())?;
let missing = || format!("no control token: set {} (or {} to a file that holds it)", names.token, names.token_file);
if let Some(token) = options.token {
return Ok(token);
}
let file = options.token_file.ok_or_else(missing)?;
let text = std::fs::read_to_string(&file).map_err(|e| format!("cannot read the control token file {}: {e}", file.display()))?;
match text.trim() {
"" => Err(missing()),
token => Ok(token.to_owned()),
}
}
/// A running VectorCraft app, reached through its loopback control port.
pub struct Remote {
addr: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
sock: SocketAddr,
token: String,
client: Option<ControlClient>,
}
/// Longest accepted control-channel reply line (bytes, without the newline). The app answers
/// small JSON objects except for images, which reach tens of megabytes; anything longer is refused
/// and the connection dropped, so a faulty endpoint can't make the server buffer without bound
/// (#1727).
const MAX_REPLY_BYTES: usize = 256 * 1024 * 1024;
impl Remote {
/// Connect to `addr` (e.g. `127.0.0.1:7979`), failing fast when nothing is listening.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1 };
r.reconnect()?;
Ok(r)
/// Connect to `addr` (e.g. `127.0.0.1:7979`) with the app's control `token`, failing fast when
/// nothing is listening.
pub fn connect(addr: &str, token: &str) -> std::io::Result<Self> {
let sock =
addr.to_socket_addrs()?.next().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")))?;
let client = ControlClient::connect(sock, token).map_err(std::io::Error::other)?;
Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client) })
}
pub fn addr(&self) -> &str {
@@ -43,145 +58,39 @@ impl Remote {
}
#[cfg(test)]
pub(crate) fn connection_probe(&self) -> TcpStream {
self.conn.as_ref().unwrap().1.try_clone().unwrap()
pub(crate) fn is_usable(&self) -> bool {
self.client.as_ref().is_some_and(ControlClient::is_usable)
}
fn reconnect(&mut self) -> std::io::Result<()> {
self.conn = None;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs()? {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
Ok(s) => {
s.set_nodelay(true).ok();
// The app answers within 60 s (its own timeout); leave headroom.
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
return Ok(());
}
Err(e) => last = e,
}
/// The open connection; a new one when the app closed the last (an idle connection, a restart)
/// or it holds a line nobody asked for.
fn open_client(&mut self, method: &str) -> Result<&mut ControlClient, String> {
if !self.client.as_ref().is_some_and(ControlClient::is_usable) {
self.client = None;
let client = ControlClient::connect(self.sock, &self.token)
.map_err(|e| format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr))?;
self.client = Some(client);
}
Err(last)
}
fn prepare_connection(&mut self) -> std::io::Result<()> {
if let Some((_, stream)) = self.conn.as_ref() {
stream.set_nonblocking(true)?;
let probe = stream.peek(&mut [0]);
stream.set_nonblocking(false)?;
match probe {
// Closed by the app, or holding bytes nobody asked for (an app that explains why it
// closes): either way no reply to the next request can be read from it.
Ok(_) => self.conn = None,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(_) => self.conn = None,
}
}
if self.conn.is_none() {
self.reconnect()?;
}
Ok(())
}
/// Wait until the app starts to answer, giving up when the call is cancelled
/// ([`vectorcraft_engine::cancel`]): the app has no way to stop what it runs, but this server
/// stops waiting for it (the connection is dropped, so a late answer can't be mistaken for
/// the next call's). Without a cancellable call this is just the read the caller does next.
fn wait_for_reply(stream: &TcpStream) -> std::io::Result<()> {
const POLL: Duration = Duration::from_millis(100);
const LIMIT: Duration = Duration::from_secs(90);
if !vectorcraft_engine::cancel::is_cancellable() {
return Ok(());
}
let start = std::time::Instant::now();
let kept = stream.read_timeout()?;
stream.set_read_timeout(Some(POLL))?;
let outcome = loop {
match stream.peek(&mut [0]) {
// Bytes (or the end of the stream) to read now.
Ok(_) => break Ok(()),
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
if vectorcraft_engine::cancel::is_cancelled() {
break Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"cancelled; the app may still finish what it was asked, which can't be stopped from here",
));
}
if start.elapsed() >= LIMIT {
break Err(e);
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => break Err(e),
}
};
stream.set_read_timeout(kept)?;
outcome
}
fn roundtrip(&mut self, line: &str) -> std::io::Result<String> {
let Some((reader, writer)) = self.conn.as_mut() else {
return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected to the app"));
};
writer.write_all(line.as_bytes())?;
writer.write_all(b"\n")?;
writer.flush()?;
Self::wait_for_reply(writer)?;
let mut buf = Vec::new();
if !crate::server::read_line_capped(reader, &mut buf, MAX_REPLY_BYTES)? {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed"));
}
if buf.len() > MAX_REPLY_BYTES {
// A faulty endpoint's endless line is refused rather than buffered: the connection is
// dropped and the call reports uncertainty, as for any reply that never arrived whole.
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("control reply longer than {MAX_REPLY_BYTES} bytes")));
}
String::from_utf8(buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
self.client.as_mut().ok_or_else(|| format!("VectorCraft app at {} is not reachable; `{method}`: nothing was sent", self.addr))
}
}
impl Backend for Remote {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.prepare_connection().map_err(|e| {
self.conn = None;
format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr)
})?;
let id = self.next_id;
self.next_id += 1;
let line = json!({"id": id, "method": method, "params": params}).to_string();
let v: Value = self
.roundtrip(&line)
.and_then(|reply| {
serde_json::from_str(reply.trim())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("bad reply from app: {e}")))
})
.map_err(|e| {
self.conn = None;
format!("VectorCraft app at {}: `{method}` failed: {e}; operation may have completed; inspect state before retrying", self.addr)
})?;
if v.get("id").is_none() && v.get("ok").and_then(Value::as_bool) == Some(false) {
// The app's refusals carry no id (too many connections, a line it would not read):
// it ran nothing and closes the connection, so the next call starts a fresh one.
self.conn = None;
let why = v.get("error").and_then(Value::as_str).unwrap_or("unknown error");
return Err(format!("VectorCraft app at {} refused `{method}`: {why}; nothing was run", self.addr));
}
if v.get("id") != Some(&json!(id)) {
// Not the answer to this call: the stream is desynchronised (or the endpoint faulty),
// so the connection is dropped and the next call starts a fresh one. The operation may
// still have completed, as with any reply that never arrived whole (#1728).
self.conn = None;
return Err(format!(
"VectorCraft app at {}: reply id mismatch (expected {id}); connection dropped; operation may have completed; inspect state before retrying",
self.addr
));
}
if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string())
let addr = self.addr.clone();
let client = self.open_client(method)?;
// The app can't stop what it runs, but a cancelled call stops waiting for it.
let cancellable = vectorcraft_engine::cancel::is_cancellable();
let result =
if cancellable { client.call_until(method, params, &vectorcraft_engine::cancel::is_cancelled) } else { client.call(method, params) };
match result {
Ok(value) => Ok(value),
// The connection survived: the app answered with this error.
Err(e) if !client.is_broken() => Err(e),
Err(_) if cancellable && vectorcraft_engine::cancel::is_cancelled() => Err(format!(
"VectorCraft app at {addr}: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here"
)),
Err(e) => Err(format!("VectorCraft app at {addr}: `{method}` failed: {e}; operation may have completed; inspect state before retrying")),
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ mod server;
mod tools;
mod ui_catalog;
pub use backend::{Backend, Remote};
pub use backend::{Backend, Remote, control_token};
pub use headless::Headless;
pub use prompts::{PROMPTS, PromptArg, PromptDef};
pub use resources::{DOC_JSON_URI, DOC_URI, TEMPLATES};
+121 -58
View File
@@ -910,6 +910,9 @@ fn errors_are_tool_results_not_crashes() {
// ---------- remote ----------
/// A fake control server: answers `document.inspect`, echoes `engine.execute`, errors otherwise.
/// The control token the fake apps take.
const TOKEN: &str = "test-token";
fn fake_app() -> (String, std::thread::JoinHandle<Vec<Value>>) {
fake_app_refusing_confirm(None)
}
@@ -934,6 +937,7 @@ fn fake_app_with(refusal: Option<&'static str>, answers_in_set: bool) -> (String
for line in BufReader::new(stream).lines() {
let msg: Value = serde_json::from_str(&line.unwrap()).unwrap();
let reply = match msg["method"].as_str().unwrap() {
"auth" if msg["params"]["token"] == TOKEN => json!({"ok": true}),
"document.inspect" => json!({"ok": true, "result": {"title": "Remote", "layers": []}}),
"engine.execute" => json!({"ok": true, "result": {"echo": msg["params"]}}),
"ui.inspect" => json!({"ok": true, "result": {"tool": "selection"}}),
@@ -959,7 +963,10 @@ fn fake_app_with(refusal: Option<&'static str>, answers_in_set: bool) -> (String
let mut reply = reply;
reply["id"] = msg["id"].clone();
writeln!(out, "{reply}").unwrap();
seen.push(msg);
// The connection's sign-in is not a call the app was asked to run.
if msg["method"] != "auth" {
seen.push(msg);
}
}
seen
});
@@ -969,7 +976,7 @@ fn fake_app_with(refusal: Option<&'static str>, answers_in_set: bool) -> (String
#[test]
fn remote_forwards_methods() {
let (addr, h) = fake_app();
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let r = call(&mut s, 1, "inspect_document", json!({}));
assert!(text_of(&r).contains("Remote"));
let r = call(&mut s, 2, "run_command", json!({"command": "object.group"}));
@@ -991,7 +998,7 @@ fn remote_forwards_methods() {
#[test]
fn answer_dialog_sets_fields_in_order_and_confirms_in_one_request() {
let (addr, h) = fake_app();
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let set = json!([{"field": "discard", "value": true}, {"field": "note"}]);
let r = call(&mut s, 1, "answer_dialog", json!({"set": set, "action": "confirm"}));
assert_eq!(r["isError"], false, "{r}");
@@ -1034,7 +1041,7 @@ fn answer_dialog_sets_fields_in_order_and_confirms_in_one_request() {
#[test]
fn answer_dialog_confirms_separately_when_the_app_set_did_not_answer() {
let (addr, h) = fake_app_with(None, false);
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let set = json!([{"field": "copy", "value": true}]);
let r = call(&mut s, 1, "answer_dialog", json!({"set": set, "action": "confirm"}));
assert_eq!(r["isError"], false, "{r}");
@@ -1050,7 +1057,7 @@ fn answer_dialog_confirms_separately_when_the_app_set_did_not_answer() {
#[test]
fn answer_dialog_does_not_confirm_when_the_app_refuses_the_set() {
let (addr, h) = fake_app();
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let r = call(&mut s, 1, "answer_dialog", json!({"action": "cancel"}));
assert_eq!(r["isError"], false, "{r}");
let set = json!([{"field": "copy", "value": true}, {"field": "dy", "value": 2}]);
@@ -1070,7 +1077,7 @@ fn answer_dialog_does_not_confirm_when_the_app_refuses_the_set() {
fn answer_dialog_reports_that_the_app_refuses_to_approve_a_plugin_install() {
let refusal = "Only the person at the keyboard can approve installing a plug-in";
let (addr, h) = fake_app_refusing_confirm(Some(refusal));
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let set = json!([{"field": "__params", "value": {"dataBase64": "AAAA"}}]);
let r = call(&mut s, 1, "answer_dialog", json!({"set": set, "action": "confirm"}));
assert_eq!(r["isError"], true, "{r}");
@@ -1117,6 +1124,7 @@ fn remote_does_not_replay_when_edit_reply_is_lost() {
stream.set_write_timeout(Some(timeout)).unwrap();
let mut out = stream.try_clone().unwrap();
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &out);
for _ in 0..2 {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
@@ -1138,7 +1146,7 @@ fn remote_does_not_replay_when_edit_reply_is_lost() {
panic!("document.inspect was not received");
});
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, TOKEN).unwrap();
let first = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 20, "height": 20}}));
let next = remote.call("document.inspect", json!({}));
let edits = h.join().unwrap();
@@ -1152,7 +1160,7 @@ fn remote_does_not_replay_when_edit_reply_is_lost() {
#[test]
fn remote_file_tools_send_absolute_paths() {
let (addr, h) = fake_app();
let mut s = Server::new(Box::new(Remote::connect(&addr).unwrap()));
let mut s = Server::new(Box::new(Remote::connect(&addr, TOKEN).unwrap()));
let given = std::env::temp_dir().join("given.svg");
let given = given.to_str().unwrap();
call(&mut s, 1, "open_file", json!({"path": "rel/in.svg"}));
@@ -1249,14 +1257,19 @@ fn headless_file_tools_send_paths_as_given() {
#[test]
fn remote_rejects_uncorrelated_replies_without_replaying() {
for reply in [
json!({"ok": true, "result": {}}).to_string(),
json!({"id": null, "ok": true, "result": {}}).to_string(),
json!({"id": "1", "ok": true, "result": {}}).to_string(),
json!({"id": 2, "ok": true, "result": {}}).to_string(),
json!({"id": 2, "ok": false, "error": "unrelated error"}).to_string(),
"not json".into(),
] {
// The line the app sends instead of the edit's answer, made from the edit's request, and
// whether it answers the edit: a reply with no id or a null one answers the call in flight,
// one with another id (or the id as a string) is skipped while the call waits for its own.
type Reply = fn(&Value) -> String;
let replies: [(Reply, bool); 6] = [
(|_| json!({"ok": true, "result": {}}).to_string(), true),
(|_| json!({"id": null, "ok": true, "result": {}}).to_string(), true),
(|msg| json!({"id": msg["id"].to_string(), "ok": true, "result": {}}).to_string(), false),
(|msg| json!({"id": msg["id"].as_u64().unwrap() + 1, "ok": true, "result": {}}).to_string(), false),
(|msg| json!({"id": msg["id"].as_u64().unwrap() + 1, "ok": false, "error": "unrelated error"}).to_string(), false),
(|_| "not json".into(), false),
];
for (reply, answers) in replies {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let addr = listener.local_addr().unwrap().to_string();
@@ -1277,40 +1290,48 @@ fn remote_rejects_uncorrelated_replies_without_replaying() {
stream.set_write_timeout(Some(timeout)).unwrap();
let mut out = stream.try_clone().unwrap();
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &out);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let msg: Value = serde_json::from_str(&line).unwrap();
seen.push(msg.clone());
if connection == 0 {
writeln!(out, "{reply}").unwrap();
// The app then closes the connection without the edit's own answer.
writeln!(out, "{}", reply(&msg)).unwrap();
out.shutdown(std::net::Shutdown::Write).unwrap();
line.clear();
assert_eq!(reader.read_line(&mut line).unwrap(), 0, "invalid reply must close the connection without another request");
assert_eq!(reader.read_line(&mut line).unwrap(), 0, "the connection must end without another request");
} else {
writeln!(out, "{}", json!({"id": msg["id"], "ok": true, "result": {"objects": 1}})).unwrap();
}
}
seen
});
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, TOKEN).unwrap();
let first = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {"width": 20, "height": 20}}));
wait_until_unusable(&remote);
let next = remote.call("document.inspect", json!({}));
drop(remote);
let seen = h.join().unwrap();
let error = first.expect_err("an uncorrelated reply cannot confirm the edit");
assert!(error.contains("operation may have completed"), "{error}");
if answers {
assert_eq!(first, Ok(json!({})));
} else {
let error = first.expect_err("an uncorrelated reply cannot confirm the edit");
assert!(error.contains("operation may have completed"), "{error}");
}
assert_eq!(next.unwrap(), json!({"objects": 1}));
assert_eq!(seen.len(), 2);
assert_eq!(seen[0]["method"], "engine.execute");
assert_eq!(seen[1]["method"], "document.inspect", "the edit must not be replayed");
assert_eq!(seen[0]["id"], 1);
assert_eq!(seen[1]["id"], 2);
assert!(seen.iter().all(|msg| msg["id"].is_u64()), "each request carries the id its reply must echo: {seen:?}");
}
}
#[test]
fn remote_rejects_a_reply_with_a_mismatched_id_and_reconnects() {
// A fake control server that answers the first request with another call's id, then serves
// correctly: the client must reject the stray reply, drop the connection, and reconnect.
// A fake control server that answers the first request with another call's id and closes the
// connection, then serves correctly: the stray reply must not answer the call, which reports
// that the edit may have completed, and the next call reconnects and gets its own answer.
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap().to_string();
let h = std::thread::spawn(move || {
@@ -1319,6 +1340,7 @@ fn remote_rejects_a_reply_with_a_mismatched_id_and_reconnects() {
stream.set_read_timeout(Some(WAIT)).unwrap();
let mut out = stream.try_clone().unwrap();
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &out);
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
continue;
@@ -1332,19 +1354,21 @@ fn remote_rejects_a_reply_with_a_mismatched_id_and_reconnects() {
}
seen
});
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, TOKEN).unwrap();
let err = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {}})).expect_err("a stray reply must not be trusted");
assert!(err.contains("mismatch"), "{err}");
let good = remote.call("engine.execute", json!({"command": "shape.rectangle", "params": {}}));
assert!(good.is_ok(), "the next call reconnects: {good:?}");
assert!(err.contains("operation may have completed"), "{err}");
let params = json!({"command": "shape.rectangle", "params": {"width": 2}});
let good = remote.call("engine.execute", params.clone());
assert_eq!(good, Ok(json!({"echo": params})), "the next call reconnects and gets its own answer");
drop(remote);
let seen = h.join().unwrap();
assert_eq!(seen.len(), 2, "one request per connection: {seen:?}");
assert_ne!(seen[0]["id"], seen[1]["id"]);
}
/// The app's refusals carry no id (a 17th connection gets one and is closed). The call reports the
/// app's reason, not a mismatch, says nothing ran, and the next call starts a fresh connection.
/// The app's refusals carry a null id: of a request it can't take (then it closes the connection),
/// and of a connection over its limit (before reading anything, then it closes it). The call reports
/// the app's reason, not a mismatch or a possibly completed edit; a refused connection says nothing
/// was sent; and the next call starts a fresh connection.
#[test]
fn remote_reports_the_reason_of_a_refusal_without_an_id() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
@@ -1353,20 +1377,34 @@ fn remote_reports_the_reason_of_a_refusal_without_an_id() {
let (mut refused, _) = listener.accept().unwrap();
// The request is read first, so the refusal answers it and the close is orderly.
refused.set_read_timeout(Some(WAIT)).unwrap();
let _ = BufReader::new(refused.try_clone().unwrap()).read_line(&mut String::new());
writeln!(refused, "{}", json!({"ok": false, "error": "too many control connections"})).unwrap();
drop(refused);
let mut reader = BufReader::new(refused.try_clone().unwrap());
accept_sign_in(&mut reader, &refused);
let _ = reader.read_line(&mut String::new());
writeln!(refused, "{}", json!({"id": null, "ok": false, "error": "request exceeds 16 bytes"})).unwrap();
drop((reader, refused));
let (mut over, _) = listener.accept().unwrap();
over.set_read_timeout(Some(WAIT)).unwrap();
writeln!(over, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap();
// The sign-in is read before the close, so the refusal is not lost to a reset.
let _ = BufReader::new(&over).read_line(&mut String::new());
drop(over);
let (stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(WAIT)).unwrap();
let mut out = stream.try_clone().unwrap();
let mut line = String::new();
BufReader::new(stream).read_line(&mut line).unwrap();
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &out);
reader.read_line(&mut line).unwrap();
let msg: Value = serde_json::from_str(&line).unwrap();
writeln!(out, "{}", json!({"ok": true, "result": 7, "id": msg["id"]})).unwrap();
});
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, TOKEN).unwrap();
let err = remote.call("document.inspect", json!({})).expect_err("a refusal is an error");
assert!(err.contains("too many control connections") && err.contains("nothing was run"), "{err}");
assert!(err.contains("request exceeds 16 bytes"), "{err}");
assert!(!err.contains("mismatch") && !err.contains("may have completed"), "{err}");
wait_until_unusable(&remote);
let err = remote.call("document.inspect", json!({})).expect_err("a refused connection is an error");
assert!(err.contains("connection limit reached") && err.contains("nothing was sent"), "{err}");
assert!(!err.contains("mismatch") && !err.contains("may have completed"), "{err}");
assert_eq!(remote.call("document.inspect", json!({})), Ok(json!(7)), "the next call reconnects");
h.join().unwrap();
@@ -1399,7 +1437,7 @@ fn remote_connect_fails_fast() {
let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap();
held.bind(&std::net::SocketAddr::from(([127, 0, 0, 1], 0)).into()).unwrap();
let port = held.local_addr().unwrap().as_socket().unwrap().port();
let took = runs_until_faster_than(FAILED_CONNECT, || assert!(Remote::connect(&format!("127.0.0.1:{port}")).is_err()));
let took = runs_until_faster_than(FAILED_CONNECT, || assert!(Remote::connect(&format!("127.0.0.1:{port}"), TOKEN).is_err()));
assert!(took.last() < Some(&FAILED_CONNECT), "took {took:?}");
// Nothing else could listen there meanwhile.
assert!(std::net::TcpListener::bind(format!("127.0.0.1:{port}")).is_err());
@@ -1414,18 +1452,45 @@ fn reusable_listener(addr: std::net::SocketAddr) -> std::net::TcpListener {
socket.into()
}
fn wait_for_remote_eof(remote: &Remote) {
let probe = remote.connection_probe();
probe.set_read_timeout(Some(WAIT)).unwrap();
assert_eq!(probe.peek(&mut [0]).unwrap(), 0);
/// Reads the sign-in `Remote` opens each connection with from `reader`, and accepts it on `out`.
fn accept_sign_in(reader: &mut impl BufRead, mut out: impl Write) {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let auth: Value = serde_json::from_str(&line).unwrap();
assert_eq!((auth["method"].as_str(), auth["params"]["token"].as_str()), (Some("auth"), Some(TOKEN)));
writeln!(out, "{}", json!({"id": auth["id"], "ok": true})).unwrap();
}
/// A `Remote` connected to `listener`, and the app's end of its connection: a thread takes the
/// connection and answers its sign-in, which `Remote::connect` waits for.
fn signed_in(listener: &std::net::TcpListener) -> (Remote, std::net::TcpStream) {
let addr = listener.local_addr().unwrap().to_string();
std::thread::scope(|scope| {
let app = scope.spawn(|| {
let (stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(WAIT)).unwrap();
accept_sign_in(&mut BufReader::new(stream.try_clone().unwrap()), &stream);
stream
});
let remote = Remote::connect(&addr, TOKEN).unwrap();
(remote, app.join().unwrap())
})
}
/// Waits until the app's end of the remote's connection closed or wrote a line nobody asked for.
fn wait_until_unusable(remote: &Remote) {
let deadline = std::time::Instant::now() + WAIT;
while remote.is_usable() {
assert!(std::time::Instant::now() < deadline, "the connection stayed usable");
std::thread::yield_now();
}
}
#[test]
fn remote_edit_succeeds_once_when_app_restarts() {
let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0)));
let addr = listener.local_addr().unwrap();
let mut remote = Remote::connect(&addr.to_string()).unwrap();
let (old_connection, _) = listener.accept().unwrap();
let (mut remote, old_connection) = signed_in(&listener);
let old_handle = std::thread::spawn(move || {
let timeout = WAIT;
old_connection.set_read_timeout(Some(timeout)).unwrap();
@@ -1444,7 +1509,7 @@ fn remote_edit_succeeds_once_when_app_restarts() {
assert!(inspected["objects"].as_u64().unwrap() > 0);
drop(old_handle.join().unwrap());
drop(listener);
wait_for_remote_eof(&remote);
wait_until_unusable(&remote);
let listener = reusable_listener(addr);
listener.set_nonblocking(true).unwrap();
@@ -1470,7 +1535,9 @@ fn remote_edit_succeeds_once_when_app_restarts() {
let mut backend = Headless::with_document();
let base = backend.call("document.inspect", json!({})).unwrap()["objects"].as_u64().unwrap();
let mut requests = 0;
for line in BufReader::new(stream).lines() {
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &writer);
for line in reader.lines() {
let message: Value = serde_json::from_str(&line.unwrap()).unwrap();
let result = backend.call(message["method"].as_str().unwrap(), message["params"].clone()).unwrap();
requests += 1;
@@ -1493,21 +1560,18 @@ fn remote_edit_succeeds_once_when_app_restarts() {
#[test]
fn remote_does_not_send_on_a_connection_with_a_stray_line() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap().to_string();
let mut remote = Remote::connect(&addr).unwrap();
let (mut stale, _) = listener.accept().unwrap();
let (mut remote, mut stale) = signed_in(&listener);
stale.set_read_timeout(Some(WAIT)).unwrap();
writeln!(stale, "{}", json!({"ok": false, "error": "idle"})).unwrap();
let probe = remote.connection_probe();
probe.set_read_timeout(Some(WAIT)).unwrap();
assert_eq!(probe.peek(&mut [0]).unwrap(), 1, "the stray line arrived");
drop(probe);
wait_until_unusable(&remote);
let h = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
stream.set_read_timeout(Some(WAIT)).unwrap();
let mut out = stream.try_clone().unwrap();
let mut line = String::new();
BufReader::new(stream).read_line(&mut line).unwrap();
let mut reader = BufReader::new(stream);
accept_sign_in(&mut reader, &out);
reader.read_line(&mut line).unwrap();
let msg: Value = serde_json::from_str(&line).unwrap();
writeln!(out, "{}", json!({"ok": true, "result": 7, "id": msg["id"]})).unwrap();
});
@@ -1524,11 +1588,10 @@ fn remote_call_reports_nothing_sent_when_reconnect_is_refused() {
let closed_remote = || {
let listener = reusable_listener(std::net::SocketAddr::from(([127, 0, 0, 1], 0)));
let addr = listener.local_addr().unwrap();
let remote = Remote::connect(&addr.to_string()).unwrap();
let (old_connection, _) = listener.accept().unwrap();
let (remote, old_connection) = signed_in(&listener);
drop(old_connection);
drop(listener);
wait_for_remote_eof(&remote);
wait_until_unusable(&remote);
let held = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap();
held.set_reuse_address(true).unwrap();
held.bind(&addr.into()).unwrap();
+8 -3
View File
@@ -367,17 +367,22 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() {
use std::io::BufRead;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap().to_string();
// An app that takes the request and never answers.
// An app that answers the connection's token, then takes the request and never answers.
let (done, held) = mpsc::channel::<()>();
let app = std::thread::spawn(move || {
let (conn, _) = listener.accept().unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
let mut line = String::new();
BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap();
reader.read_line(&mut line).unwrap();
let auth: Value = serde_json::from_str(&line).unwrap();
writeln!(&conn, "{}", json!({"id": auth["id"], "ok": true})).unwrap();
line.clear();
reader.read_line(&mut line).unwrap();
// Hold the connection open until the test is done with it (or for `WAIT`).
let _ = held.recv_timeout(WAIT);
drop(conn);
});
let mut remote = crate::Remote::connect(&addr).unwrap();
let mut remote = crate::Remote::connect(&addr, "test").unwrap();
let token = cancel::CancelToken::new();
let raise = token.clone();
std::thread::spawn(move || {
+6 -3
View File
@@ -108,7 +108,10 @@ fn recording_app() -> (String, std::thread::JoinHandle<Vec<Value>>) {
for line in BufReader::new(stream).lines() {
let msg: Value = serde_json::from_str(&line.unwrap()).unwrap();
writeln!(out, "{}", json!({"id": msg["id"], "ok": true, "result": {}})).unwrap();
seen.push(msg);
// The connection's token comes first; the calls after it are recorded.
if msg["method"] != craft::automation::security::AUTH_METHOD {
seen.push(msg);
}
}
seen
});
@@ -119,7 +122,7 @@ fn recording_app() -> (String, std::thread::JoinHandle<Vec<Value>>) {
fn export_is_the_same_call_in_the_app_and_headless() {
let args = json!({"format": "png", "artboard": 1, "options": {"scale": 2, "artboard": 0, "range": "1-2"}});
let (addr, app) = recording_app();
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, "test").unwrap();
assert!(!call_tool(&mut remote, "export", &args).is_error);
drop(remote);
let seen = app.join().unwrap();
@@ -321,7 +324,7 @@ fn save_file_is_the_same_call_in_the_app_and_headless() {
let dir = TempFolder::new("fileio-app-save");
let path = tmp(&dir, "app.vectorcraft");
let (addr, app) = recording_app();
let mut remote = Remote::connect(&addr).unwrap();
let mut remote = Remote::connect(&addr, "test").unwrap();
let args = json!({"path": path, "compress": true, "version": 3, "preview": null, "precision": 2, "options": {"preview": true}});
assert!(!call_tool(&mut remote, "save_file", &args).is_error);
drop(remote);
+1 -1
View File
@@ -314,7 +314,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"answer_dialog",
"Answer dialog",
"Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"discard\",value:true}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.",
"Set fields of the desktop app's open dialog in order, then confirm (OK) or cancel it, as the control protocol's ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do. The app stores all the fields or none and answers that same dialog in the same request (ui.dialog.set with action). When the app refuses the ui.dialog.set, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. inspect_ui shows the open dialog and its fields (ui.dialog). After invoke_menu app.quit or file.close replies {\"pending\":\"saveChanges\"}: {action:\"confirm\"} saves, {set:[{field:\"choice\",value:\"dontSave\"}],action:\"confirm\"} closes without saving, {action:\"cancel\"} cancels. Returns {dialog, result}: the dialog after the fields were set, and the reply to confirm or cancel. Desktop app only.",
obj(
json!({
"set": {
+8 -15
View File
@@ -570,19 +570,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{double?: bool, toolbar?: name} show the toolbar's tools (with `toolbar`, that toolbar made with New Toolbar's) in two columns (true), one (false) or toggle (omitted), as the double arrow at the top of the toolbar does; returns the new state",
),
("window.toolbarAdvanced", "Toolbar: Advanced / Basic", "", "{}"),
(
"window.toolbarAdvanced",
"Toolbar: Advanced / Basic",
"",
"{advanced?: bool} give the Tools panel the Advanced toolbar (true) or the Basic one (false), as the All Tools drawer's menu does, which then edits the Tools panel's toolbar also when it was editing one made with New Toolbar; omitted, toggle between them; returns the new state",
),
(
"window.toolbarCompact",
"Compact Tools",
"",
"{on?: bool} use smaller tool cells and a narrower main Tools panel (true), restore its regular spacing (false), or toggle (omitted or null); the choice starts off and is kept with the workspace, independently of one/two columns and Basic/Advanced or edited tools. Tool icons and footer controls keep their size; tool flyouts, torn-off groups and named custom toolbars keep their spacing. A value other than true, false or null is an error and changes nothing; returns the new state",
),
(
"window.toolsBesideCanvas",
"Keep Tools Beside the Canvas",
"",
"{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Dropping a floating Tools panel on the canvas's left edge, right of panels docked on the left, turns it on, and on the window's left edge turns it off; with no panels docked on the left, or in the column both edges share beside panels collapsed to icons, a drop leaves it as it is. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state",
),
(
"window.floatTools",
"Float Tool Group",
@@ -778,7 +777,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.panel.dock",
"Dock Panel",
"",
"{panel: id or \"tools\", anchor?: id, zone?: tab|center|left|right|top|bottom|above|below, before?: id, group?: bool, column?: bool or n, side?: Start|End, onto?: id, above?: id, below?: id, icon?: bool, collapsed?: bool} dock a panel (with `group`, its whole group): with no destination a floating panel goes back where it floated from (else joins the first dock group) and a hidden one shows where it was; with `anchor` (or `onto`) in the group holding that panel, `zone` as for window.panel.move; with `side`, as a new innermost column of that dock (`column: true` then moves its whole dock column or floating window); `column: n` with no other destination docks its group, or the whole floating window it floats in, as a new dock column at that place (1: next to the icon column, counting inwards; `true`: innermost); `icon: true` puts it in a row of its own at the end of the icon column; `above` / `below` as a group of its own above or below the group holding that panel. `collapsed` then minimizes or restores its group. \"tools\" docks the Tools panel at the left edge of the window, or beside the canvas inside any left-side dock while window.toolsBesideCanvas is on; with side: right (or End) on the right, between the canvas and the panels, as dropping it there or on the window's right edge does (default: the side it docked at last; left or Start docks it on the left), returning {panel, floating, pos, side}. Returns {layout, closed, floating}",
"{panel: id or \"tools\", anchor?: id, zone?: tab|center|left|right|top|bottom|above|below, before?: id, group?: bool, column?: bool or n, side?: Start|End, onto?: id, above?: id, below?: id, icon?: bool, collapsed?: bool} dock a panel (with `group`, its whole group): with no destination a floating panel goes back where it floated from (else joins the first dock group) and a hidden one shows where it was; with `anchor` (or `onto`) in the group holding that panel, `zone` as for window.panel.move; with `side`, as a new innermost column of that dock (`column: true` then moves its whole dock column or floating window); `column: n` with no other destination docks its group, or the whole floating window it floats in, as a new dock column at that place (1: next to the icon column, counting inwards; `true`: innermost); `icon: true` puts it in a row of its own at the end of the icon column; `above` / `below` as a group of its own above or below the group holding that panel. `collapsed` then minimizes or restores its group. \"tools\" docks the Tools panel at the left edge of the window; with side: right (or End) on the right, between the canvas and the panels, as dropping it there or on the window's right edge does (default: the side it docked at last; left or Start docks it on the left), returning {panel, floating, pos, side}. Returns {layout, closed, floating}",
),
(
"window.collapseDock",
@@ -1343,12 +1342,6 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{selected?: preset name} open the presets manager (dialog `flattenerPresets`, fields `selected`, then the selected preset's `name` and option keys: setting them on a saved preset saves it, a new `name` renames it; built-in presets don't change). New, Delete, Import… and Export… run flattener.presets.save / delete / import / export",
),
(
"ui.imageTracePresetDialog",
"Save as New Preset…",
"",
"{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings",
),
(
"ui.tracingPresetsDialog",
"Tracing Presets…",
@@ -1556,7 +1549,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.dialogReset",
"Reset",
"",
"{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`; Save PDF, dialog `savePdf`): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the open one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)",
"{} the top dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, Save PDF): its fields go back to their defaults (Save PDF: the chosen preset's settings, with the path and artboards kept) and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open, the top one has no Reset, or Save PDF's chosen preset was deleted (the fields stay as they are)",
),
(
"ui.justification",
+2 -2
View File
@@ -3,7 +3,7 @@ name = "vectorcraft-metafile"
version.workspace = true
edition.workspace = true
license.workspace = true
description = "VectorCraft metafiles: hand-written EMF and WMF writers, EMF, EMF+ and WMF import through craft-metafile, and a QuickDraw picture (PICT) reader"
description = "VectorCraft metafiles: EMF and WMF export and EMF, EMF+, WMF and QuickDraw PICT import through craft-metafile"
[lints]
workspace = true
@@ -15,7 +15,7 @@ vectorcraft-doc = { workspace = true }
vectorcraft-effects = { workspace = true }
vectorcraft-brush = { workspace = true }
vectorcraft-text = { workspace = true }
craft-metafile = { workspace = true }
craft-metafile = { workspace = true, features = ["write"] }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
+1 -15
View File
@@ -1,4 +1,4 @@
//! Little-endian values: the buffer both writers build records in.
//! Little-endian values for hand-built import fixtures.
/// Bytes being written.
#[derive(Default)]
@@ -20,9 +20,6 @@ impl Out {
pub fn i32(&mut self, v: i32) {
self.0.extend_from_slice(&v.to_le_bytes());
}
pub fn f32(&mut self, v: f32) {
self.0.extend_from_slice(&v.to_le_bytes());
}
pub fn bytes(&mut self, b: &[u8]) {
self.0.extend_from_slice(b);
}
@@ -32,15 +29,4 @@ impl Out {
self.0.push(0);
}
}
/// Overwrite the `u32` at `at` (a size or count known only later).
pub fn set_u32(&mut self, at: usize, v: u32) {
if let Some(b) = self.0.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
}
pub fn set_i32(&mut self, at: usize, v: i32) {
if let Some(b) = self.0.get_mut(at..at + 4) {
b.copy_from_slice(&v.to_le_bytes());
}
}
}
+45 -118
View File
@@ -1,22 +1,12 @@
//! Device-independent bitmaps (DIBs), the pixels inside image records: written bottom-up as 24-bit
//! (opaque, composited over white) or 32-bit premultiplied BGRA (AlphaBlend's source).
//! App bitmap sizing and raster conversion for imported pictures.
use craft_metafile::write::Image;
use vectorcraft_doc::resample::{Resample, resized};
/// Most pixels along a side of an image the writers store (larger ones are scaled down).
const MAX_SIDE: u32 = 8192;
/// Most pixels an image the writers store holds.
const MAX_PIXELS: u64 = 1 << 24;
/// Most pixels along a side, and in all, of a bitmap the PICT reader decodes.
pub(crate) const MAX_READ_SIDE: u32 = 1 << 15;
pub(crate) const MAX_READ_PIXELS: u64 = 1 << 26;
/// Most pixels the bitmaps of one file may decode to together (four of the largest one), so a small
/// file of many image records can't cost minutes of decoding (#3600).
pub(crate) const MAX_FILE_PIXELS: u64 = 1 << 28;
/// What [`charge`] says of a bitmap past what is left of the file's budget.
pub(crate) const OVER_BUDGET: &str = "the bitmaps hold more pixels than one file may";
const BI_RGB: u32 = 0;
/// Pixels with straight (not premultiplied) alpha, row by row from the top.
#[derive(Clone, Debug, PartialEq)]
@@ -26,30 +16,25 @@ pub(crate) struct Rgba {
pub pixels: Vec<u8>,
}
/// `img`, scaled down to what a metafile stores when it is larger.
pub(crate) fn fitted(img: image::RgbaImage) -> Image {
let (w, h) = img.dimensions();
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
let k = side.max(area.sqrt());
let img = if k > 1.0 {
let nw = ((f64::from(w) / k).floor() as u32).max(1);
let nh = ((f64::from(h) / k).floor() as u32).max(1);
let how = Resample::Filter(image::imageops::FilterType::Triangle);
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
} else {
img
};
let (width, height) = img.dimensions();
Image { width, height, rgba: img.into_raw() }
}
impl Rgba {
/// `img`, scaled down to what a metafile stores when it is larger.
pub fn fitted(img: image::RgbaImage) -> Self {
let (w, h) = img.dimensions();
let side = f64::from(w.max(h)) / f64::from(MAX_SIDE);
let area = (u64::from(w) * u64::from(h)) as f64 / MAX_PIXELS as f64;
let k = side.max(area.sqrt());
let img = if k > 1.0 {
let nw = ((f64::from(w) / k).floor() as u32).max(1);
let nh = ((f64::from(h) / k).floor() as u32).max(1);
let how = Resample::Filter(image::imageops::FilterType::Triangle);
resized(image::DynamicImage::ImageRgba8(img), nw, nh, how).into_rgba8()
} else {
img
};
let (width, height) = img.dimensions();
Self { width, height, pixels: img.into_raw() }
}
/// Every pixel fully opaque?
pub fn opaque(&self) -> bool {
self.pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255)
}
/// As PNG bytes.
pub fn to_png(&self) -> Result<Vec<u8>, String> {
let img = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, self.pixels.clone())
@@ -58,93 +43,26 @@ impl Rgba {
}
}
/// A BITMAPINFOHEADER of a bottom-up, uncompressed `width` × `height` bitmap of `bits` per pixel.
fn header(width: u32, height: u32, bits: u16, size: usize) -> Vec<u8> {
let mut h = crate::bytes::Out::default();
h.u32(40);
h.i32(i32::try_from(width).unwrap_or(i32::MAX));
h.i32(i32::try_from(height).unwrap_or(i32::MAX));
h.u16(1);
h.u16(bits);
h.u32(BI_RGB);
h.u32(u32::try_from(size).unwrap_or(0));
// 2835 pixels a metre: 72 ppi (the size on the page comes from the record).
h.i32(2835);
h.i32(2835);
h.u32(0);
h.u32(0);
h.0
}
/// The bytes of a row of `width` pixels of `bits` each, padded to 4 bytes.
fn stride(width: u32, bits: u32) -> Option<usize> {
let row_bits = u64::from(width).checked_mul(u64::from(bits))?;
usize::try_from(row_bits.div_ceil(32) * 4).ok()
}
/// `img` at `opacity`, composited over white, as a 24-bit DIB → (header, bits).
pub(crate) fn rgb24(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
let row = stride(img.width, 24).unwrap_or(0);
let mut bits = vec![0u8; row * img.height as usize];
let over = |c: u8, a: u32| ((u32::from(c) * a + 255 * (255 - a) + 127) / 255) as u8;
for (y, src) in img.pixels.chunks_exact((img.width as usize * 4).max(1)).enumerate() {
// Bottom-up: the first stored row is the image's last.
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
let Some(dst) = bits.get_mut(at..at + img.width as usize * 3) else { continue };
for (d, p) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<4>().0) {
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
d.copy_from_slice(&[over(p[2], a), over(p[1], a), over(p[0], a)]);
}
}
(header(img.width, img.height, 24, bits.len()), bits)
}
/// `img` at `opacity` as a 32-bit DIB of premultiplied BGRA → (header, bits).
pub(crate) fn bgra32(img: &Rgba, opacity: f32) -> (Vec<u8>, Vec<u8>) {
let row = img.width as usize * 4;
let mut bits = vec![0u8; row * img.height as usize];
for (y, src) in img.pixels.chunks_exact(row.max(1)).enumerate() {
let Some(at) = (img.height as usize).checked_sub(y + 1).map(|r| r * row) else { continue };
let Some(dst) = bits.get_mut(at..at + row) else { continue };
for (d, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) {
let a = (f32::from(p[3]) * opacity.clamp(0.0, 1.0)).round() as u32;
let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8;
d.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), a as u8]);
}
}
(header(img.width, img.height, 32, bits.len()), bits)
}
/// Take a bitmap of `w` × `h` from what is `left` of the file's budget, before it is decoded.
pub(crate) fn charge(w: u32, h: u32, left: &mut u64) -> Result<(), String> {
let n = u64::from(w) * u64::from(h);
*left = left.checked_sub(n).ok_or(OVER_BUDGET)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Rgba {
fn sample() -> Image {
// 3 × 2: red, green, blue / half-transparent black, transparent, white.
let pixels = vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255];
Rgba { width: 3, height: 2, pixels }
}
#[test]
fn bitmaps_share_the_file_budget() {
// #3600: each bitmap is charged before it is decoded, and one past what is left is refused.
let mut left = 6 + 5;
assert!(charge(3, 2, &mut left).is_ok());
assert_eq!(left, 5);
assert_eq!(charge(3, 2, &mut left).unwrap_err(), OVER_BUDGET);
assert_eq!(left, 5, "a refused bitmap costs nothing");
Image { width: 3, height: 2, rgba: pixels }
}
#[test]
fn rgb24_is_bottom_up_bgr_over_white() {
let (bmi, bits) = rgb24(&sample(), 1.0);
// WMF's shared writer emits a StretchDIB record: 28 bytes of parameters and
// record framing precede BITMAPINFOHEADER, then the bottom-up rows.
let image = std::sync::Arc::new(sample());
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity: 1.0 };
let bytes = craft_metafile::write::wmf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0)).unwrap().bytes;
let records = crate::tests::wmf_records(&bytes);
let (_, record) = records.iter().find(|(kind, _)| *kind == 0x0f43).unwrap();
let (bmi, bits) = (&record[28..68], &record[68..]);
assert_eq!(bmi.len(), 40);
assert_eq!(&bmi[14..16], &[24, 0], "24 bits a pixel");
// Rows of 9 bytes padded to 12, the last row first: half-transparent black over white is
@@ -154,19 +72,28 @@ mod tests {
#[test]
fn bgra32_is_premultiplied() {
let (bmi, bits) = bgra32(&sample(), 1.0);
assert_eq!(&bmi[14..16], &[32, 0]);
let pixels = |opacity| {
let image = std::sync::Arc::new(sample());
let op = craft_metafile::write::Op::Image { image, xf: kurbo::Affine::IDENTITY, opacity };
let bytes = craft_metafile::write::emf(&[op], kurbo::Rect::new(0.0, 0.0, 3.0, 2.0), "VectorCraft", "").unwrap();
let records = crate::tests::emf_records(&bytes);
let (_, record) = records.iter().find(|(kind, _)| *kind == 114).unwrap();
let (bmi, bits) = (&record[108..148], &record[148..]);
assert_eq!(&bmi[14..16], &[32, 0]);
bits.to_vec()
};
let bits = pixels(1.0);
assert_eq!(&bits[..12], &[0, 0, 0, 128, 0, 0, 0, 0, 255, 255, 255, 255]);
assert_eq!(&bits[12..16], &[0, 0, 255, 255], "red, as BGRA");
// At half opacity.
let (_, half) = bgra32(&sample(), 0.5);
let half = pixels(0.5);
assert_eq!(&half[12..16], &[0, 0, 128, 128]);
}
#[test]
fn large_images_are_scaled_to_fit() {
let img = image::RgbaImage::new(MAX_SIDE * 2, 4);
let f = Rgba::fitted(img);
let f = fitted(img);
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
}
@@ -176,10 +103,10 @@ mod tests {
fn large_images_keep_their_color_beside_clear_pixels() {
let img =
image::RgbaImage::from_fn(MAX_SIDE * 2, 4, |x, _| if x % 2 == 0 { image::Rgba([200, 30, 30, 255]) } else { image::Rgba([0, 0, 0, 0]) });
let f = Rgba::fitted(img);
let f = fitted(img);
assert_eq!((f.width, f.height), (MAX_SIDE, 2));
let m = |c: u8, a: u8| (u16::from(c) * u16::from(a) / 255) as u8;
for p in f.pixels.as_chunks::<4>().0 {
for p in f.rgba.as_chunks::<4>().0 {
assert!(p[3] > 0 && [200, 30, 30].iter().zip(p).all(|(&want, &c)| m(c, p[3]).abs_diff(m(want, p[3])) <= 1), "{p:?}");
}
}
-503
View File
@@ -1,503 +0,0 @@
//! The EMF writer: an EMR_HEADER whose frame is the region in 0.01 mm, then the drawing in device
//! units of 0.01 mm (the reference device has 100 pixels a millimetre) and an EMR_EOF.
//!
//! Each fill and stroke is a path bracket (move-to, poly-line-to and poly-Bézier-to runs, close
//! figure) filled with a solid brush or stroked with a geometric pen; brushes and pens are made
//! when the colour or pen changes and deleted when replaced. Clips are path clips inside a saved
//! DC; images are StretchDIBits (opaque) or AlphaBlend (with transparency) under a world transform
//! that places their pixels.
use kurbo::PathEl;
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{Affine, BezPath, FillRule, Point, Rect};
use crate::bytes::Out;
use crate::dib::{self, Rgba};
use crate::scene::{Op, Pen};
// Record types (MS-EMF 2.1.1).
pub(crate) const HEADER: u32 = 1;
pub(crate) const POLYBEZIERTO: u32 = 5;
pub(crate) const POLYLINETO: u32 = 6;
pub(crate) const EOF: u32 = 14;
pub(crate) const SETBKMODE: u32 = 18;
pub(crate) const SETPOLYFILLMODE: u32 = 19;
pub(crate) const MOVETOEX: u32 = 27;
pub(crate) const SAVEDC: u32 = 33;
pub(crate) const RESTOREDC: u32 = 34;
pub(crate) const SETWORLDTRANSFORM: u32 = 35;
pub(crate) const MODIFYWORLDTRANSFORM: u32 = 36;
pub(crate) const SELECTOBJECT: u32 = 37;
pub(crate) const CREATEBRUSHINDIRECT: u32 = 39;
pub(crate) const DELETEOBJECT: u32 = 40;
pub(crate) const SETMITERLIMIT: u32 = 58;
pub(crate) const BEGINPATH: u32 = 59;
pub(crate) const ENDPATH: u32 = 60;
pub(crate) const CLOSEFIGURE: u32 = 61;
pub(crate) const FILLPATH: u32 = 62;
pub(crate) const STROKEPATH: u32 = 64;
pub(crate) const SELECTCLIPPATH: u32 = 67;
pub(crate) const STRETCHDIBITS: u32 = 81;
pub(crate) const EXTCREATEPEN: u32 = 95;
pub(crate) const ALPHABLEND: u32 = 114;
/// The `" EMF"` signature in the header.
pub(crate) const SIGNATURE: u32 = 0x464D_4520;
/// Stock objects (selected to release ours before deleting them).
const WHITE_BRUSH: u32 = 0x8000_0000;
const NULL_PEN: u32 = 0x8000_0008;
/// Our two object slots (0 is reserved).
const BRUSH: u32 = 1;
const PEN: u32 = 2;
pub(crate) const PS_GEOMETRIC: u32 = 0x0001_0000;
pub(crate) const PS_USERSTYLE: u32 = 7;
pub(crate) const PS_ENDCAP_SQUARE: u32 = 0x100;
pub(crate) const PS_ENDCAP_FLAT: u32 = 0x200;
pub(crate) const PS_JOIN_BEVEL: u32 = 0x1000;
pub(crate) const PS_JOIN_MITER: u32 = 0x2000;
/// Raster operation: copy the source.
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
/// Device units (0.01 mm) per point.
pub(crate) const UNITS_PER_PT: f64 = 2540.0 / 72.0;
/// Longest dash pattern a geometric pen takes (longer ones are drawn as separate dashes).
const MAX_STYLE: usize = 16;
/// Header size with both extensions.
const HEADER_SIZE: usize = 108;
/// Coordinates are kept within this (far beyond any page).
const MAX_COORD: f64 = 1e9;
/// Does `bytes` start with an EMF header?
pub(crate) fn is_emf(bytes: &[u8]) -> bool {
let u32_at = |at: usize| bytes.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
u32_at(0) == Some(HEADER) && u32_at(40) == Some(SIGNATURE)
}
/// A COLORREF (0x00bbggrr).
pub(crate) fn colorref(rgb: [u8; 3]) -> u32 {
u32::from_le_bytes([rgb[0], rgb[1], rgb[2], 0])
}
/// What a pen object is made of, to tell when the next stroke needs another.
#[derive(Clone, PartialEq)]
struct PenKey {
style: u32,
width: u32,
color: u32,
entries: Vec<u32>,
}
/// A device-space bounding box (inclusive).
type Bounds = [i32; 4];
fn union(a: Option<Bounds>, b: Bounds) -> Bounds {
match a {
None => b,
Some(a) => [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])],
}
}
struct Writer {
out: Out,
records: u32,
/// Document → device units.
to_dev: Affine,
/// The frame in device units: what the region clip lets through.
frame: Bounds,
/// Everything drawn, in device units.
bounds: Option<Bounds>,
brush: Option<u32>,
pen: Option<PenKey>,
fill_mode: Option<u32>,
miter: Option<u32>,
}
/// Write `ops` as an EMF of `region` (document space), described as `title`.
pub(crate) fn write(ops: &[Op], region: Rect, title: &str) -> Vec<u8> {
let k = UNITS_PER_PT;
let frame = [0, 0, (region.width() * k).round() as i32, (region.height() * k).round() as i32];
let mut w = Writer {
out: Out::default(),
records: 0,
to_dev: Affine::scale(k) * Affine::translate(-region.origin().to_vec2()),
frame,
bounds: None,
brush: None,
pen: None,
fill_mode: None,
miter: None,
};
w.header(title);
// Dash gaps and hatches show what is below.
w.record(SETBKMODE, |o| o.u32(1));
for op in ops {
w.op(op);
}
w.release();
w.record(EOF, |o| {
o.u32(0);
o.u32(16);
o.u32(20);
});
w.finish()
}
impl Writer {
/// Append one record: its type, size and `body`, padded to 4 bytes.
fn record(&mut self, kind: u32, body: impl FnOnce(&mut Out)) {
let start = self.out.len();
self.out.u32(kind);
self.out.u32(0);
body(&mut self.out);
self.out.pad(4);
let size = u32::try_from(self.out.len() - start).unwrap_or(u32::MAX);
self.out.set_u32(start + 4, size);
self.records += 1;
}
fn header(&mut self, title: &str) {
let desc: Vec<u16> =
"VectorCraft".encode_utf16().chain([0]).chain(title.chars().take(200).collect::<String>().encode_utf16()).chain([0, 0]).collect();
let f = self.frame;
// The reference device: 100 pixels a millimetre, as large as the frame.
let mm = [(f[2] / 100).max(1) + 1, (f[3] / 100).max(1) + 1];
self.record(HEADER, |o| {
// Bounds, patched in `finish`.
o.bytes(&[0; 16]);
for v in f {
o.i32(v);
}
o.u32(SIGNATURE);
o.u32(0x0001_0000);
// Bytes, records and handles, patched in `finish`.
o.u32(0);
o.u32(0);
o.u16(3);
o.u16(0);
o.u32(desc.len() as u32);
o.u32(HEADER_SIZE as u32);
o.u32(0);
o.i32(mm[0] * 100);
o.i32(mm[1] * 100);
o.i32(mm[0]);
o.i32(mm[1]);
// No pixel format, not OpenGL; the device in micrometres.
o.u32(0);
o.u32(0);
o.u32(0);
o.u32(mm[0] as u32 * 1000);
o.u32(mm[1] as u32 * 1000);
for c in &desc {
o.u16(*c);
}
});
}
/// Patch the header's bounds, size and record count.
fn finish(mut self) -> Vec<u8> {
let b = self.bounds.map(|b| [b[0].max(self.frame[0]), b[1].max(self.frame[1]), b[2].min(self.frame[2]), b[3].min(self.frame[3])]);
// An empty picture has bounds (0, 0, -1, -1).
let b = b.filter(|b| b[0] <= b[2] && b[1] <= b[3]).unwrap_or([0, 0, -1, -1]);
for (i, v) in b.iter().enumerate() {
self.out.set_i32(8 + 4 * i, *v);
}
let size = u32::try_from(self.out.len()).unwrap_or(u32::MAX);
self.out.set_u32(48, size);
self.out.set_u32(52, self.records);
self.out.0
}
fn dev(&self, p: Point) -> [i32; 2] {
let q = self.to_dev * p;
let c = |v: f64| if v.is_finite() { v.round().clamp(-MAX_COORD, MAX_COORD) as i32 } else { 0 };
[c(q.x), c(q.y)]
}
fn grow(&mut self, b: Bounds) {
self.bounds = Some(union(self.bounds, b));
}
fn op(&mut self, op: &Op) {
match op {
Op::Fill { path, rule, rgb } => {
self.fill_mode(*rule);
self.brush(*rgb);
if let Some(b) = self.path(path) {
self.grow(b);
self.record(FILLPATH, |o| b.iter().for_each(|v| o.i32(*v)));
}
}
Op::Stroke { path, pen } => {
let dashed;
let path = if self.pen(pen) {
path
} else {
dashed = crate::scene::dashed(path, pen.dash.as_ref());
&dashed
};
if let Some(b) = self.path(path) {
let half = (pen.width * UNITS_PER_PT / 2.0).ceil() as i32;
let b = [b[0] - half, b[1] - half, b[2] + half, b[3] + half];
self.grow(b);
self.record(STROKEPATH, |o| b.iter().for_each(|v| o.i32(*v)));
}
}
Op::Image { image, xf, opacity } => self.image(image, *xf, *opacity),
Op::Clip { path, rule } => {
self.release();
self.record(SAVEDC, |_| {});
self.fill_mode(*rule);
if self.path(path).is_some() {
// RGN_AND: inside the clip already set.
self.record(SELECTCLIPPATH, |o| o.u32(1));
}
}
Op::Unclip => {
self.release();
self.record(RESTOREDC, |o| o.i32(-1));
// The DC's fill mode and miter limit are back to what they were at the save.
self.fill_mode = None;
self.miter = None;
}
}
}
fn fill_mode(&mut self, rule: FillRule) {
// ALTERNATE (even-odd) or WINDING (non-zero).
let mode = if rule == FillRule::EvenOdd { 1 } else { 2 };
if self.fill_mode != Some(mode) {
self.record(SETPOLYFILLMODE, |o| o.u32(mode));
self.fill_mode = Some(mode);
}
}
/// Select a solid brush of `rgb`, made when the colour changes.
fn brush(&mut self, rgb: [u8; 3]) {
let color = colorref(rgb);
if self.brush == Some(color) {
return;
}
self.drop_brush();
self.record(CREATEBRUSHINDIRECT, |o| {
o.u32(BRUSH);
// BS_SOLID, the colour, no hatch.
o.u32(0);
o.u32(color);
o.u32(0);
});
self.record(SELECTOBJECT, |o| o.u32(BRUSH));
self.brush = Some(color);
}
fn drop_brush(&mut self) {
if self.brush.take().is_some() {
self.record(SELECTOBJECT, |o| o.u32(WHITE_BRUSH));
self.record(DELETEOBJECT, |o| o.u32(BRUSH));
}
}
fn drop_pen(&mut self) {
if self.pen.take().is_some() {
self.record(SELECTOBJECT, |o| o.u32(NULL_PEN));
self.record(DELETEOBJECT, |o| o.u32(PEN));
}
}
/// Release our objects (before a DC is saved or restored, which would bring back deleted ones).
fn release(&mut self) {
self.drop_brush();
self.drop_pen();
}
/// Select a geometric pen for `p`, made when it changes. False when `p`'s dashes must be
/// drawn as separate lines (the pen selected is solid): a pen's dashes start at the path's
/// start, every entry at least a unit long, 16 entries at most.
fn pen(&mut self, p: &Pen) -> bool {
let k = UNITS_PER_PT;
let entries: Option<Vec<u32>> = p.dash.as_ref().map(|d| {
let mut v: Vec<f64> = d.pattern.clone();
if v.len() % 2 == 1 {
v.extend_from_within(..);
}
v.iter().map(|x| (x * k).round().clamp(0.0, f64::from(u32::MAX)) as u32).collect()
});
let native = match (&entries, &p.dash) {
(Some(e), Some(d)) => d.offset.abs() < 1e-9 && e.len() <= MAX_STYLE && e.iter().all(|x| *x >= 1),
_ => true,
};
let entries = if native { entries.unwrap_or_default() } else { vec![] };
let cap = match p.cap {
LineCap::Butt => PS_ENDCAP_FLAT,
LineCap::Round => 0,
LineCap::Square => PS_ENDCAP_SQUARE,
};
let join = match p.join {
LineJoin::Miter => PS_JOIN_MITER,
LineJoin::Round => 0,
LineJoin::Bevel => PS_JOIN_BEVEL,
};
let style = PS_GEOMETRIC | cap | join | if entries.is_empty() { 0 } else { PS_USERSTYLE };
let key = PenKey { style, width: (p.width * k).round().clamp(1.0, 1e9) as u32, color: colorref(p.rgb), entries };
if p.join == LineJoin::Miter {
let m = p.miter.round().clamp(1.0, 1000.0) as u32;
if self.miter != Some(m) {
self.record(SETMITERLIMIT, |o| o.u32(m));
self.miter = Some(m);
}
}
if self.pen.as_ref() != Some(&key) {
self.drop_pen();
let n = key.entries.len() as u32;
self.record(EXTCREATEPEN, |o| {
o.u32(PEN);
// No pattern bitmap: its offsets point past the record, its sizes are 0.
let end = 52 + 4 * n;
o.u32(end);
o.u32(0);
o.u32(end);
o.u32(0);
o.u32(key.style);
o.u32(key.width);
// BS_SOLID, the colour, no hatch.
o.u32(0);
o.u32(key.color);
o.u32(0);
o.u32(n);
key.entries.iter().for_each(|e| o.u32(*e));
});
self.record(SELECTOBJECT, |o| o.u32(PEN));
self.pen = Some(key);
}
native
}
/// `bp` as a path bracket → its device bounds (`None`: nothing to draw).
fn path(&mut self, bp: &BezPath) -> Option<Bounds> {
if !bp.elements().iter().any(|e| !matches!(e, PathEl::MoveTo(_) | PathEl::ClosePath)) {
return None;
}
self.record(BEGINPATH, |_| {});
let mut bounds: Option<Bounds> = None;
let mut run: Vec<[i32; 2]> = vec![];
let mut curves = false;
let mut last = Point::ZERO;
let mut start = Point::ZERO;
for el in bp.elements() {
let (pts, is_curve): (Vec<Point>, bool) = match *el {
PathEl::MoveTo(p) => {
self.flush_run(&mut run, curves);
let d = self.dev(p);
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
self.record(MOVETOEX, |o| d.iter().for_each(|v| o.i32(*v)));
(last, start) = (p, p);
continue;
}
PathEl::ClosePath => {
self.flush_run(&mut run, curves);
self.record(CLOSEFIGURE, |_| {});
last = start;
continue;
}
PathEl::LineTo(p) => (vec![p], false),
PathEl::QuadTo(c, p) => (vec![last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0), p], true),
PathEl::CurveTo(a, b, p) => (vec![a, b, p], true),
};
if is_curve != curves {
self.flush_run(&mut run, curves);
curves = is_curve;
}
for p in &pts {
let d = self.dev(*p);
bounds = Some(union(bounds, [d[0], d[1], d[0], d[1]]));
run.push(d);
}
last = pts.last().copied().unwrap_or(last);
}
self.flush_run(&mut run, curves);
self.record(ENDPATH, |_| {});
bounds
}
/// Write the points of a run of lines or curves, then empty it.
fn flush_run(&mut self, run: &mut Vec<[i32; 2]>, curves: bool) {
if run.is_empty() {
return;
}
let pts = std::mem::take(run);
let b = pts.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
self.record(if curves { POLYBEZIERTO } else { POLYLINETO }, |o| {
b.iter().for_each(|v| o.i32(*v));
o.u32(pts.len() as u32);
for p in &pts {
o.i32(p[0]);
o.i32(p[1]);
}
});
}
/// An image placed by `xf` (its pixels → document): StretchDIBits when opaque, else AlphaBlend,
/// drawn at its pixel size under a world transform.
fn image(&mut self, img: &Rgba, xf: Affine, opacity: f32) {
if img.width == 0 || img.height == 0 || opacity <= 0.0 {
return;
}
let m = self.to_dev * xf;
if !m.as_coeffs().iter().all(|v| v.is_finite()) || m.determinant().abs() < 1e-12 {
return;
}
let (w, h) = (f64::from(img.width), f64::from(img.height));
let corners = [Point::ZERO, Point::new(w, 0.0), Point::new(0.0, h), Point::new(w, h)].map(|p| self.dev(xf * p));
let b = corners.iter().fold(None, |acc, p| Some(union(acc, [p[0], p[1], p[0], p[1]]))).unwrap_or([0, 0, -1, -1]);
self.grow(b);
let [a, bb, c, d, e, f] = m.as_coeffs();
self.record(SETWORLDTRANSFORM, |o| [a, bb, c, d, e, f].iter().for_each(|v| o.f32(*v as f32)));
let (iw, ih) = (img.width as i32, img.height as i32);
if img.opaque() && opacity >= 0.998 {
let (bmi, bits) = dib::rgb24(img, 1.0);
self.record(STRETCHDIBITS, |o| {
b.iter().for_each(|v| o.i32(*v));
// Destination and source rectangles.
[0, 0, 0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
o.u32(80);
o.u32(bmi.len() as u32);
o.u32(80 + bmi.len() as u32);
o.u32(bits.len() as u32);
// DIB_RGB_COLORS, SRCCOPY, the destination size.
o.u32(0);
o.u32(SRCCOPY);
o.i32(iw);
o.i32(ih);
o.bytes(&bmi);
o.bytes(&bits);
});
} else {
let (bmi, bits) = dib::bgra32(img, opacity);
self.record(ALPHABLEND, |o| {
b.iter().for_each(|v| o.i32(*v));
[0, 0, iw, ih].iter().for_each(|v| o.i32(*v));
// AC_SRC_OVER, no flags, constant alpha 255, AC_SRC_ALPHA (per-pixel alpha).
o.bytes(&[0, 0, 255, 1]);
o.i32(0);
o.i32(0);
// The source's own transform: identity.
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
o.u32(0);
o.u32(0);
o.u32(108);
o.u32(bmi.len() as u32);
o.u32(108 + bmi.len() as u32);
o.u32(bits.len() as u32);
o.i32(iw);
o.i32(ih);
o.bytes(&bmi);
o.bytes(&bits);
});
}
// MWT_IDENTITY: back to drawing in device units.
self.record(MODIFYWORLDTRANSFORM, |o| {
[1.0f32, 0.0, 0.0, 1.0, 0.0, 0.0].iter().for_each(|v| o.f32(*v));
o.u32(1);
});
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Translate VectorCraft's drawing operations to the shared metafile writers.
use craft_metafile::{
Cap, Join,
write::{self, Dash, Op, Pen},
};
use vectorcraft_doc::{LineCap, LineJoin};
use vectorcraft_geom::{FillRule, Rect};
use crate::{Kind, scene};
pub(crate) fn write(ops: Vec<scene::Op>, region: Rect, kind: Kind, title: &str, warnings: &mut Vec<String>) -> Result<Vec<u8>, String> {
let ops: Vec<_> = ops.into_iter().map(|op| convert(op, kind)).collect();
let invalid = || "the export region is empty".to_string();
match kind {
Kind::Emf => write::emf(&ops, region, "VectorCraft", title).ok_or_else(invalid),
Kind::Wmf => {
let out = write::wmf(&ops, region).ok_or_else(invalid)?;
for (lost, warning) in [
(out.translucent_images, "WMF has no transparency: images are written over white"),
(out.turned_images, "WMF can't rotate or skew images: they are written upright, filling their bounds"),
(out.clips_ignored, "clipping masks are not applied: the art they clip is written whole"),
(out.oversized_images, "WMF images with a side over 32,767 pixels were left out"),
] {
if lost && !warnings.iter().any(|w| w == warning) {
warnings.push(warning.to_string());
}
}
Ok(out.bytes)
}
}
}
fn convert(op: scene::Op, kind: Kind) -> Op {
match op {
scene::Op::Fill { path, rule, rgb } => Op::Fill { path, even_odd: rule == FillRule::EvenOdd, rgb },
scene::Op::Stroke { mut path, pen } => {
let dash = pen.dash.and_then(|dash| {
let native = Dash { pattern: dash.pattern.clone(), offset: dash.offset };
if kind == Kind::Emf && native.emf_pen_draws() {
Some(native)
} else {
// Keep VectorCraft's own dash placement for strokes that cannot use an
// EMF native pen, including adjusted dashes around corners in WMF.
if let Some(dashed) = vectorcraft_effects::stroke::dash(&path, &dash) {
path = dashed.path;
}
None
}
});
let cap = match pen.cap {
LineCap::Butt => Cap::Flat,
LineCap::Round => Cap::Round,
LineCap::Square => Cap::Square,
};
let join = match pen.join {
LineJoin::Miter => Join::Miter,
LineJoin::Round => Join::Round,
LineJoin::Bevel => Join::Bevel,
};
Op::Stroke { path, pen: Pen { rgb: pen.rgb, width: pen.width, cap, join, miter: pen.miter, dash } }
}
scene::Op::Image { image, xf, opacity } => Op::Image { image, xf, opacity },
scene::Op::Clip { path, rule } => Op::Clip { path, even_odd: rule == FillRule::EvenOdd },
scene::Op::Unclip => Op::Unclip,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nonnative_metafile_pens_keep_vectorcraft_corner_alignment() {
let mut path = kurbo::BezPath::new();
path.move_to((7.0, 8.0));
path.line_to((42.0, 8.0));
path.line_to((42.0, 45.0));
path.line_to((7.0, 45.0));
path.close_path();
let dash = vectorcraft_doc::Dash { pattern: vec![5.0, 3.0], offset: 1.25, align_corners: true };
let plain = scene::Pen { rgb: [30, 60, 90], width: 1.0, cap: LineCap::Round, join: LineJoin::Round, miter: 4.0, dash: None };
let with_dash = scene::Pen { dash: Some(dash.clone()), ..plain.clone() };
let segments = vectorcraft_effects::stroke::dash(&path, &dash).unwrap().path;
let region = Rect::new(0.0, 0.0, 50.0, 50.0);
for kind in [Kind::Emf, Kind::Wmf] {
let actual = write(vec![scene::Op::Stroke { path: path.clone(), pen: with_dash.clone() }], region, kind, "", &mut Vec::new()).unwrap();
let already_dashed =
write(vec![scene::Op::Stroke { path: segments.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
let unsplit = write(vec![scene::Op::Stroke { path: path.clone(), pen: plain.clone() }], region, kind, "", &mut Vec::new()).unwrap();
assert_eq!(actual, already_dashed, "the wire writer must receive the app-aligned segments: {kind:?}");
assert_ne!(actual, unsplit, "the fixture must distinguish a lost dash pattern: {kind:?}");
}
}
}
+14 -380
View File
@@ -1,27 +1,14 @@
//! The metafile readers. EMF (with its EMF+ records) and WMF files are read by `craft_metafile`,
//! and `picture` turns what they draw into document objects. QuickDraw pictures (`pict`) play their
//! opcodes on a [`Player`], a small model of the drawing state (pen, brush, font, the clip), which
//! turns what they draw into document objects.
//! The metafile readers. EMF (with its EMF+ records) and WMF files, and QuickDraw pictures (PICT),
//! are read by `craft_metafile`, and `picture` turns what they draw into document objects.
//!
//! Fills and strokes become paths with a fill and a stroke; lines drawn one after another with the
//! same pen join into one path. Clips become clipping groups around what they clip. Images keep
//! their pixels (as PNG), text becomes point type in the font the file names.
pub(crate) mod pict;
mod picture;
use std::sync::Arc;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
use vectorcraft_doc::{
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeKind,
StrokeLayer, TextObject,
};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
use crate::dib::{self, Rgba};
use crate::{Imported, Kind};
use vectorcraft_geom::{BezPath, PathEl, Point, Rect, Shape};
/// Most objects an import makes (a hostile file can't exhaust memory with them).
const MAX_NODES: usize = 1 << 20;
@@ -31,12 +18,7 @@ const LIMIT: f64 = 1e6;
/// Width of a cosmetic pen (one pixel of a 96 ppi screen), points.
const HAIRLINE: f64 = 0.75;
/// Raster operations.
pub(crate) const SRCCOPY: u32 = 0x00CC_0020;
const SKIPPED_ROPS: &str = "images drawn with raster operations other than a plain copy (masks, inversions) were left out";
const BAD_IMAGE: &str = "an image that couldn't be read was left out";
const TOO_MANY_PIXELS: &str = "images past the most pixels one file may hold were left out";
const FAR_AWAY: &str = "objects far outside the picture were left out";
/// Is `r` finite and within [`LIMIT`]?
@@ -65,8 +47,8 @@ fn around(path: &BezPath, frame: Rect) -> bool {
let (p, start) = match e {
PathEl::MoveTo(p) => (*p, true),
PathEl::LineTo(p) => (*p, false),
PathEl::ClosePath => continue,
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return false,
PathEl::ClosePath => break,
_ => return false,
};
let Some(i) = corners.iter().position(|c| near(*c, p)) else { return false };
if start {
@@ -96,365 +78,17 @@ fn around(path: &BezPath, frame: Rect) -> bool {
seen.iter().all(|s| *s) && b.contains(frame.origin()) && b.contains(Point::new(frame.x1, frame.y1))
}
/// A pen: its style flags (`PS_*`), width in logical units, colour and dash entries.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PenObj {
pub style: u32,
pub width: f64,
pub color: [u8; 3],
/// PS_USERSTYLE entries, logical units.
pub entries: Vec<f64>,
}
impl PenObj {
pub fn solid(color: [u8; 3]) -> Self {
Self { style: 0, width: 0.0, color, entries: vec![] }
}
}
pub(crate) const PS_NULL: u32 = 5;
const PS_GEOMETRIC: u32 = 0x0001_0000;
/// A font: its height in logical units (negative: the character height, positive: the cell
/// height), escapement (tenths of a degree), weight, italics and face.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct FontObj {
pub height: f64,
pub escapement: f64,
pub weight: i32,
pub italic: bool,
pub face: String,
}
/// The drawing state.
#[derive(Clone, Debug)]
struct Dc {
pen: PenObj,
/// The brush's color.
brush: [u8; 3],
font: FontObj,
text_color: [u8; 3],
text_align: u32,
fill_rule: FillRule,
miter: f64,
clips: Vec<Arc<Clip>>,
}
impl Default for Dc {
fn default() -> Self {
Self {
pen: PenObj::solid([0; 3]),
brush: [255; 3],
font: FontObj::default(),
text_color: [0; 3],
text_align: 0,
fill_rule: FillRule::EvenOdd,
miter: 10.0,
clips: vec![],
}
}
}
pub(crate) struct Player {
kind: Kind,
/// Picture units → document points.
dev_to_doc: Affine,
dc: Dc,
/// The artboard (document space): clips holding all of it clip nothing worth keeping.
frame: Rect,
/// Lines drawn one after another, not drawn yet.
pending: BezPath,
out: Drawn,
doc: Document,
warnings: Vec<String>,
next_clip: u32,
/// Pixels the file's bitmaps may still decode to ([`dib::MAX_FILE_PIXELS`]).
pub pixels_left: u64,
}
fn rgb(c: [u8; 3]) -> Paint {
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
}
/// A rectangle with elliptical corners `rx` × `ry`.
pub(crate) fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath {
let r = r.abs();
let (rx, ry) = ((rx / 2.0).abs().min(r.width() / 2.0), (ry / 2.0).abs().min(r.height() / 2.0));
if rx <= 0.0 || ry <= 0.0 {
return shapes::rectangle(r).to_bezpath();
}
// A rectangle with round corners of radius `ry`, squeezed across.
let s = ry / rx;
let squeezed = Rect::new(r.x0 * s, r.y0, r.x1 * s, r.y1);
let mut bp = shapes::rounded_rectangle(squeezed, ry).to_bezpath();
bp.apply_affine(Affine::scale_non_uniform(1.0 / s, 1.0));
bp
}
impl Player {
fn new(kind: Kind, dev_to_doc: Affine, artboard: Rect) -> Self {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, LIMIT) } else { 1.0 };
let (w, h) = (side(artboard.width()), side(artboard.height()));
let mut doc = Document::new(w, h);
doc.layers.clear();
Self {
kind,
dev_to_doc,
dc: Dc::default(),
frame: artboard,
pending: BezPath::new(),
out: vec![],
doc,
warnings: vec![],
next_clip: 0,
pixels_left: dib::MAX_FILE_PIXELS,
}
}
pub fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
// ---------- mapping ----------
/// Picture units → document.
fn xf(&self) -> Affine {
self.dev_to_doc
}
/// How much picture lengths grow in the document.
fn scale(&self) -> f64 {
let s = self.xf().determinant().abs().sqrt();
if s.is_finite() { s } else { 0.0 }
}
// ---------- output ----------
fn push(&mut self, mut node: Node) {
if self.out.len() >= MAX_NODES {
return;
}
if !node.visual_bounds().is_none_or(sane) {
return self.warn(FAR_AWAY);
}
node.id = self.doc.alloc_id();
self.out.push((self.dc.clips.clone(), node));
}
fn fill_paint(&self) -> Paint {
rgb(self.dc.brush)
}
fn stroke_layer(&self) -> Option<StrokeLayer> {
let p = &self.dc.pen;
let kind = p.style & 0xf;
if kind == PS_NULL {
return None;
}
// Geometric pens, and other pens wider than 1, have a width in logical units; the others
// are one pixel wide.
let w = p.width * self.scale();
let width = if w > 0.0 && w.is_finite() && (p.style & PS_GEOMETRIC != 0 || p.width > 1.0) { w } else { HAIRLINE };
let mut st = StrokeLayer::new(rgb(p.color), width);
// Round caps and joins unless the style asks for others.
st.cap = match p.style & 0xf00 {
0x100 => LineCap::Square,
0x200 => LineCap::Butt,
_ => LineCap::Round,
};
st.join = match p.style & 0xf000 {
0x1000 => LineJoin::Bevel,
0x2000 => LineJoin::Miter,
_ => LineJoin::Round,
};
st.miter_limit = self.dc.miter;
let unit = width.max(HAIRLINE);
let pattern: Vec<f64> = match kind {
1 => vec![3.0 * unit, unit],
2 => vec![unit, unit],
3 => vec![3.0 * unit, unit, unit, unit],
4 => vec![3.0 * unit, unit, unit, unit, unit, unit],
7 => p.entries.iter().map(|e| e * self.scale()).collect(),
_ => vec![],
};
let dash = Dash { pattern, offset: 0.0, align_corners: false };
st.dash = dash.is_dashed().then_some(dash);
Some(st)
}
/// Paint `bp` (document space) with the brush and the pen.
fn draw(&mut self, bp: BezPath, fill: bool, stroke: bool) {
if bp.elements().is_empty() {
return;
}
let mut items = vec![];
if fill {
items.push(AppearanceItem::Fill(FillLayer::new(self.fill_paint())));
}
if stroke && let Some(st) = self.stroke_layer() {
items.push(AppearanceItem::Stroke(st));
}
if items.is_empty() {
return;
}
let mut n = Node::path(vectorcraft_doc::NodeId(0), PathData::from_bezpath(&bp), Appearance { items, ..Appearance::default() });
if let NodeKind::Path { rule, .. } = &mut n.kind {
*rule = self.dc.fill_rule;
}
self.push(n);
}
/// Draw the lines drawn one after another so far.
pub fn flush(&mut self) {
if !self.pending.elements().is_empty() {
let bp = std::mem::take(&mut self.pending);
self.draw(bp, false, true);
}
}
// ---------- clips ----------
fn push_clip(&mut self, path: BezPath, rule: FillRule, replace: bool) {
if replace {
self.dc.clips.clear();
}
if !sane(path.bounding_box()) {
return self.warn(FAR_AWAY);
}
if around(&path, self.frame) {
return;
}
if self.dc.clips.len() >= MAX_NEST {
return self.warn(&deep_clips());
}
self.next_clip += 1;
self.dc.clips.push(Arc::new(Clip { id: self.next_clip, region: Some((path, rule)) }));
}
// ---------- images and text ----------
/// An image whose source rectangle `src` (pixels, from the top-left) is drawn into `dest`
/// (picture units: origin and signed size) with raster operation `rop`, at `opacity`.
pub fn image(&mut self, img: Result<Rgba, String>, src: Rect, dest: Rect, rop: u32, opacity: f64) {
if rop != SRCCOPY {
self.warn(SKIPPED_ROPS);
return;
}
let img = match img {
Ok(i) => i,
Err(e) if e == dib::OVER_BUDGET => return self.warn(TOO_MANY_PIXELS),
Err(_) => return self.warn(BAD_IMAGE),
};
let img = crop(img, src);
if img.width == 0 || img.height == 0 {
return;
}
let (w, h) = (f64::from(img.width), f64::from(img.height));
self.image_xf(img, Affine::translate((dest.x0, dest.y0)) * Affine::scale_non_uniform(dest.width() / w, dest.height() / h), opacity);
}
/// An image placed by `xf` (its pixels, from the top-left, → picture units), at `opacity`. An
/// image that `xf` flattens or sends past finite numbers is left out, and adds nothing to the
/// document's images.
pub(crate) fn image_xf(&mut self, img: Rgba, xf: Affine, opacity: f64) {
if img.width == 0 || img.height == 0 {
return;
}
let xf = self.xf() * xf;
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
return;
}
let Ok(png) = img.to_png() else { return self.warn(BAD_IMAGE) };
let blob = ImageBlob::new("image/png", png);
let key = blob.content_key();
self.doc.images.entry(key.clone()).or_insert(blob);
let im = ImageObject { key, width: img.width, height: img.height, xf, link: None, placement: Default::default(), pixels: None };
let mut n = Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im)));
n.opacity = opacity.clamp(0.0, 1.0) as f32;
self.push(n);
}
/// Text at `at` (picture units) in the current font.
pub fn text(&mut self, at: Point, s: &str) {
let s: String = s.chars().filter(|c| *c != '\0').collect();
if s.trim().is_empty() {
return;
}
let align = self.dc.text_align;
let f = self.dc.font.clone();
let k = self.scale();
// A negative height is the em; a positive one the cell (the em and the internal leading).
let em = if f.height < 0.0 { -f.height } else { f.height * 0.85 };
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
let mut style = CharStyle { size, fill: rgb(self.dc.text_color), stroke: Paint::None, ..CharStyle::default() };
if !f.face.trim().is_empty() {
style.font_family = f.face.trim().to_string();
}
style.font_style = match (f.weight >= 600, f.italic) {
(true, true) => "Bold Italic",
(true, false) => "Bold",
(false, true) => "Italic",
(false, false) => "Regular",
}
.into();
let angle = -(f.escapement / 10.0).to_radians();
let angle = if angle.is_finite() { angle } else { 0.0 };
// TA_BASELINE, TA_BOTTOM or TA_TOP (the default): where the baseline is.
let drop = match align & 0x18 {
0x18 => 0.0,
0x08 => -0.2 * size,
_ => 0.8 * size,
};
let origin = self.xf() * at;
let mut t = TextObject::point(Point::ZERO, &s, style);
t.xf = Affine::translate(origin.to_vec2()) * Affine::rotate(angle) * Affine::translate((0.0, drop));
t.para.justify = match align & 0x06 {
0x06 => Justify::Center,
0x02 => Justify::Right,
_ => Justify::Left,
};
t.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).bounds);
self.push(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(t))));
}
// ---------- the document ----------
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self) -> Imported {
self.flush();
let out = std::mem::take(&mut self.out);
let children = nest(&mut self.doc, out);
let mut layer = Node::layer(self.doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
if let Some(c) = layer.children_mut() {
*c = children;
}
self.doc.layers = vec![Arc::new(layer)];
Imported { document: self.doc, kind: self.kind, warnings: self.warnings }
}
}
/// `img` cut to `src` (pixels from the top-left, within the image).
fn crop(img: Rgba, src: Rect) -> Rgba {
let (w, h) = (img.width, img.height);
let s = src.abs();
let clamp = |v: f64, max: u32| if v.is_finite() { v.round().clamp(0.0, f64::from(max)) as u32 } else { 0 };
let (x0, y0, x1, y1) = (clamp(s.x0, w), clamp(s.y0, h), clamp(s.x1, w), clamp(s.y1, h));
if (x0, y0, x1, y1) == (0, 0, w, h) || x1 <= x0 || y1 <= y0 {
return img;
}
let mut pixels = Vec::with_capacity(((x1 - x0) * (y1 - y0) * 4) as usize);
for y in y0..y1 {
let row = (y * w) as usize * 4;
if let Some(p) = img.pixels.get(row + x0 as usize * 4..row + x1 as usize * 4) {
pixels.extend_from_slice(p);
}
}
Rgba { width: x1 - x0, height: y1 - y0, pixels }
}
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
picture::import(bytes)
pub(crate) use picture::import;
/// Read a QuickDraw picture (PICT, versions 1 and 2) through `craft_metafile`.
pub(crate) fn import_pict(bytes: &[u8]) -> Result<crate::Picture, String> {
let pic = craft_metafile::parse_pict(bytes).map_err(|e| match e {
craft_metafile::Error::NotPict => "not a PICT file".to_string(),
_ => "the PICT file is damaged".to_string(),
})?;
Ok(picture::convert(pic))
}
File diff suppressed because it is too large. Load diff
+51 -172
View File
@@ -44,158 +44,55 @@ use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect,
use super::{BAD_IMAGE, FAR_AWAY, HAIRLINE, LIMIT, MAX_NODES, around, rgb, sane};
use crate::dib::Rgba;
use crate::wmf::PLACEABLE_KEY;
use crate::{Imported, Kind};
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read";
const PICT_TRUNCATED: &str = "the picture is cut short or reached a limit on what one file may hold: what came after was not read";
/// Points a unit of a WMF without a placeable header (1440 units an inch).
const WMF_UNIT: f64 = 72.0 / 1440.0;
/// The SAVEDC levels `craft_metafile` keeps; it stops reading at a SAVEDC past them.
const SAVED_LEVELS: usize = 1024;
/// Points a pixel at 96 pixels an inch.
const PT_PER_PX: f64 = 72.0 / 96.0;
/// Points a millimetre.
const PT_PER_MM: f64 = 72.0 / 25.4;
/// WMF records that draw lines and shapes, which `craft_metafile` plays only when the mix mode
/// lets them draw.
const WMF_SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830];
/// WMF records that draw text and bitmaps, which `craft_metafile` plays whatever the mix mode.
const WMF_DRAWS: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43];
/// SETROP2 mix modes under which `craft_metafile` draws no lines, shapes or brush fills: R2_XORPEN
/// and R2_NOP.
const WMF_MIX_SKIPS: [u16; 2] = [7, 11];
/// The mix mode a WMF starts in (R2_COPYPEN).
const WMF_MIX_START: u16 = 13;
/// PATBLT raster operations `craft_metafile` draws: PATCOPY (with the brush, as the mix mode
/// allows), BLACKNESS and WHITENESS.
const PATCOPY: u32 = 0x00F0_0021;
const BLACKNESS: u32 = 0x0000_0042;
const WHITENESS: u32 = 0x00FF_0062;
/// Does a WMF draw in a metric map mode (MM_LOMETRIC to MM_TWIPS)? `craft_metafile` plays those
/// at 96 pixels an inch, whatever the window. The mode that more drawing records are played in
/// decides, counting only records the reader draws (not lines and shapes under R2_NOP or
/// R2_XORPEN, nor a PATBLT it does not fill); a file that draws nothing goes by its last mode.
/// `start` is where the standard header begins.
fn wmf_metric(bytes: &[u8], start: usize) -> bool {
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let Some(words) = start.checked_add(2).and_then(u16_at) else { return false };
let mut at = start.saturating_add(usize::from(words) * 2);
let mut mode = 1;
let mut mix = WMF_MIX_START;
let metric = |mode: u16| (2..=6).contains(&mode);
// Drawing records played in a metric mode, and in any other.
let (mut in_metric, mut in_other) = (0usize, 0usize);
// The map and mix modes SAVEDC kept, which RESTOREDC brings back as the reader does.
let mut saved: Vec<(u16, u16)> = Vec::new();
// The records as the reader walks them: it stops at the end record, a record shorter than its
// header, one that runs past the file and a SAVEDC past its 1,024 levels.
while let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) {
let size = (words as usize).saturating_mul(2);
let Some(next) = at.checked_add(size) else { break };
if function == 0 || size < 6 || next > bytes.len() {
break;
}
match function {
// SETMAPMODE, when the record holds its mode.
0x0103 if size >= 8 => mode = u16_at(at + 6).unwrap_or(mode),
// SETROP2, when the record holds its mix mode.
0x0104 if size >= 8 => mix = u16_at(at + 6).unwrap_or(mix),
// SAVEDC.
0x001E => {
if saved.len() >= SAVED_LEVELS {
break;
}
saved.push((mode, mix));
}
// RESTOREDC: a negative count pops that many levels, a positive one goes back to that
// level. One that names no saved level changes nothing.
0x0127 if size >= 8 => {
let n = u16_at(at + 6).map_or(0, |v| i32::from(i16::from_le_bytes(v.to_le_bytes())));
let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) };
if let Some(level) = level
&& let Some((m, x)) = saved.get(level).copied()
{
mode = m;
mix = x;
saved.truncate(level);
}
}
f => {
let draws = match f {
_ if WMF_DRAWS.contains(&f) => true,
_ if WMF_SHAPES.contains(&f) => !WMF_MIX_SKIPS.contains(&mix),
// PATBLT: its raster operation, when the record holds one.
0x061D => match u32_at(at + 6).filter(|_| size >= 10) {
Some(PATCOPY) => !WMF_MIX_SKIPS.contains(&mix),
Some(rop) => rop == BLACKNESS || rop == WHITENESS,
None => false,
},
_ => false,
};
if draws && metric(mode) {
in_metric += 1;
} else if draws {
in_other += 1;
}
}
}
at = next;
}
if in_metric == in_other { metric(mode) } else { in_metric > in_other }
}
/// Points a picture unit across and down. `craft_metafile` gives a placeable WMF with a box and an
/// EMF with a frame in points, and other files in their logical units (WMF; pixels in a metric map
/// mode) or device units (EMF).
fn unit(bytes: &[u8], kind: Kind) -> (f64, f64) {
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let i16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| i16::from_le_bytes([b[0], b[1]]));
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let i32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let positive = |v: Option<i32>| v.filter(|v| *v > 0).map(f64::from);
match kind {
Kind::Wmf => {
let placeable = bytes.get(..4) == Some(&PLACEABLE_KEY.to_le_bytes()[..]);
if placeable
&& let (Some(l), Some(t), Some(r), Some(b)) = (i16_at(6), i16_at(8), i16_at(10), i16_at(12))
&& r > l
&& b > t
{
return (1.0, 1.0);
}
if wmf_metric(bytes, if placeable { 22 } else { 0 }) {
return (PT_PER_PX, PT_PER_PX);
}
if !placeable {
return (WMF_UNIT, WMF_UNIT);
}
let k = 72.0 / u16_at(14).filter(|v| *v > 0).map_or(1440.0, f64::from);
/// mode) or device units (EMF). The file's frame and unit facts come from
/// [`craft_metafile::unit_facts`]; the fallback scales here are VectorCraft's policy.
fn unit(bytes: &[u8]) -> (f64, f64) {
use craft_metafile::{EmfPhysicalSize, UnitFacts};
match craft_metafile::unit_facts(bytes) {
Some(UnitFacts::WmfPlaceableFrame) => (1.0, 1.0),
// `craft_metafile` plays the metric map modes at 96 pixels an inch, whatever the window.
Some(UnitFacts::WmfMetricMap) => (PT_PER_PX, PT_PER_PX),
// Without a placeable header, or with no units an inch in it: 1440 units an inch.
Some(UnitFacts::WmfLogical { units_per_inch }) => {
let k = units_per_inch.map_or(WMF_UNIT, |inch| 72.0 / f64::from(inch));
(k, k)
}
Kind::Emf => {
// Device pixels a millimetre on each axis: szlDevice over szlMicrometers when the header
// has them, else over szlMillimeters (both sizes must be positive).
let device = positive(i32_at(72)).zip(positive(i32_at(76)));
let micro = (u32_at(4).is_some_and(|s| s >= 108))
.then(|| u32_at(100).zip(u32_at(104)).filter(|(w, h)| *w > 0 && *h > 0).map(|(w, h)| (f64::from(w) / 1000.0, f64::from(h) / 1000.0)))
.flatten();
let mm = micro.or_else(|| positive(i32_at(80)).zip(positive(i32_at(84))));
let px_mm = device.zip(mm).map(|((w, h), (mw, mh))| (w / mw, h / mh));
let frame = matches!((i32_at(24), i32_at(28), i32_at(32), i32_at(36)), (Some(l), Some(t), Some(r), Some(b)) if r > l && b > t);
Some(UnitFacts::Emf { has_frame, device }) => {
// Device pixels a millimetre on each axis.
let px_mm = device.map(|d| {
let (w, h) = (f64::from(d.pixels.0), f64::from(d.pixels.1));
let (mw, mh) = match d.physical_size {
EmfPhysicalSize::Micrometres(w, h) => (f64::from(w) / 1000.0, f64::from(h) / 1000.0),
EmfPhysicalSize::Millimetres(w, h) => (f64::from(w), f64::from(h)),
};
(w / mw, h / mh)
});
let ok = |v: f64| v.is_finite() && v > 0.0;
match px_mm {
Some(_) if frame => (1.0, 1.0),
Some(_) if has_frame => (1.0, 1.0),
Some((x, y)) if ok(x) && ok(y) => (PT_PER_MM / x, PT_PER_MM / y),
_ => (PT_PER_PX, PT_PER_PX),
}
}
// Not reached: `crate::sniff` accepted the file through the same shared sniff.
None => (PT_PER_PX, PT_PER_PX),
}
}
@@ -272,7 +169,7 @@ fn average(rgba: &[u8]) -> Option<[u8; 4]> {
}
let a = sum[3];
let alpha = (a / pixels.len().max(1) as u64) as u8;
(a > 0).then(|| [(sum[0] / a) as u8, (sum[1] / a) as u8, (sum[2] / a) as u8, alpha.max(1)])
(a > 0).then(|| [((sum[0] + a / 2) / a) as u8, ((sum[1] + a / 2) / a) as u8, ((sum[2] + a / 2) / a) as u8, alpha.max(1)])
}
impl Mapper {
@@ -1162,57 +1059,21 @@ fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) ->
Some(out)
}
/// Does the file stop before its end-of-file record?
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]]));
let mut at = match kind {
Kind::Emf => 0,
Kind::Wmf => {
let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 };
let Some(words) = u16_at(start + 2) else { return true };
start + usize::from(words) * 2
}
};
loop {
let size = match kind {
Kind::Emf => {
let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true };
if kind == 14 {
return false;
}
// Records are a multiple of 4 bytes long; reading stops at one that isn't.
if !size.is_multiple_of(4) {
return true;
}
size as usize
}
Kind::Wmf => {
let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true };
if function == 0 {
return false;
}
(words as usize).saturating_mul(2)
}
};
if size < 6 {
return true;
}
at = at.saturating_add(size);
}
}
/// Read an EMF or WMF file.
pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
let kind = crate::sniff(bytes).ok_or("not an EMF or WMF file")?;
let pic = craft_metafile::parse(bytes).map_err(|e| match e {
craft_metafile::Error::NotMetafile => "not an EMF or WMF file".to_string(),
craft_metafile::Error::NotMetafile | craft_metafile::Error::NotPict => "not an EMF or WMF file".to_string(),
craft_metafile::Error::BadHeader => format!("the {} header is damaged", kind.id().to_uppercase()),
craft_metafile::Error::NoRecords => format!("the {} file holds no records", kind.id().to_uppercase()),
})?;
let k = unit(bytes, kind);
let k = unit(bytes);
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), k);
if ends_early(bytes, kind) {
let wire_kind = match kind {
Kind::Emf => craft_metafile::Kind::Emf,
Kind::Wmf => craft_metafile::Kind::Wmf,
};
if craft_metafile::ends_early(bytes, wire_kind) {
m.warn(ENDS_EARLY);
}
if pic.truncated {
@@ -1224,3 +1085,21 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
}
Ok(m.finish(kind, lost))
}
/// Turn a metafile picture into a document.
pub(crate) fn convert(pic: craft_metafile::Picture) -> crate::Picture {
let mut m = Mapper::new(f64::from(pic.width), f64::from(pic.height), (1.0, 1.0));
if pic.truncated {
m.warn(PICT_TRUNCATED);
}
let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops };
for item in pic.items {
m.item(item);
}
let imported = m.finish(Kind::Wmf, lost);
let mut p = crate::Picture { document: imported.document, warnings: imported.warnings };
if p.document.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())) {
p.warnings.push("the picture draws nothing VectorCraft reads".to_string());
}
p
}
+14 -27
View File
@@ -22,18 +22,14 @@
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
//! - `bytes`: little-endian writing.
//! - `dib`: device-independent bitmaps for the writers.
//! - `scene`: the document walk both writers share.
//! - `emf`, `wmf`: the writers.
//! - `import`: the readers.
//! The app walks its document and maps its drawing operations to the shared writers.
#[cfg(test)]
mod bytes;
mod dib;
mod emf;
mod encode;
mod import;
mod scene;
mod wmf;
use vectorcraft_doc::Document;
use vectorcraft_geom::Rect;
@@ -59,13 +55,10 @@ impl Kind {
/// The metafile format `bytes` start like, if any.
pub fn sniff(bytes: &[u8]) -> Option<Kind> {
if emf::is_emf(bytes) {
Some(Kind::Emf)
} else if wmf::is_wmf(bytes) {
Some(Kind::Wmf)
} else {
None
}
craft_metafile::sniff(bytes).map(|kind| match kind {
craft_metafile::Kind::Emf => Kind::Emf,
craft_metafile::Kind::Wmf => Kind::Wmf,
})
}
/// A written metafile.
@@ -109,18 +102,13 @@ pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Ve
let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false };
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
let doc = baked.as_ref().unwrap_or(doc);
let outputs = regions
regions
.into_iter()
.map(|r| {
let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run();
let bytes = match kind {
Kind::Emf => emf::write(&ops, r, doc.info_title()),
Kind::Wmf => wmf::write(&ops, r, &mut warnings),
};
Output { bytes, warnings }
encode::write(ops, r, kind, doc.info_title(), &mut warnings).map(|bytes| Output { bytes, warnings })
})
.collect();
Ok(outputs)
.collect()
}
/// A metafile read into a document.
@@ -148,17 +136,16 @@ pub struct Picture {
pub warnings: Vec<String>,
}
/// Do `bytes` hold a version 2 QuickDraw picture, after a PICT file's 512 bytes of application
/// data or on their own? A version 1 picture is known by its file's name.
/// Do `bytes` hold a QuickDraw picture (version 1 or 2), after a PICT file's 512 bytes of
/// application data or on their own?
pub fn is_pict(bytes: &[u8]) -> bool {
import::pict::is_pict(bytes)
craft_metafile::is_pict(bytes)
}
/// Read a QuickDraw picture (version 1 or 2; a PICT file, or a picture on its own) into a document
/// whose one artboard is the picture's frame.
pub fn import_pict(bytes: &[u8]) -> Result<Picture, String> {
let i = import::pict::play(bytes)?;
let mut p = Picture { document: i.document, warnings: i.warnings };
let mut p = import::import_pict(bytes)?;
p.document.limit_depth_noting(&mut p.warnings);
Ok(p)
}
+9 -14
View File
@@ -14,7 +14,7 @@ use vectorcraft_doc::{AppearanceItem, Dash, Document, ImageObject, LineCap, Line
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape};
use crate::dib::Rgba;
use craft_metafile::write::Image;
/// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out).
const MAX_NEST: u32 = 8;
@@ -73,7 +73,7 @@ pub(crate) enum Op {
/// An image: its pixel space (0..w, 0..h) maps into the document by `xf`; its alpha times
/// `opacity`.
Image {
image: Arc<Rgba>,
image: Arc<Image>,
xf: Affine,
opacity: f32,
},
@@ -104,11 +104,6 @@ fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
}
/// `bp` cut into its dashes (as it is when `dash` draws none), for pens that can't draw them.
pub(crate) fn dashed(bp: &BezPath, dash: Option<&Dash>) -> BezPath {
dash.and_then(|d| stroke::dash(bp, d)).map_or_else(|| bp.clone(), |d| d.path)
}
fn q(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0).round() as u8
}
@@ -124,7 +119,7 @@ pub(crate) struct Scene<'a> {
ops: Vec<Op>,
warnings: Vec<String>,
/// Decoded images by key (`None`: can't be decoded, left out).
images: HashMap<String, Option<Arc<Rgba>>>,
images: HashMap<String, Option<Arc<Image>>>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// The opacity of the containers around the current object.
opacity: f32,
@@ -456,7 +451,7 @@ impl<'a> Scene<'a> {
})
.collect()
};
let image = Rgba { width: u32::from(cols), height: u32::from(rows), pixels };
let image = Image { width: u32::from(cols), height: u32::from(rows), rgba: pixels };
let xf =
Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width() / f64::from(cols), area.height() / f64::from(rows));
self.ops.push(Op::Clip { path: bp.clone(), rule });
@@ -518,7 +513,7 @@ impl<'a> Scene<'a> {
/// Image `im`'s pixels (scaled down to what a metafile stores), `None` with a warning when it
/// has none or can't be decoded.
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Rgba>> {
fn decoded(&mut self, im: &ImageObject) -> Option<Arc<Image>> {
let key = im.key.as_str();
if let Some(i) = self.images.get(key) {
return i.clone();
@@ -527,7 +522,7 @@ impl<'a> Scene<'a> {
let img = blob
.and_then(|b| craft_image_codecs::decode(&b.bytes).ok())
.and_then(|i| image::RgbaImage::from_raw(i.width(), i.height(), i.to_rgba8()))
.map(Rgba::fitted)
.map(crate::dib::fitted)
.filter(|i| i.width > 0 && i.height > 0)
.map(Arc::new);
if img.is_none() {
@@ -541,7 +536,7 @@ impl<'a> Scene<'a> {
/// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel
/// more on each side: the part and its top left pixel. The whole image when `xf` cannot be
/// inverted; `None` when `clip` shows none of it.
fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
fn cropped(img: &Image, xf: Affine, clip: Rect) -> Option<(Image, u32, u32)> {
if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() {
return Some((img.clone(), 0, 0));
}
@@ -564,9 +559,9 @@ fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> {
let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4);
for y in y0..y1 {
let start = y as usize * row + x0 as usize * 4;
pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?);
pixels.extend_from_slice(img.rgba.get(start..start + (x1 - x0) as usize * 4)?);
}
Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0))
Some((Image { width: x1 - x0, height: y1 - y0, rgba: pixels }, x0, y0))
}
/// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so
+9 -13
View File
@@ -342,7 +342,7 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
})
.collect();
let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run();
let parts: Vec<(&crate::dib::Rgba, Affine)> = ops
let parts: Vec<(&craft_metafile::write::Image, Affine)> = ops
.iter()
.filter_map(|o| match o {
crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)),
@@ -355,12 +355,12 @@ fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() {
assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len());
for ((part, xf), full) in parts.iter().zip(&whole) {
// The part's first pixel names where it starts in the image.
let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4));
let (x0, y0) = (f64::from(part.rgba[0] / 4), f64::from(part.rgba[1] / 4));
let want = *full * Affine::translate((x0, y0));
assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}");
// Each row runs on from that pixel.
let last = (part.width as usize - 1) * 4;
assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1));
assert_eq!(f64::from(part.rgba[last] / 4), x0 + f64::from(part.width - 1));
}
}
@@ -394,7 +394,7 @@ fn ruby_is_written_with_its_type() {
let reading = contours(&lay.ruby);
assert!(reading >= 3, "the reading has ink: {reading}");
let doc = |ruby: bool| doc_with(100.0, 100.0, vec![Node::new(NodeId(0), NodeKind::Text(Box::new(typed(ruby))))]);
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), crate::emf::MOVETOEX);
let moves = |d: &Document| count(&kinds(&emf_records(&emf(d).bytes)), 27 /* EMR_MOVETOEX */);
assert_eq!(moves(&doc(true)), moves(&doc(false)) + reading, "the reading's contours are written");
assert!(wmf(&doc(true)).bytes.len() > wmf(&doc(false)).bytes.len(), "WMF writes the reading too");
}
@@ -411,7 +411,6 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
assert_eq!(u16_at(b, 14), 1440);
let xor = (0..10).fold(0u16, |a, i| a ^ u16_at(b, 2 * i));
assert_eq!(u16_at(b, 20), xor, "the checksum");
assert_eq!(crate::wmf::checksum(&b[..20]), xor);
// The WMF header: a memory metafile of 9 words, its size in words, the largest record.
assert_eq!([u16_at(b, 22), u16_at(b, 24), u16_at(b, 26)], [1, 9, 0x0300]);
assert_eq!(u32_at(b, 28) as usize * 2, b.len() - 22);
@@ -431,12 +430,12 @@ fn wmf_placeable_header_checksum_and_record_sizes() {
#[test]
fn wmf_sizes_fit_sixteen_bits() {
assert_eq!(crate::wmf::units_per_inch(612.0, 792.0), 1440);
let inch = crate::wmf::units_per_inch(3000.0, 1000.0);
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
let ordinary = wmf(&doc_with(612.0, 792.0, Vec::new())).bytes;
assert_eq!(u16_at(&ordinary, 14), 1440);
let d = doc_with(3000.0, 1000.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 3000.0, 1000.0)), red(), Paint::None, 0.0)]);
let b = wmf(&d).bytes;
assert_eq!(u16_at(&b, 14), inch);
let inch = u16_at(&b, 14);
assert!(inch < 1440 && f64::from(inch) * 3000.0 / 72.0 <= 32767.0);
assert!(u16_at(&b, 10) <= 32767);
}
@@ -483,10 +482,7 @@ fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers);
let doc = baked.as_ref().unwrap_or(doc);
let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run();
let bytes = match kind {
Kind::Emf => crate::emf::write(&ops, r, doc.info_title()),
Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings),
};
let bytes = crate::encode::write(ops, r, kind, doc.info_title(), &mut warnings)?;
Ok(Output { bytes, warnings })
}
+1 -1
View File
@@ -314,7 +314,7 @@ fn hand_wmf(w: i16, h: i16, records: &[(u16, Vec<u8>)]) -> Vec<u8> {
}
o.u16(1440);
o.u32(0);
let sum = crate::wmf::checksum(&o.0);
let sum = o.0.as_chunks::<2>().0.iter().fold(0, |acc, pair| acc ^ u16::from_le_bytes(*pair));
o.u16(sum);
o.bytes(&[1, 0, 9, 0, 0, 3]);
o.bytes(&[0; 12]);
Loaded 100 of 1034 files, more files were not shown because too many files have changed in this diff. Show more