mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 09:23:10 +01:00
Merge main into fix/metafile-loss-warnings
# Conflicts: # Cargo.toml
This commit is contained in:
commit
cce26edfa0
161 files changed
+13344
-662
No files matched your search
Generated
+1
-1
@@ -1190,7 +1190,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
|
||||
|
||||
@@ -591,14 +591,15 @@ fn main() -> std::process::ExitCode {
|
||||
created.created(&cc.egui_ctx);
|
||||
if !gpu::skipped().is_empty() {
|
||||
// A processor chosen in Settings can be the one that can't show the window.
|
||||
let hint = if chosen_gpu {
|
||||
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
if chosen_gpu {
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
|
||||
));
|
||||
} else {
|
||||
""
|
||||
};
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
|
||||
));
|
||||
app.status(format!(
|
||||
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
|
||||
));
|
||||
}
|
||||
} else if let Some(crash) = &crash {
|
||||
app.status(match crash {
|
||||
gpu::Crash::Adapter { name, .. } => format!(
|
||||
|
||||
@@ -54,6 +54,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) ->
|
||||
|
||||
impl Overrides {
|
||||
/// Whether a flag or a variable set the present mode or the frame latency.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
|
||||
pub fn is_set(&self) -> bool {
|
||||
*self != Self::default()
|
||||
}
|
||||
|
||||
@@ -9,9 +9,8 @@ impl PrintService for SystemPrint {
|
||||
system::printers()
|
||||
}
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
let result = system::print(job);
|
||||
let to = job.printer.unwrap_or("the default printer");
|
||||
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
|
||||
@@ -29,6 +28,15 @@ impl PrintService for SystemPrint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status after the job `title` went to `printer` (the default one without a name), with the
|
||||
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
|
||||
/// match it and translate it. The note follows as its own sentence: a printer name can end in
|
||||
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
|
||||
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
|
||||
let to = printer.unwrap_or("the default printer");
|
||||
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
|
||||
}
|
||||
|
||||
mod system {
|
||||
use super::{Command, PrintJob, Printer};
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
@@ -38,7 +46,7 @@ mod system {
|
||||
// Copies, layout, marks and colour management are already in the PDF. Preserve its
|
||||
// physical sheet size and the queue's duplex default without printing copies twice.
|
||||
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
|
||||
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
@@ -127,9 +135,28 @@ mod tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod turn_tests {
|
||||
use super::SystemPrint;
|
||||
use super::{SystemPrint, sent};
|
||||
use vectorcraft_ui_egui::print::PrintService;
|
||||
|
||||
#[test]
|
||||
fn the_sent_status_names_the_job_the_printer_and_the_note() {
|
||||
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
|
||||
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
|
||||
let printer = Some("HP LaserJet (Copy 1)");
|
||||
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
|
||||
assert_eq!(
|
||||
message(de, &sent("Poster", printer, "job 12")),
|
||||
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_macos_queues_need_landscape_pages_turned() {
|
||||
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
|
||||
|
||||
@@ -294,13 +294,19 @@ impl GuideOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
|
||||
if step == 0 {
|
||||
return c;
|
||||
}
|
||||
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
|
||||
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 => {
|
||||
|
||||
@@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
|
||||
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
|
||||
}
|
||||
|
||||
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
|
||||
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
|
||||
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
|
||||
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
|
||||
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
|
||||
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
|
||||
let rail = Rail::new(keys, spec);
|
||||
keys.windows(2).enumerate().all(|(i, w)| {
|
||||
let [a, b] = w else { return true };
|
||||
match spec.spacing {
|
||||
BlendSpacing::Steps(_) => true,
|
||||
// The count is `len / d` rounded, which grows with `len`.
|
||||
BlendSpacing::Distance(d) => {
|
||||
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
|
||||
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
|
||||
count(len - length) == count(len + length)
|
||||
}
|
||||
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
|
||||
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
|
||||
/// between their edges in key sizes), so the pair is settled when the least and the most of
|
||||
/// these ask for the same count.
|
||||
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ, but by too little to count, or by little more: moving them may cross
|
||||
// where they stop counting as the same. (The same colors stay the same.)
|
||||
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach =
|
||||
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
// The centers and sizes move by up to twice `length`.
|
||||
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
|
||||
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
|
||||
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
|
||||
reach.is_finite() && least == most
|
||||
}
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
|
||||
(_, Some((ba, bb))) => {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
if w <= 4.0 * length || h <= 4.0 * length {
|
||||
return false;
|
||||
}
|
||||
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
|
||||
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
|
||||
// Each edge moves by up to `length`: the distances between them by up to twice that,
|
||||
// and the mean sizes too.
|
||||
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
|
||||
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
|
||||
let m = 2.0 * length;
|
||||
let least = q(dx - m, dy - m, w + m, h + m);
|
||||
let most = q(dx + m, dy + m, w - m, h - m);
|
||||
least.is_finite() && most.is_finite() && count(least) == count(most)
|
||||
}
|
||||
(_, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
|
||||
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
|
||||
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
|
||||
@@ -3535,4 +3599,46 @@ mod tests {
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
|
||||
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
|
||||
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
|
||||
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
|
||||
/// color difference or the keys' reach sits where its count changes, or keys of the same color
|
||||
/// are at most four times 0.01 pt wide.
|
||||
#[test]
|
||||
fn steps_settle_unless_rounding_can_change_their_count() {
|
||||
let (length, color) = (0.01, 0.001);
|
||||
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
|
||||
let spec = BlendSpec { spacing, ..Default::default() };
|
||||
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
|
||||
};
|
||||
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
|
||||
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
|
||||
|
||||
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
|
||||
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
|
||||
|
||||
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
|
||||
// (settled) and by 51.5 (where the count changes).
|
||||
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
|
||||
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
|
||||
// 10.0625 pt (80.5 steps) is not.
|
||||
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
|
||||
assert!(near(10.0));
|
||||
assert!(!near(10.0625));
|
||||
// Keys without bounds are counted by their colors alone.
|
||||
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
|
||||
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
|
||||
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
|
||||
// are never settled.
|
||||
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
|
||||
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,11 @@ impl TextObject {
|
||||
/// Character attributes as presented by controls (stored runs stay local for layout
|
||||
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
|
||||
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
|
||||
let scale = self.style_scale()?;
|
||||
Self::scaled_char_style(style, self.style_scale()?)
|
||||
}
|
||||
|
||||
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
|
||||
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
|
||||
let mut style = style.clone();
|
||||
style.size *= scale.points;
|
||||
style.leading = style.leading.map(|v| v * scale.points);
|
||||
@@ -57,19 +61,27 @@ impl TextObject {
|
||||
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
|
||||
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
|
||||
/// transform).
|
||||
///
|
||||
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
|
||||
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
|
||||
/// non-uniform scale of the path would move, and a uniform one keeps.
|
||||
pub fn scale_text_attributes(&mut self) -> bool {
|
||||
let Some(scale) = self.style_scale() else { return false };
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
let Some(mut scale) = self.style_scale() else { return false };
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let [a, b, c, d, _, _] = self.xf.as_coeffs();
|
||||
let (sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
if sx <= 1e-12 || sy <= 1e-12 {
|
||||
if matches!(self.kind, TextKind::OnPath { .. }) {
|
||||
scale.horizontal = 1.0;
|
||||
sx = sy;
|
||||
}
|
||||
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
let mut baked = Vec::with_capacity(self.runs.len());
|
||||
for run in &self.runs {
|
||||
let Some(eff) = self.effective_char_style(&run.style) else { return false };
|
||||
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
|
||||
baked.push(eff);
|
||||
}
|
||||
for (run, style) in self.runs.iter_mut().zip(baked) {
|
||||
@@ -78,6 +90,14 @@ impl TextObject {
|
||||
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
|
||||
self.scale_char_strokes(1.0 / sy);
|
||||
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
|
||||
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
|
||||
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
|
||||
let grow = Affine::scale_non_uniform(sx, sy);
|
||||
match &mut self.kind {
|
||||
TextKind::Area { frame } => frame.transform(grow),
|
||||
TextKind::OnPath { path, .. } => path.transform(grow),
|
||||
TextKind::Point => {}
|
||||
}
|
||||
self.cached_bounds = None;
|
||||
self.cached_baselines.clear();
|
||||
self.cached_ink = None;
|
||||
|
||||
@@ -53,7 +53,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flare",
|
||||
[],
|
||||
None,
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: places the rings along the path anew, keeping their count and sizes)} → {id}",
|
||||
"{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}",
|
||||
has_doc,
|
||||
flare
|
||||
),
|
||||
@@ -565,7 +565,7 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))),
|
||||
};
|
||||
// The generator's state is odd (never 0).
|
||||
// Xorshift64. Both streams start from a nonzero state.
|
||||
let random = |mut state: u64| {
|
||||
move || {
|
||||
state ^= state << 13;
|
||||
@@ -580,7 +580,13 @@ fn flare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))),
|
||||
r => r,
|
||||
};
|
||||
let mut ring_at = ring_seed.map(|r| random((r << 1) | 1));
|
||||
let mut ring_at = ring_seed.map(|r| {
|
||||
// SplitMix64 initializes the ring-position stream.
|
||||
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
random(z ^ (z >> 31))
|
||||
});
|
||||
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) };
|
||||
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -200,14 +200,22 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
|
||||
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
|
||||
let closed = switch_or(p, "closed", false, C)?;
|
||||
let brush = str_param(p, "style") == Some("brush");
|
||||
let brush = match p.get("style").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("pencil")) => false,
|
||||
Some(Some("brush")) => true,
|
||||
Some(_) => return Err(bad(C, "style must be \"pencil\" or \"brush\"")),
|
||||
};
|
||||
// The undo step's name: a stroke painted with a brush is a Paintbrush stroke, whatever its style.
|
||||
let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" };
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) {
|
||||
None | Some(Some("end")) => false,
|
||||
Some(Some("start")) => true,
|
||||
Some(_) => return Err(bad(C, "extend end must be \"start\" or \"end\"")),
|
||||
};
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
let target = brush_target(&s.doc()?.doc, id);
|
||||
@@ -488,12 +496,23 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let samples = samples_param(p, "points", C)?;
|
||||
let size = ranged(p, "size", 10.0, SIZES, C)?;
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
if !(-180.0..=180.0).contains(&angle) {
|
||||
return Err(bad(C, "`angle` must be from -180 to 180 degrees"));
|
||||
}
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
if !angle.is_finite() || !roundness.is_finite() {
|
||||
return Err(bad(C, "angle and roundness must be finite"));
|
||||
if !(0.0..=100.0).contains(&roundness) {
|
||||
return Err(bad(C, "`roundness` must be from 0 to 100%"));
|
||||
}
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?),
|
||||
};
|
||||
if fidelity.is_some_and(|f| !(vectorcraft_tools::draw2::MIN_FIDELITY..=100.0).contains(&f)) {
|
||||
return Err(bad(C, "`fidelity` must be from 0.01 to 100 pt"));
|
||||
}
|
||||
let angle = angle.clamp(-180.0, 180.0);
|
||||
let roundness = roundness.clamp(0.0, 100.0);
|
||||
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
@@ -515,13 +534,6 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
let reach = pressure.as_ref().map_or(size, |(_, v)| size + v);
|
||||
// With `fidelity` (pt), the brush follows the stroke fitted by [`fit_freehand`], as a Pencil
|
||||
// stroke is fitted. Without it, or when the fitted stroke has no length (a short stroke back to
|
||||
// its start), the brush follows every point.
|
||||
let fidelity = match p.get("fidelity") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(number_or(p, "fidelity", 0.0, C)?.clamp(vectorcraft_tools::draw2::MIN_FIDELITY, 100.0)),
|
||||
};
|
||||
let spine = |tol: Option<f64>| {
|
||||
let path = match tol {
|
||||
Some(tol) => PathData::single(fit_freehand(&pts, tol, false)),
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mod
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while the document links a JavaScript file
Line truncated
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is written from), is refused, before the folder is made or any file is written, while t
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -241,7 +241,8 @@ struct RasterOptions {
|
||||
width: Option<f64>,
|
||||
/// The height of each file in pixels (wins over `ppi` and `scale`).
|
||||
height: Option<f64>,
|
||||
quality: Option<u8>,
|
||||
/// JPEG and lossy WebP quality, read by [`RasterOptions::quality`].
|
||||
quality: Option<Value>,
|
||||
background: Option<Value>,
|
||||
anti_alias: Option<String>,
|
||||
interlaced: Option<bool>,
|
||||
@@ -281,6 +282,19 @@ fn clamped_ppi(ppi: f64) -> f64 {
|
||||
}
|
||||
|
||||
impl RasterOptions {
|
||||
/// `quality` as given: `None` when absent or null, else a whole number 0–255 (JPEG caps it at
|
||||
/// 100; WebP refuses more than 100), or an error naming it.
|
||||
fn quality(&self) -> Result<Option<u8>> {
|
||||
match &self.quality {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.and_then(|q| u8::try_from(q).ok())
|
||||
.map(Some)
|
||||
.ok_or_else(|| bad(C, format!("quality must be a whole number from 0 to 100, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -311,7 +325,8 @@ impl RasterOptions {
|
||||
},
|
||||
anti_alias: self.anti_alias.as_deref().map(anti_alias).transpose().map_err(|e| bad(C, e))?.unwrap_or_default(),
|
||||
interlaced: self.interlaced.unwrap_or(false),
|
||||
quality: self.quality.unwrap_or(90).min(100),
|
||||
quality: self.quality()?.unwrap_or(90).min(100),
|
||||
webp_lossless: self.lossless.unwrap_or(true),
|
||||
jpeg: JpegOptions {
|
||||
color_model,
|
||||
method: parse(self.method.as_deref(), jpeg::Method::from_id, "method", "baseline, optimized or progressive")?,
|
||||
@@ -1136,6 +1151,11 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"psd" => RasterFormat::Psd,
|
||||
_ => RasterFormat::WebP,
|
||||
};
|
||||
if format == RasterFormat::WebP
|
||||
&& let Some(q) = o.quality()?.filter(|q| *q > 100)
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
@@ -1182,9 +1202,6 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
_ => return Err(bad(C, format!("no encoder for {} yet", f.label))),
|
||||
|
||||
@@ -206,11 +206,15 @@ const LOSSLESS: FormatOption = FormatOption {
|
||||
name: "lossless",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "lossless WebP; false asks for lossy, which isn't available yet (written lossless, with a warning)",
|
||||
description: "lossless WebP (every pixel kept exactly); false writes lossy WebP at quality: a smaller file that loses some detail",
|
||||
};
|
||||
|
||||
const WEBP_QUALITY: FormatOption =
|
||||
FormatOption { name: "quality", ty: "integer", default: "90", description: "lossy quality 0–100 (for when lossy WebP is available)" };
|
||||
const WEBP_QUALITY: FormatOption = FormatOption {
|
||||
name: "quality",
|
||||
ty: "integer",
|
||||
default: "90",
|
||||
description: "lossy WebP quality 0–100 (with lossless false; higher keeps more detail in a larger file; more than 100 is refused)",
|
||||
};
|
||||
|
||||
/// The options of the palette formats (PNG-8, GIF).
|
||||
const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
|
||||
@@ -135,26 +135,25 @@ fn formats_list_use_artboards() {
|
||||
assert!(opts("vectorcraft").get("useArtboards").is_none());
|
||||
}
|
||||
|
||||
/// An export's reply gives what the file loses before its notes on the options, whatever order
|
||||
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
|
||||
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
|
||||
/// order.
|
||||
/// An export's reply gives what the file loses before its notes on the options: the type the
|
||||
/// export drew in the fallback font comes before the note on an option WebP doesn't read. With
|
||||
/// only notes on the options, they keep their order.
|
||||
#[test]
|
||||
fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
|
||||
let unused = "`interlaced` was not used: WebP files don't read it";
|
||||
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
|
||||
};
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "interlaced": true})), [unused]);
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
|
||||
let w = warnings(&mut s, json!({"format": "webp", "interlaced": true}));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
|
||||
assert_eq!(w[1], lossy);
|
||||
assert_eq!(w[1], unused);
|
||||
// document.serialize gives them in the same order.
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "interlaced": true})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
|
||||
@@ -546,20 +546,19 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
|
||||
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
|
||||
}
|
||||
|
||||
/// What a later file loses comes before a note on the options that an earlier file gave: the
|
||||
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
|
||||
/// fit.
|
||||
/// What a later file loses comes before a note on the options: the second artboard's WebP says
|
||||
/// its type doesn't fit, before the note on the row's option that WebP doesn't read.
|
||||
#[test]
|
||||
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
let area = json!({"width": 30, "height": 8});
|
||||
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "interlaced": true}]}));
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("`formats[0].interlaced` was not used"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -53,41 +53,115 @@ fn text_export_writes_the_stories_in_stacking_order() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The chunk types of RIFF WebP file `file`, in order.
|
||||
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
|
||||
let mut chunks = Vec::new();
|
||||
let mut at = 12;
|
||||
while at + 8 <= file.len() {
|
||||
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
|
||||
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// The size and straight RGBA pixels of image file `file`.
|
||||
fn rgba(file: &[u8]) -> (u32, u32, Vec<u8>) {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
let (w, h) = img.dimensions();
|
||||
(w, h, img.to_rgba8())
|
||||
}
|
||||
|
||||
/// A 120 × 80 pt document filled with a grid of rectangles in 96 colors.
|
||||
fn varied_art() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 120, "height": 80})).unwrap();
|
||||
for row in 0..8 {
|
||||
for col in 0..12 {
|
||||
s.execute("shape.rectangle", &json!({"x": col * 10, "y": row * 10, "width": 10, "height": 10})).unwrap();
|
||||
let color = format!("#{:02x}{:02x}{:02x}", col * 21, row * 32, (col * 7 + row * 23) % 256);
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_is_lossless_and_says_so_when_lossy_is_asked_for() {
|
||||
fn webp_is_lossless_by_default_and_lossy_when_asked() {
|
||||
let mut s = varied_art();
|
||||
let export = |s: &mut Session, p: Value| -> (Vec<u8>, Value) {
|
||||
let r = s.execute("document.export", &merge(json!({"format": "webp", "background": "white"}), p)).unwrap();
|
||||
(b64(&r), r["warnings"].clone())
|
||||
};
|
||||
let (lossless, warnings) = export(&mut s, json!({}));
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
assert_eq!(warnings, json!([]));
|
||||
// Quality doesn't change a lossless file.
|
||||
assert_eq!(export(&mut s, json!({"lossless": true, "quality": 10})).0, lossless);
|
||||
|
||||
let (lossy, warnings) = export(&mut s, json!({"lossless": false}));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8 "], "opaque art is a plain lossy file");
|
||||
assert_eq!(warnings, json!([]), "no note: the file is lossy");
|
||||
assert_eq!(export(&mut s, json!({"lossless": false, "quality": 90})).0, lossy, "quality 90 by default");
|
||||
// At quality 90 each channel stays within 4 levels of the exact pixels on average.
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
assert_eq!((w, h), (120, 80));
|
||||
let diff: u64 = exact.iter().zip(&near).map(|(a, b)| u64::from(a.abs_diff(*b))).sum();
|
||||
let mean = diff as f64 / exact.len() as f64;
|
||||
assert!(mean <= 4.0, "mean difference {mean}");
|
||||
// Lower quality, smaller file.
|
||||
let low = export(&mut s, json!({"lossless": false, "quality": 10})).0;
|
||||
let high = export(&mut s, json!({"lossless": false, "quality": 95})).0;
|
||||
assert_eq!(webp_chunks(&low), [*b"VP8 "]);
|
||||
assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len());
|
||||
for q in [0, 100] {
|
||||
assert_eq!(webp_chunks(&export(&mut s, json!({"lossless": false, "quality": q})).0), [*b"VP8 "], "quality {q}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_webp_keeps_translucent_pixels() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 30, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "webp"})).unwrap();
|
||||
let file = b64(&r);
|
||||
assert_eq!((&file[..4], &file[8..12], &file[12..16]), (&b"RIFF"[..], &b"WEBP"[..], &b"VP8L"[..]), "lossless bitstream");
|
||||
assert_eq!(r["warnings"], json!([]));
|
||||
let r = s.execute("document.export", &json!({"format": "webp", "lossless": false, "quality": 60, "background": "black"})).unwrap();
|
||||
assert_eq!(&b64(&r)[12..16], b"VP8L");
|
||||
assert!(r["warnings"][0].as_str().unwrap().contains("lossless"), "{r}");
|
||||
assert_eq!(
|
||||
craft_image_codecs::decode(&b64(&r))
|
||||
.map(|__cimg| {
|
||||
let (__w, __h) = __cimg.dimensions();
|
||||
match (__cimg.layout(), __cimg.sample_type()) {
|
||||
(craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
(craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
|
||||
image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
|
||||
}
|
||||
_ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.to_rgba8()
|
||||
.get_pixel(29, 19)
|
||||
.0,
|
||||
[0, 0, 0, 255]
|
||||
);
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
let file = |s: &mut Session, lossless: bool| b64(&s.execute("document.export", &json!({"format": "webp", "lossless": lossless})).unwrap());
|
||||
let (lossless, lossy) = (file(&mut s, true), file(&mut s, false));
|
||||
assert_eq!(webp_chunks(&lossy), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let ((w, h, exact), (lw, lh, near)) = (rgba(&lossless), rgba(&lossy));
|
||||
assert_eq!((lw, lh), (w, h));
|
||||
let at = |px: &[u8], x: u32, y: u32| -> [u8; 4] {
|
||||
let i = 4 * (y * w + x) as usize;
|
||||
[px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||||
};
|
||||
// The alpha is written exactly: half covered under the rectangle, clear past it.
|
||||
let alphas = |px: &[u8]| px.chunks(4).map(|p| p[3]).collect::<Vec<u8>>();
|
||||
assert_eq!(alphas(&near), alphas(&exact));
|
||||
assert!((120..=135).contains(&at(&near, 5, 5)[3]), "{:?}", at(&near, 5, 5));
|
||||
assert_eq!(at(&near, 28, 10)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_quality_out_of_its_range_is_refused() {
|
||||
let mut s = varied_art();
|
||||
for q in [json!(101), json!(255), json!(256), json!(-1), json!(60.5), json!("high"), json!(true)] {
|
||||
let p = json!({"format": "webp", "lossless": false, "quality": q});
|
||||
let e = s.execute("document.export", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("quality"), "{q}: {e}");
|
||||
// In Export for Screens too, in a row or in the format's settings.
|
||||
let row = json!({"formats": [{"format": "webp", "lossless": false, "quality": q}]});
|
||||
assert!(s.execute("document.exportForScreens", &row).is_err(), "{q}");
|
||||
let settings = json!({"formats": [{"format": "webp"}], "settings": {"webp": {"lossless": false, "quality": q}}});
|
||||
assert!(s.execute("document.exportForScreens", &settings).is_err(), "{q}");
|
||||
}
|
||||
// A lossless file refuses it as well: the value is not a WebP quality.
|
||||
assert!(s.execute("document.export", &json!({"format": "webp", "quality": 101})).is_err());
|
||||
let r = s.execute("document.exportForScreens", &json!({"formats": [{"format": "webp", "lossless": false, "quality": 100}]})).unwrap();
|
||||
let file = b64(&r["files"][0]);
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -649,6 +649,7 @@ pub const UNCHECKED: &[&str] = &[
|
||||
"transparency.setOpacityMask",
|
||||
"transparency.unlinkOpacityMask",
|
||||
"type.pathOptions",
|
||||
"webExport.optimizeToFileSize",
|
||||
"webExport.presets.save",
|
||||
"webExport.settings",
|
||||
];
|
||||
@@ -663,18 +664,28 @@ fn pdf_option_tree() -> Value {
|
||||
tree
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `key`, a key with the objects it is in (`marks.ofset`),
|
||||
/// when a key those objects take is near it: `near`, written the same way (`marks.offset`). Each
|
||||
/// is one value of the message, so a catalog can match the message and translate it.
|
||||
fn misspelled(id: &str, key: &str, near: &str) -> crate::EngineError {
|
||||
bad(id, format!("unknown parameter `{key}`; did you mean `{near}`?"))
|
||||
}
|
||||
|
||||
/// `given`, the object at `within` (`marks.`), has only keys of `schema`, the objects inside it too.
|
||||
fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Value>, schema: &serde_json::Map<String, Value>) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
match (schema.get(key), value) {
|
||||
(None, _) => {
|
||||
let keys: Vec<&str> = schema.keys().map(String::as_str).collect();
|
||||
let why = match nearest(key, &keys) {
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
let near = nearest(key, &keys);
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => {
|
||||
let (object, keys) = (within.trim_end_matches('.'), keys.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
_ => {}
|
||||
@@ -691,14 +702,11 @@ fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
));
|
||||
let key = format!("{within}{}", shown_key(key));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}{near}")),
|
||||
None => bad(id, format!("unknown parameter `{key}`; {why_not}")),
|
||||
});
|
||||
}
|
||||
if let (Some(Value::Object(schema)), Value::Object(value)) = (trees.get(key), value) {
|
||||
check_option_tree(id, &format!("{within}{key}."), value, schema)?;
|
||||
@@ -797,12 +805,15 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
let formats = screen_formats();
|
||||
for (format, options) in settings {
|
||||
if !formats.contains(&format.as_str()) {
|
||||
let why = match nearest(format, &formats) {
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
let near = nearest(format, &formats);
|
||||
let key = format!("{within}settings.{}", shown_key(format));
|
||||
return Err(match near {
|
||||
Some(near) => misspelled(id, &key, &format!("{within}settings.{near}")),
|
||||
None => {
|
||||
let (object, keys) = (format!("{within}settings"), formats.join(", "));
|
||||
bad(id, format!("unknown parameter `{key}`; `{object}` takes: {keys}"))
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
check_option_keys(id, &format!("{within}settings.{format}."), options, &keys, NO_FORMAT, trees)?;
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Setup",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks knock out; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
|
||||
has_doc,
|
||||
setup
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Print Preview",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
"{preset?: name (as print.setup's: its settings instead of the document's), settings?: {…settings of print.setup} (over the document's or the preset's)} → {pages (copies included), sheets: [{artboard (0-based; null with artboards ignored), tile? (1-based), ink? (separations), width, height (pt, the page), orientation, scale: [width %, height %], transform: [a, b, c, d, e, f] (document space → the page, pt, y down), area: [x0, y0, x1, y1] (the document region the page prints), trim: [x0, y0, x1, y1] (the artboard on the page; with copies per sheet, the box around every copy's), copies?: [[x0, y0, x1, y1]…] (copies per sheet: each copy's artboard on the page, across then down)}] (one copy, in order), tiles: [{artboard, columns, rows, printed: [1-based tiles], tiles: [[x0, y0, x1, y1]…] (document space)}], inks: [{name, spot, print, frequency, angle}] (separations: the plates), documentInks: [{name, spot, print, frequency, angle, convertToProcess?: true (a spot ink printing as process, with no plate)}] (separations: every ink of the document), warnings (art larger than the imageable area, type that prints in the fallback font, type that doesn't fit its frame, options not applied yet…), settings} without printing",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
|
||||
@@ -66,11 +66,13 @@ impl FlattenReport {
|
||||
lowest
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let name = r.name.map(|name| format!(" ({name})")).unwrap_or_default();
|
||||
format!(
|
||||
"raster effects on object {}{name}: requested {:.1} ppi, achieved {:.1} ppi due to the 64 million pixel cap",
|
||||
r.id.0, self.requested_ppi, r.achieved_ppi
|
||||
)
|
||||
// The id and the name are one value of the message, so a catalog can match it.
|
||||
let object = match r.name {
|
||||
Some(name) => format!("{} ({name})", r.id.0),
|
||||
None => r.id.0.to_string(),
|
||||
};
|
||||
let (requested, achieved) = (self.requested_ppi, r.achieved_ppi);
|
||||
format!("raster effects on object {object}: requested {requested:.1} ppi, achieved {achieved:.1} ppi due to the 64 million pixel cap")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -127,4 +129,23 @@ mod tests {
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains(&format!("object {}", original.id.0)), "{:?}", warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warning_names_the_object_by_its_id_and_its_name() {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.raster_effects_ppi = 300.0;
|
||||
let mut named = Node::group(NodeId(7), vec![]);
|
||||
named.name = Some("Logo".into());
|
||||
let unnamed = Node::group(NodeId(8), vec![]);
|
||||
let mut report = FlattenReport::new(Which::All, &doc);
|
||||
report.record(&named, &image(72.0));
|
||||
report.record(&unnamed, &image(150.0));
|
||||
assert_eq!(
|
||||
report.warnings(),
|
||||
[
|
||||
"raster effects on object 7 (Logo): requested 300.0 ppi, achieved 72.0 ppi due to the 64 million pixel cap",
|
||||
"raster effects on object 8: requested 300.0 ppi, achieved 150.0 ppi due to the 64 million pixel cap",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Swatch",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
"{name?, color? | colors?: [colour | {swatch, tint?}] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused; `{swatch, tint}` is the paint paint.setFill gives, so a tint of a global or spot color becomes a tint swatch) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. A gradient swatch keeps the gradient's aspect (with or without start/end) and holds no link to the swatch its gradient came from, and a pattern swatch holds the pattern untransformed. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}",
|
||||
has_doc,
|
||||
swatch_new
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Color Group",
|
||||
["Window", "Swatches"],
|
||||
None,
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
"{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour | {swatch, tint?}] (added as new swatches; #rrggbbaa and #rgba are refused; `{swatch, tint}` below 100% of a global or spot color adds a tint swatch, \"Name 40%\", linked to it, and any other `{swatch}` its color), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}",
|
||||
has_doc,
|
||||
swatch_new_group
|
||||
),
|
||||
@@ -146,9 +146,11 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = |c: Color| if mode.is_some() { c } else { super::paint::new_color(s, p, c) };
|
||||
let cs: Vec<Paint> = cs
|
||||
.iter()
|
||||
.map(|c| color_value(c).map(|c| Paint::solid(stored(c))))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(|| bad(C, "bad colour in `colors`"))?;
|
||||
.map(|c| match swatch_entry(s, c, C)? {
|
||||
Some(paint) => Ok(paint),
|
||||
None => color_value(c).map(|c| Paint::solid(stored(c))).ok_or_else(|| bad(C, "bad colour in `colors`")),
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if cs.is_empty() {
|
||||
return Err(bad(C, "`colors` is empty"));
|
||||
}
|
||||
@@ -216,6 +218,16 @@ fn swatch_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": names[0], "names": names }))
|
||||
}
|
||||
|
||||
/// A `colors` entry of `swatch.new` or `swatch.newGroup` that names a color swatch,
|
||||
/// `{swatch, tint?}`: the paint `paint.setFill {swatch, tint}` applies (a tint of a global or spot
|
||||
/// color stays linked to it). `None` for an entry without `swatch`.
|
||||
fn swatch_entry(s: &Session, v: &Value, cmd: &str) -> Result<Option<Paint>> {
|
||||
let Some(name) = v.get("swatch") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(cmd, format!("`swatch` in `colors` must be a swatch name, not {name}")))?;
|
||||
let tint = super::paint::tint_param(v, cmd)?;
|
||||
super::paint::swatch_solid(&s.doc()?.doc, name, tint).map(Some).map_err(|e| bad(cmd, e))
|
||||
}
|
||||
|
||||
/// A gradient or pattern `paint`, parsed from the paint params `p`, as a new or edited swatch
|
||||
/// stores it.
|
||||
fn stored_paint(paint: Paint, p: &Value) -> Paint {
|
||||
@@ -475,10 +487,20 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut names = str_list(p, "swatches");
|
||||
super::paint::check_keep_model(p, C)?;
|
||||
check_switches(p, &["fromArtwork", "toGlobal", "includeTints"], C)?;
|
||||
let colors: Vec<Color> = p
|
||||
// A `{swatch, tint}` entry below 100% becomes a tint swatch linked to its base; any other
|
||||
// entry becomes a process color swatch.
|
||||
let colors: Vec<Paint> = p
|
||||
.get("colors")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|v| match swatch_entry(s, v, C)? {
|
||||
Some(paint @ Paint::Solid { swatch: Some(_), tint, .. }) if tint < 1.0 => Ok(paint),
|
||||
Some(paint) => paint.color().map(Paint::solid).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
None => color_value(v).map(|c| Paint::solid(super::paint::new_color(s, p, c))).ok_or_else(|| bad(C, format!("bad color {v}"))),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let from_art = bool_or(p, "fromArtwork", false);
|
||||
@@ -486,15 +508,15 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tints = bool_or(p, "includeTints", false);
|
||||
let requested = name_param(p, "name");
|
||||
let (name, members, linked) = s.edit("New Color Group", |d, sel| {
|
||||
// New swatches: (colour, global).
|
||||
let mut new: Vec<(Color, bool)> = colors.iter().map(|c| (*c, false)).collect();
|
||||
// New swatches: (paint, global).
|
||||
let mut new: Vec<(Paint, bool)> = colors.iter().map(|c| (c.clone(), false)).collect();
|
||||
if from_art {
|
||||
if sel.objects.is_empty() {
|
||||
return Err(bad(C, "select artwork to make a group of its colours"));
|
||||
}
|
||||
let mut art = vec![];
|
||||
artwork_colors(d, &sel.objects, tints, &mut names, &mut art);
|
||||
new.extend(art.into_iter().map(|c| (c, to_global)));
|
||||
new.extend(art.into_iter().map(|c| (Paint::solid(c), to_global)));
|
||||
}
|
||||
let name = d.free_swatch_name(requested.as_deref().unwrap_or("Color Group"));
|
||||
// Colour groups hold solid colours only.
|
||||
@@ -505,12 +527,13 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut free = d.free_swatch_names();
|
||||
free.insert(&name);
|
||||
group.swatches.iter().for_each(|sw| free.insert(&sw.name));
|
||||
for (c, global) in new {
|
||||
let nm = free.take(&color_name(c));
|
||||
if global {
|
||||
for (paint, global) in new {
|
||||
// A tint swatch is named "Name 40%", a colour after its values.
|
||||
let nm = free.take_new(&paint);
|
||||
if global && let Some(c) = paint.color() {
|
||||
links.push((c, nm.clone()));
|
||||
}
|
||||
group.swatches.push(Swatch { name: nm, paint: Paint::solid(c), global, spot: false });
|
||||
group.swatches.push(Swatch { name: nm, paint, global, spot: false });
|
||||
}
|
||||
let members: Vec<String> = group.swatches.iter().map(|w| w.name.clone()).collect();
|
||||
d.swatch_groups.push(group);
|
||||
|
||||
@@ -45,6 +45,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.optimizeToFileSize",
|
||||
"Optimize to File Size",
|
||||
[],
|
||||
None,
|
||||
"{desiredK: the desired file size in K (1024 bytes; above 0, at most 1048576), startWith?: current (default: the format given, its JPEG quality or GIF/PNG-8 colors lowered; GIF then takes lossy 100)|auto (GIF for art with transparency or at most 256 colors (blended over the matte without transparency), else JPEG; the other one when the first can't reach the size and the art is opaque), use?: allSlices (default: the image, or the image slices' files together)|eachSlice (every image slice's file)|currentSlice (the `slice` given, else the selected image slice, else the first), slice?: n (1-based, from slice.list), preset?, …the settings of document.exportForWeb} the settings whose files fit in the size, searched by encoding at most 32 trial settings (each one encodes every image it measures); slices share one setting, which every scope changes → {targetBytes, achieved (false: no setting tried fits, and settings are the smallest one found), bytes (as use measures them), format, settings, trials, images, warnings}; writes nothing and changes no remembered setting",
|
||||
has_doc,
|
||||
optimize_to_file_size
|
||||
),
|
||||
cmd!(
|
||||
query "webExport.settings",
|
||||
"Save for Web Settings",
|
||||
@@ -1054,6 +1063,297 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------- Optimize to File Size ----------
|
||||
|
||||
/// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image
|
||||
/// it measures once.
|
||||
pub const OPTIMIZE_TRIALS: usize = 32;
|
||||
/// The largest desired file size, in K (1 GiB).
|
||||
pub const MAX_DESIRED_K: f64 = 1_048_576.0;
|
||||
|
||||
/// Where Optimize to File Size starts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StartWith {
|
||||
/// The current format, with its JPEG quality or palette colors lowered.
|
||||
Current,
|
||||
/// GIF or JPEG, by the image's content.
|
||||
Auto,
|
||||
}
|
||||
|
||||
/// The pixels `px` (`[x0, y0, x1, y1]`) of `r` as an image: borrowed when `px` is the whole render,
|
||||
/// else a copy.
|
||||
fn file_pixels(r: &WebRender, px: [u32; 4]) -> std::borrow::Cow<'_, [u8]> {
|
||||
if px == [0, 0, r.width, r.height] { std::borrow::Cow::Borrowed(r.rgba.as_slice()) } else { std::borrow::Cow::Owned(crop(r, px)) }
|
||||
}
|
||||
|
||||
/// The settings Optimize to File Size found.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SizeFit {
|
||||
pub settings: WebSettings,
|
||||
/// The size the settings give the measured images.
|
||||
pub bytes: usize,
|
||||
/// Whether `bytes` is within the target.
|
||||
pub achieved: bool,
|
||||
/// The trial settings encoded.
|
||||
pub trials: usize,
|
||||
}
|
||||
|
||||
/// The files a search measures and the trials it has left.
|
||||
struct Trials<'a> {
|
||||
doc: &'a Document,
|
||||
r: &'a WebRender,
|
||||
/// The pixels (`[x0, y0, x1, y1]`) of each file in `r`.
|
||||
files: &'a [[u32; 4]],
|
||||
/// Measure the largest file (else the files together).
|
||||
each: bool,
|
||||
left: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Trials<'_> {
|
||||
/// The size `s` gives the files, encoded one at a time; `None` when no trial is left.
|
||||
fn size(&mut self, s: &WebSettings) -> std::result::Result<Option<usize>, String> {
|
||||
if self.left == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
self.left -= 1;
|
||||
self.used += 1;
|
||||
let mut out = 0usize;
|
||||
for &px in self.files {
|
||||
let n = optimize(self.doc, &file_pixels(self.r, px), px[2] - px[0], px[3] - px[1], s)?.bytes.len();
|
||||
out = if self.each { out.max(n) } else { out.saturating_add(n) };
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `(settings, bytes)` of a trial.
|
||||
pub type Trial = (WebSettings, usize);
|
||||
|
||||
/// Keep `(s, n)` in `smallest` when it is the smallest trial so far.
|
||||
fn keep_smallest(smallest: &mut Option<Trial>, s: WebSettings, n: usize) {
|
||||
if smallest.as_ref().is_none_or(|(_, b)| n < *b) {
|
||||
*smallest = Some((s, n));
|
||||
}
|
||||
}
|
||||
|
||||
/// The values [`highest_within`] measures spread over its range before it narrows a step.
|
||||
pub const OPTIMIZE_SAMPLES: u16 = 6;
|
||||
|
||||
/// Measures the size a setting gives; `None` when no trial is left.
|
||||
pub type MeasureSize<'a> = dyn FnMut(&WebSettings) -> std::result::Result<Option<usize>, String> + 'a;
|
||||
|
||||
/// The highest value in `lo..hi` that `set` gives `start` whose size is within `target`, when the
|
||||
/// value `hi` is over it. A lower value can give a larger file, so the search measures up to
|
||||
/// [`OPTIMIZE_SAMPLES`] values spread over the range, from `hi - 1` down, stops at the first that
|
||||
/// fits, and halves the step between it and the measured value above it, keeping the highest value
|
||||
/// measured within `target`. `None` when no value measured fits or no trial is left; the trials over
|
||||
/// the target go to `smallest`.
|
||||
pub fn highest_within(
|
||||
size: &mut MeasureSize,
|
||||
start: &WebSettings,
|
||||
(lo, hi): (u16, u16),
|
||||
set: fn(&mut WebSettings, u16),
|
||||
target: usize,
|
||||
smallest: &mut Option<Trial>,
|
||||
) -> std::result::Result<Option<Trial>, String> {
|
||||
let with = |v: u16| {
|
||||
let mut s = start.clone();
|
||||
set(&mut s, v);
|
||||
s
|
||||
};
|
||||
if lo >= hi {
|
||||
return Ok(None);
|
||||
}
|
||||
let span = u32::from(hi - lo);
|
||||
let samples = u32::from(OPTIMIZE_SAMPLES).min(span);
|
||||
let (mut above, mut found) = (hi, None);
|
||||
for i in (0..samples).rev() {
|
||||
let step = if samples == 1 { 0 } else { (span - 1) * i / (samples - 1) };
|
||||
let v = lo.saturating_add(u16::try_from(step).unwrap_or(0));
|
||||
let s = with(v);
|
||||
let Some(n) = size(&s)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
found = Some((v, (s, n)));
|
||||
break;
|
||||
}
|
||||
keep_smallest(smallest, s, n);
|
||||
above = v;
|
||||
}
|
||||
let Some((mut lo, mut best)) = found else { return Ok(None) };
|
||||
let mut hi = above;
|
||||
while hi - lo > 1 {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let s = with(mid);
|
||||
let Some(n) = size(&s)? else { break };
|
||||
if n <= target {
|
||||
lo = mid;
|
||||
best = (s, n);
|
||||
} else {
|
||||
keep_smallest(smallest, s, n);
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
Ok(Some(best))
|
||||
}
|
||||
|
||||
/// Sets the JPEG quality, for [`highest_within`].
|
||||
pub fn set_quality(s: &mut WebSettings, v: u16) {
|
||||
s.quality = u8::try_from(v).unwrap_or(100);
|
||||
}
|
||||
|
||||
/// Sets the palette colors, for [`highest_within`].
|
||||
pub fn set_colors(s: &mut WebSettings, v: u16) {
|
||||
s.colors = v;
|
||||
}
|
||||
|
||||
/// The best settings of `start`'s format within `target`: `start` when it fits, else the highest
|
||||
/// JPEG quality or the most palette colors [`highest_within`] finds that fit, and for GIF, when none
|
||||
/// is found, lossy 100 with the most colors that fit. When nothing tried fits, the smallest trial, not achieved.
|
||||
/// `None` when no trial is left.
|
||||
fn search_format(t: &mut Trials, start: &WebSettings, target: usize) -> std::result::Result<Option<SizeFit>, String> {
|
||||
let fit = |(settings, bytes): Trial, achieved: bool| SizeFit { settings, bytes, achieved, trials: 0 };
|
||||
let Some(n) = t.size(start)? else { return Ok(None) };
|
||||
if n <= target {
|
||||
return Ok(Some(fit((start.clone(), n), true)));
|
||||
}
|
||||
let mut smallest = Some((start.clone(), n));
|
||||
let found = match start.format {
|
||||
WebFormat::Jpg => highest_within(&mut |s: &WebSettings| t.size(s), start, (1, u16::from(start.quality)), set_quality, target, &mut smallest)?,
|
||||
WebFormat::Gif | WebFormat::Png8 => {
|
||||
match highest_within(&mut |s: &WebSettings| t.size(s), start, (2, start.colors), set_colors, target, &mut smallest)? {
|
||||
None if start.format == WebFormat::Gif && start.lossy < 100 => {
|
||||
let lossy = WebSettings { lossy: 100, ..start.clone() };
|
||||
match t.size(&lossy)? {
|
||||
Some(n) if n <= target => Some((lossy, n)),
|
||||
Some(n) => {
|
||||
keep_smallest(&mut smallest, lossy.clone(), n);
|
||||
highest_within(&mut |s: &WebSettings| t.size(s), &lossy, (2, lossy.colors), set_colors, target, &mut smallest)?
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
WebFormat::Png24 => None,
|
||||
};
|
||||
Ok(match (found, smallest) {
|
||||
(Some(f), _) => Some(fit(f, true)),
|
||||
(None, Some(s)) => Some(fit(s, false)),
|
||||
(None, None) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The format Auto Select GIF/JPEG starts with, and whether the files (`[x0, y0, x1, y1]` of `r`)
|
||||
/// are opaque: GIF for files with transparent pixels (when `transparency` keeps them) or at most
|
||||
/// 256 colors, else JPEG. The colors counted are the ones the files are written with: without
|
||||
/// `transparency`, the pixels blended over `matte`.
|
||||
fn auto_format(r: &WebRender, files: &[[u32; 4]], transparency: bool, matte: [u8; 3]) -> (WebFormat, bool) {
|
||||
let stride = r.width as usize * 4;
|
||||
let row =
|
||||
move |y: u32, x0: u32, x1: u32| r.rgba.get(y as usize * stride + x0 as usize * 4..y as usize * stride + x1 as usize * 4).unwrap_or_default();
|
||||
let pixels = || files.iter().flat_map(move |&[x0, y0, x1, y1]| (y0..y1).flat_map(move |y| row(y, x0, x1).as_chunks::<4>().0.iter()));
|
||||
let opaque = !transparency || pixels().all(|p| p[3] == 255);
|
||||
if !opaque {
|
||||
return (WebFormat::Gif, false);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
// An opaque pixel blends to itself.
|
||||
let few = pixels().all(|p| {
|
||||
seen.insert(flatten(p, matte).next().unwrap_or_default());
|
||||
seen.len() <= 256
|
||||
});
|
||||
(if few { WebFormat::Gif } else { WebFormat::Jpg }, true)
|
||||
}
|
||||
|
||||
/// Optimize to File Size: the settings, from `s`, whose files (the pixels `[x0, y0, x1, y1]` of
|
||||
/// `r`) fit in `target` bytes, measured together, or with `each` the largest one. At most
|
||||
/// [`OPTIMIZE_TRIALS`] trial settings are encoded, and a trial encodes the files one at a time.
|
||||
pub fn optimize_to_size(
|
||||
doc: &Document,
|
||||
r: &WebRender,
|
||||
files: &[[u32; 4]],
|
||||
s: &WebSettings,
|
||||
start: StartWith,
|
||||
each: bool,
|
||||
target: usize,
|
||||
) -> std::result::Result<SizeFit, String> {
|
||||
let mut t = Trials { doc, r, files, each, left: OPTIMIZE_TRIALS, used: 0 };
|
||||
let with = |format: WebFormat| WebSettings { format, ..s.clone() };
|
||||
let found = match start {
|
||||
_ if files.is_empty() => None,
|
||||
StartWith::Current => search_format(&mut t, s, target)?,
|
||||
StartWith::Auto => {
|
||||
let (first, opaque) = auto_format(r, files, s.transparency, s.matte_rgb()?.unwrap_or([255; 3]));
|
||||
let other = if first == WebFormat::Gif { WebFormat::Jpg } else { WebFormat::Gif };
|
||||
match search_format(&mut t, &with(first), target)? {
|
||||
Some(a) if !a.achieved && opaque => match search_format(&mut t, &with(other), target)? {
|
||||
Some(b) if b.achieved || b.bytes < a.bytes => Some(b),
|
||||
_ => Some(a),
|
||||
},
|
||||
a => a,
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut best = found.ok_or("Optimize to File Size: there is no image to measure")?;
|
||||
best.trials = t.used;
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
fn optimize_to_file_size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const O: &str = "webExport.optimizeToFileSize";
|
||||
let k = p
|
||||
.get("desiredK")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|k| k.is_finite() && *k > 0.0 && *k <= MAX_DESIRED_K)
|
||||
.ok_or_else(|| bad(O, "give `desiredK`, the desired file size in K (1024 bytes): a number above 0 and at most 1048576"))?;
|
||||
let target = ((k * 1024.0).floor() as usize).max(1);
|
||||
let start = match p.get("startWith").map(Value::as_str) {
|
||||
None | Some(Some("current")) => StartWith::Current,
|
||||
Some(Some("auto")) => StartWith::Auto,
|
||||
Some(_) => return Err(bad(O, "`startWith` is `current` or `auto`")),
|
||||
};
|
||||
let scope = match p.get("use").map(Value::as_str) {
|
||||
None if p.get("slice").is_some() => "currentSlice",
|
||||
None => "allSlices",
|
||||
Some(Some(u @ ("allSlices" | "eachSlice" | "currentSlice"))) => u,
|
||||
Some(_) => return Err(bad(O, "`use` is `allSlices`, `eachSlice` or `currentSlice`")),
|
||||
};
|
||||
let slice = match p.get("slice").map(|v| v.as_u64().filter(|n| *n >= 1 && scope == "currentSlice")) {
|
||||
None => None,
|
||||
Some(Some(n)) => Some(n),
|
||||
Some(None) => return Err(bad(O, "`slice` is a slice number from `slice.list`, with `use: currentSlice`")),
|
||||
};
|
||||
let settings = s.web_settings(p).map_err(|e| bad(O, e))?;
|
||||
let st = s.doc()?;
|
||||
let doc = &st.doc;
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let r = render(doc, &settings).map_err(|e| bad(O, e))?;
|
||||
let warnings = undecoded(failed);
|
||||
let areas = doc.slice_layout();
|
||||
let selected = super::slices::selected_slices(doc, &st.selection);
|
||||
let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(O, e))?;
|
||||
let image_cells: Vec<&Cell> =
|
||||
cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).collect();
|
||||
let picked: Vec<&Cell> = match (scope, slice) {
|
||||
("currentSlice", Some(n)) => {
|
||||
let c = image_cells.iter().find(|c| c.area.number as u64 == n);
|
||||
vec![*c.ok_or_else(|| bad(O, format!("no slice {n} in the image (see slice.list)")))?]
|
||||
}
|
||||
("currentSlice", None) => {
|
||||
image_cells.iter().find(|c| c.area.id.is_some_and(|id| selected.contains(&id))).or(image_cells.first()).copied().into_iter().collect()
|
||||
}
|
||||
_ => image_cells,
|
||||
};
|
||||
let files: Vec<[u32; 4]> = if cells.is_empty() { vec![[0, 0, r.width, r.height]] } else { picked.iter().map(|c| c.px).collect() };
|
||||
let fit = optimize_to_size(doc, &r, &files, &settings, start, scope == "eachSlice", target).map_err(|e| bad(O, e))?;
|
||||
Ok(json!({
|
||||
"targetBytes": target, "achieved": fit.achieved, "bytes": fit.bytes, "format": fit.settings.format.id(),
|
||||
"settings": fit.settings.to_json(), "trials": fit.trials, "images": files.len(), "warnings": warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const S: &str = "webExport.settings";
|
||||
let base = if bool_or(p, "reset", false) { WebSettings::default() } else { s.last_web_settings() };
|
||||
|
||||
@@ -3313,6 +3313,26 @@ fn flare_ring_seed_moves_only_the_rings() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() {
|
||||
let mut s = session();
|
||||
let mut positions = Vec::new();
|
||||
for seed in [0, 1, 2, 5, 11, (1u64 << 53) - 1] {
|
||||
let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed});
|
||||
let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") };
|
||||
let ring = children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap();
|
||||
let center = ring.geometric_bounds().unwrap().center();
|
||||
assert!((20.0..=1020.0).contains(¢er.x), "seed {seed}: {center:?}");
|
||||
assert!((center.y - 30.0).abs() < 1e-9);
|
||||
positions.push(center.x);
|
||||
}
|
||||
assert!((positions[0] - positions[1]).abs() > 1.0, "neighboring small seeds visibly move the first ring: {positions:?}");
|
||||
let lo = positions[..5].iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let hi = positions[..5].iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}");
|
||||
}
|
||||
|
||||
/// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew.
|
||||
#[test]
|
||||
fn ellipse_with_four_anchors_is_the_live_ellipse() {
|
||||
|
||||
@@ -95,3 +95,50 @@ fn new_swatch_saves_several_colours_in_one_step() {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": []})).is_err());
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["nope"]})).is_err());
|
||||
}
|
||||
|
||||
/// The tint swatch a swatch named `name` is: (base, tint 0..1); none for any other swatch.
|
||||
fn tint_of(s: &Session, name: &str) -> Option<(String, f32)> {
|
||||
s.doc().unwrap().doc.swatch(name)?.tint_of().map(|(b, t)| (b.to_string(), t))
|
||||
}
|
||||
|
||||
/// `{swatch, tint}` entries of `swatch.new {colors}` and `swatch.newGroup {colors}` make tint
|
||||
/// swatches linked to their spot color, beside plain colors, in one undo step; the tints follow an
|
||||
/// edit of the spot color; a bad entry saves nothing.
|
||||
#[test]
|
||||
fn colors_entries_naming_a_spot_color_save_tint_swatches() {
|
||||
let mut s = session();
|
||||
s.execute("swatch.new", &json!({"name": "Ink", "color": "#0066cc", "spot": true})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("swatch.new", &json!({"colors": [{"swatch": "Ink", "tint": 60}, "#112233", {"swatch": "Ink", "tint": 30}]})).unwrap();
|
||||
let names = hexes(&r["names"]);
|
||||
assert_eq!(names, ["Ink 60%", "R=17 G=34 B=51", "Ink 30%"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
let (base, tint) = tint_of(&s, "Ink 60%").expect("a tint swatch");
|
||||
assert_eq!(base, "Ink");
|
||||
assert!((tint - 0.6).abs() < 1e-6, "{tint}");
|
||||
assert!(tint_of(&s, "R=17 G=34 B=51").is_none());
|
||||
let r = s.execute("swatch.newGroup", &json!({"name": "Guide", "colors": [{"swatch": "Ink", "tint": 45}, "#445566", {"swatch": "Ink"}]})).unwrap();
|
||||
let members = hexes(&r["swatches"]);
|
||||
assert_eq!(members[0], "Ink 45%");
|
||||
assert_eq!(tint_of(&s, "Ink 45%").map(|(b, _)| b).as_deref(), Some("Ink"));
|
||||
assert!(members[1..].iter().all(|m| tint_of(&s, m).is_none()), "a color and the full spot color are process copies: {members:?}");
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let full = d.swatch(&members[2]).unwrap();
|
||||
assert!(!full.spot && !full.global, "{full:?}");
|
||||
// The tint swatches follow an edit of the spot color.
|
||||
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#cc0000"})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let ink = d.global_color("Ink").unwrap();
|
||||
for name in ["Ink 60%", "Ink 45%"] {
|
||||
let w = d.swatch(name).unwrap();
|
||||
let t = w.tint_of().unwrap().1;
|
||||
assert_eq!(w.paint.color().map(|c| c.to_hex()), Some(ink.tinted(t).to_hex()), "{name}");
|
||||
}
|
||||
// A missing swatch, a tint of a process color or a tint that is not a number saves nothing.
|
||||
let count = s.doc().unwrap().doc.swatches_iter().count();
|
||||
for bad in [json!({"swatch": "Nope", "tint": 50}), json!({"swatch": "R=17 G=34 B=51", "tint": 50}), json!({"swatch": "Ink", "tint": "half"})] {
|
||||
assert!(s.execute("swatch.new", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
assert!(s.execute("swatch.newGroup", &json!({"colors": ["#010203", bad]})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc.swatches_iter().count(), count);
|
||||
}
|
||||
@@ -86,8 +86,57 @@ fn blob_tip_zero_and_invalid_values_are_safe() {
|
||||
p[key] = value;
|
||||
assert!(s.execute("path.blob", &p).is_err(), "{key}: {p}");
|
||||
}
|
||||
s.execute("path.blob", &json!({"points": [[100, 200], [300, 200]], "angle": 1e300, "roundness": -1e300, "merge": false})).unwrap();
|
||||
assert!(paths(&s)[1].1.control_bounds().unwrap().height().is_finite());
|
||||
let stroke = json!({"points": [[100, 200], [300, 200]], "merge": false});
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"angle": 1e300})), "`angle` must be from -180 to 180 degrees");
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, json!({"roundness": -1e300})), "`roundness` must be from 0 to 100%");
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
}
|
||||
|
||||
/// `path.blob` refuses an `angle`, `roundness` or `fidelity` outside its range and changes nothing;
|
||||
/// each end of a range paints, and a key left out or null takes its default (0°, 100% and no fitting).
|
||||
#[test]
|
||||
fn blob_brush_rejects_out_of_range_tip_and_fidelity_without_edit() {
|
||||
let mut s = session();
|
||||
let stroke = json!({"points": [[100, 100], [300, 100]], "size": 20, "merge": false});
|
||||
let angle = "`angle` must be from -180 to 180 degrees";
|
||||
let roundness = "`roundness` must be from 0 to 100%";
|
||||
let fidelity = "`fidelity` must be from 0.01 to 100 pt";
|
||||
for (extra, want) in [
|
||||
(json!({"angle": -180.5}), angle),
|
||||
(json!({"angle": 181}), angle),
|
||||
(json!({"angle": 1e300}), angle),
|
||||
(json!({"roundness": -0.5}), roundness),
|
||||
(json!({"roundness": 101}), roundness),
|
||||
(json!({"fidelity": 0.005}), fidelity),
|
||||
(json!({"fidelity": 0}), fidelity),
|
||||
(json!({"fidelity": -1}), fidelity),
|
||||
(json!({"fidelity": 101}), fidelity),
|
||||
(json!({"fidelity": 1e300}), fidelity),
|
||||
(json!({"angle": 45, "roundness": 50, "fidelity": 100.5}), fidelity),
|
||||
] {
|
||||
refuses_with(&mut s, "path.blob", &with(&stroke, extra), want);
|
||||
}
|
||||
assert!(paths(&s).is_empty());
|
||||
let painted = |s: &mut Session, extra: serde_json::Value| {
|
||||
let id = NodeId(s.execute("path.blob", &with(&stroke, extra)).unwrap()["id"].as_u64().unwrap());
|
||||
path(s, id)
|
||||
};
|
||||
for extra in [
|
||||
json!({"angle": -180}),
|
||||
json!({"angle": 180}),
|
||||
json!({"roundness": 0}),
|
||||
json!({"roundness": 100}),
|
||||
json!({"fidelity": 0.01}),
|
||||
json!({"fidelity": 100}),
|
||||
] {
|
||||
let pd = painted(&mut s, extra.clone());
|
||||
assert!(pd.control_bounds().is_some_and(|b| b.height().is_finite() && b.height() > 0.0), "{extra}: {pd:?}");
|
||||
}
|
||||
let defaults = painted(&mut s, json!({}));
|
||||
let nulls = painted(&mut s, json!({"angle": null, "roundness": null, "fidelity": null}));
|
||||
let given = painted(&mut s, json!({"angle": 0, "roundness": 100}));
|
||||
assert_eq!(nulls, defaults);
|
||||
assert_eq!(given, defaults);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -330,6 +379,41 @@ fn pencil_connect_keeps_the_rest_of_a_compound_path_and_refuses_the_extended_pat
|
||||
assert!(s.execute("path.freehand", &json!({"points": points, "extend": {"id": a.0}, "connect": {"id": a.0}})).is_err());
|
||||
}
|
||||
|
||||
/// `path.freehand` refuses a `style` other than "pencil" or "brush" and an `extend` end other than
|
||||
/// "start" or "end" and changes nothing; left out or null, the style is "pencil" and the stroke
|
||||
/// continues the path from its end.
|
||||
#[test]
|
||||
fn pencil_refuses_an_unknown_style_or_extend_end() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
let stroke = json!({"points": [[100, 300], [200, 320], [300, 300]]});
|
||||
for style in [json!("calligraphic"), json!("Brush"), json!(""), json!(1), json!(true)] {
|
||||
refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "style": style })), "style must be \"pencil\" or \"brush\"");
|
||||
}
|
||||
let from_end = json!({"points": [[200, 100], [250, 150], [300, 100]]});
|
||||
for end in [json!("middle"), json!("START"), json!(""), json!(0), json!(false)] {
|
||||
let p = with(&from_end, json!({"extend": {"id": a.0, "end": end}}));
|
||||
refuses_with(&mut s, "path.freehand", &p, "extend end must be \"start\" or \"end\"");
|
||||
}
|
||||
assert_eq!((paths(&s).len(), path(&s, a).anchor_count()), (1, 2), "refused: nothing changed");
|
||||
for style in [json!("pencil"), json!("brush"), json!(null)] {
|
||||
s.execute("path.freehand", &with(&stroke, json!({ "style": style }))).unwrap();
|
||||
}
|
||||
assert_eq!(paths(&s).len(), 4);
|
||||
for end in [json!(null), json!("end")] {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &with(&from_end, json!({"extend": {"id": a.0, "end": end}}))).unwrap();
|
||||
let sp = &path(&s, a).subpaths[0];
|
||||
assert_eq!((sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p), (Point::new(100.0, 100.0), Point::new(300.0, 100.0)), "{end}");
|
||||
}
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("path.freehand", &json!({"points": [[100, 100], [50, 150], [0, 100]], "extend": {"id": a.0, "end": "start"}})).unwrap();
|
||||
let ends: Vec<Point> = path(&s, a).subpaths[0].anchors.iter().map(|x| x.p).collect();
|
||||
assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}");
|
||||
}
|
||||
|
||||
/// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath
|
||||
/// that connect joins on is no longer selected, and Delete then has nothing to delete.
|
||||
#[test]
|
||||
|
||||
@@ -641,7 +641,7 @@ fn export_selection_reports_the_encoders_warnings() {
|
||||
assert_eq!(plain["format"], "svg");
|
||||
assert!(warnings(&plain).is_empty(), "{plain}");
|
||||
for (format, options, says) in [
|
||||
("webp", json!({"lossless": false}), "lossless"),
|
||||
("webp", json!({"interlaced": true}), "interlaced"),
|
||||
("svg", json!({"profile": "tiny12"}), "blend"),
|
||||
("pdf", json!({"createLayers": true, "compatibility": "1.4"}), "layers"),
|
||||
] {
|
||||
|
||||
@@ -391,3 +391,21 @@ fn for_a_printer_a_landscape_page_is_written_upright() {
|
||||
assert_eq!(size(&spooled), [(612.0, 792.0)]);
|
||||
assert_eq!(v["pages"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate() {
|
||||
let (mut s, _) = session();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let ink = json!({"name": "Gold", "convertToProcess": true});
|
||||
let v = s.execute("print.setup", &json!({"settings": {"output": {"mode": "separations", "inks": [ink]}}})).unwrap();
|
||||
assert_eq!(v["settings"]["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}]));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.print_setup.as_ref().map(|p| p["output"]["inks"][0]["convertToProcess"].clone()), Some(json!(true)), "kept in the file");
|
||||
let pv = s.execute("print.preview", &json!({})).unwrap();
|
||||
let names = |list: &Value| list.as_array().unwrap().iter().map(|i| i["name"].as_str().unwrap().to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&pv["inks"]), ["Cyan", "Magenta", "Yellow", "Black"], "no Gold plate");
|
||||
assert_eq!(names(&pv["documentInks"]), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]);
|
||||
assert_eq!(pv["documentInks"][4]["convertToProcess"], json!(true));
|
||||
assert_eq!(pv["documentInks"][0].get("convertToProcess"), None, "written only when on");
|
||||
}
|
||||
@@ -369,3 +369,129 @@ fn scale_text_attributes_keeps_tracked_type_where_it_was() {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What Scale Text Attributes must leave as it was: the document-space bounds of an area's frame
|
||||
/// or a path type's path, each line's text, whether the text overflows, and where each glyph
|
||||
/// starts on the page.
|
||||
struct Placed {
|
||||
outline: Option<vectorcraft_geom::Rect>,
|
||||
lines: Vec<(usize, usize)>,
|
||||
overflow: bool,
|
||||
pens: Vec<Point>,
|
||||
}
|
||||
|
||||
fn placed(s: &Session, id: NodeId) -> Placed {
|
||||
let t = text(s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
let outline = match &t.kind {
|
||||
vectorcraft_doc::TextKind::Area { frame } => Some(frame),
|
||||
vectorcraft_doc::TextKind::OnPath { path, .. } => Some(path),
|
||||
vectorcraft_doc::TextKind::Point => None,
|
||||
};
|
||||
Placed {
|
||||
outline: outline.and_then(|p| p.transformed(t.xf).bounds()),
|
||||
lines: lay.lines.iter().map(|l| (l.start, l.end)).collect(),
|
||||
overflow: lay.overflow,
|
||||
pens: lay.glyphs.iter().map(|g| t.xf * (g.xf * Point::ZERO)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn same_place(before: &Placed, after: &Placed) {
|
||||
let (Some(b), Some(a)) = (before.outline, after.outline) else { panic!("no frame or path: {:?} {:?}", before.outline, after.outline) };
|
||||
for (x, y) in [(b.x0, a.x0), (b.y0, a.y0), (b.x1, a.x1), (b.y1, a.y1)] {
|
||||
assert!((x - y).abs() < 1e-6, "frame {b:?} became {a:?}");
|
||||
}
|
||||
assert_eq!(after.lines, before.lines, "line breaks");
|
||||
assert_eq!(after.overflow, before.overflow, "overflow");
|
||||
assert_eq!(before.pens.len(), after.pens.len());
|
||||
for (b, a) in before.pens.iter().zip(&after.pens) {
|
||||
assert!((*a - *b).hypot() < 1e-6, "{:?} {:?}", before.pens, after.pens);
|
||||
}
|
||||
}
|
||||
|
||||
/// #8297: Scale Text Attributes on scaled area type keeps the frame the scale gave it, so the
|
||||
/// lines break where they did and no text becomes overset. It used to leave the frame at its
|
||||
/// unscaled size, which then held two lines of the larger type and hid the rest.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_an_area_frame_and_its_lines() {
|
||||
for (sx, sy, size) in [(200, 200, 24.0), (200, 100, 12.0), (50, 50, 6.0)] {
|
||||
let mut s = session();
|
||||
let id = NodeId(
|
||||
s.execute(
|
||||
"text.create",
|
||||
&json!({"x": 40, "y": 60, "size": 12, "area": {"width": 120, "height": 80}, "text": "Bright river stones mark a gentle path past old trees."}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("object.scale", &json!({"sx": sx, "sy": sy, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(before.lines.len() >= 3 && !before.overflow, "{sx}x{sy}: {:?}", before.lines);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, size);
|
||||
same_place(&before, &placed(&s, id));
|
||||
if (sx, sy) == (200, 200) {
|
||||
let f = before.outline.unwrap();
|
||||
assert_eq!((f.x0.round(), f.y0.round(), f.x1.round(), f.y1.round()), (80.0, 120.0, 320.0, 280.0));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 12.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a path keeps its path: it used to shrink with the scale removed, so the type ran past
|
||||
/// its end.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_a_path_types_path() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M100 300 L300 300" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Along the way", "size": 12, "at": [100, 300]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
assert!(!before.overflow);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
same_place(&before, &placed(&s, id));
|
||||
}
|
||||
|
||||
/// A non-uniform scale on type on a path: only the uniform part is baked and the stretch stays in
|
||||
/// the transform, so the brackets, which sit at fractions of the path's length, stay where they
|
||||
/// were. Baking the stretch into the path would move them: on this path, scaled 3 × 2, the length
|
||||
/// grows from 200 to 500 and not in proportion, so the same fraction lands elsewhere.
|
||||
#[test]
|
||||
fn scale_text_attributes_keeps_path_type_on_a_stretched_path_where_it_was() {
|
||||
let mut s = session();
|
||||
let pid = s.execute("path.create", &json!({ "d": "M0 0 L100 0 L100 100" })).unwrap()["id"].as_u64().unwrap();
|
||||
let id = NodeId(
|
||||
s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "Corner", "size": 12, "at": [60, 0]})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 300, "sy": 200, "origin": [0, 0]})).unwrap();
|
||||
let before = placed(&s, id);
|
||||
let brackets = |s: &Session| match text(s, id).kind {
|
||||
vectorcraft_doc::TextKind::OnPath { start, end, .. } => (start, end),
|
||||
k => panic!("not path type: {k:?}"),
|
||||
};
|
||||
let before_brackets = brackets(&s);
|
||||
s.execute("type.scaleTextAttributes", &json!({})).unwrap();
|
||||
near(text(&s, id).runs[0].style.size, 24.0);
|
||||
near(text(&s, id).runs[0].style.h_scale, 100.0);
|
||||
let left = text(&s, id).style_scale().unwrap();
|
||||
near(left.points, 1.0);
|
||||
near(left.horizontal, 1.5);
|
||||
assert_eq!(brackets(&s), before_brackets);
|
||||
same_place(&before, &placed(&s, id));
|
||||
// Only the stretch is left: there is nothing more to bake.
|
||||
assert!(s.execute("type.scaleTextAttributes", &json!({})).is_err());
|
||||
}
|
||||
@@ -523,3 +523,215 @@ fn setting_keys_are_their_json_values() {
|
||||
.unwrap();
|
||||
assert_eq!(serde_json::from_value::<cmd::webexport::WebSettings>(custom.to_json()).unwrap(), custom);
|
||||
}
|
||||
|
||||
fn optimize_to(s: &mut Session, p: Value) -> Value {
|
||||
run(s, "webExport.optimizeToFileSize", p)
|
||||
}
|
||||
|
||||
/// The size of the file the settings `p` write (the whole image, or slice `slice`).
|
||||
fn written(s: &mut Session, p: &Value) -> usize {
|
||||
run(s, "document.exportForWeb.preview", p.clone())["bytes"].as_u64().unwrap() as usize
|
||||
}
|
||||
|
||||
/// 20×20: 400 one-point squares of different colors (more than a palette holds).
|
||||
fn photo_like() -> Session {
|
||||
let mut s = session(20.0, 20.0);
|
||||
for i in 0..400 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
rect(&mut s, [x, y, 1.0, 1.0], &format!("#{:02x}{:02x}{:02x}", (i % 20) * 12, (i / 20) * 12, (i * 7) % 256));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_takes_the_highest_jpeg_quality_that_fits() {
|
||||
let mut s = many_colours();
|
||||
let start = json!({"format": "jpg", "quality": 90});
|
||||
let full = written(&mut s, &start);
|
||||
let k = (full * 3 / 4) as f64 / 1024.0;
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": k})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!(target, (k * 1024.0).floor() as usize);
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str(), r["images"].as_u64()), (Some(true), Some("jpg"), Some(1)), "{r}");
|
||||
let q = r["settings"]["quality"].as_u64().unwrap();
|
||||
assert!(q < 90, "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target, "{r}");
|
||||
// The size is the size of the file Save writes with the settings.
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert_eq!(one(&mut s, r["settings"].clone()).len(), bytes);
|
||||
// One quality step up is over the size.
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"quality": q + 1}))) > target);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
// The other settings stay.
|
||||
assert_eq!(r["settings"]["matte"], json!("white"));
|
||||
assert_eq!(r["settings"]["metadata"], json!("copyright"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_lowers_palette_colors() {
|
||||
let mut s = many_colours();
|
||||
for format in ["gif", "png8"] {
|
||||
let start = json!({"format": format, "dither": "none", "colors": 128});
|
||||
let full = written(&mut s, &start);
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (full * 3 / 4) as f64 / 1024.0})));
|
||||
let target = r["targetBytes"].as_u64().unwrap() as usize;
|
||||
assert_eq!((r["achieved"].as_bool(), r["format"].as_str()), (Some(true), Some(format)), "{r}");
|
||||
let colors = r["settings"]["colors"].as_u64().unwrap();
|
||||
assert!(colors < 64, "{format}: {r}");
|
||||
assert_eq!((r["settings"]["lossy"].as_u64(), r["settings"]["dither"].as_str()), (Some(0), Some("none")), "{format}: {r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes <= target && written(&mut s, &r["settings"]) == bytes, "{format}: {r}");
|
||||
assert!(written(&mut s, &merge(&r["settings"], json!({"colors": colors + 1}))) > target, "{format}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_selects_gif_or_jpeg_by_content() {
|
||||
// Flat, opaque art: GIF, from a JPEG start.
|
||||
let mut flat = two_colours();
|
||||
let r = optimize_to(&mut flat, json!({"format": "jpg", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("gif"), Some(true)), "{r}");
|
||||
// More colors than a palette holds: JPEG, from a GIF start.
|
||||
let mut photo = photo_like();
|
||||
let r = optimize_to(&mut photo, json!({"format": "gif", "desiredK": 100, "startWith": "auto"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// Transparent pixels: GIF, which keeps them.
|
||||
let mut clear = session(40.0, 30.0);
|
||||
rect(&mut clear, [0.0, 0.0, 10.0, 10.0], "#000000");
|
||||
for (k, transparency, format) in [(100.0, true, "gif"), (100.0, false, "gif"), (0.01, true, "gif")] {
|
||||
let r = optimize_to(&mut clear, json!({"format": "jpg", "desiredK": k, "startWith": "auto", "transparency": transparency}));
|
||||
assert_eq!(r["format"].as_str(), Some(format), "{k} {transparency}: {r}");
|
||||
}
|
||||
// The current format stays without auto.
|
||||
let r = optimize_to(&mut photo, json!({"format": "png8", "desiredK": 100}));
|
||||
assert_eq!(r["format"].as_str(), Some("png8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_auto_counts_the_colors_blended_over_the_matte() {
|
||||
// Three colors at 100 opacities: without transparency, 300 colors once blended over the matte.
|
||||
let mut s = session(20.0, 15.0);
|
||||
for i in 0..300 {
|
||||
let (x, y) = ((i % 20) as f64, (i / 20) as f64);
|
||||
let id = rect(&mut s, [x, y, 1.0, 1.0], ["#000000", "#ff0000", "#0000ff"][i % 3]);
|
||||
run(&mut s, "transparency.set", json!({"ids": [id], "opacity": i / 3 + 1}));
|
||||
}
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 100, "startWith": "auto", "transparency": false, "antiAlias": "none"}));
|
||||
assert_eq!((r["format"].as_str(), r["achieved"].as_bool()), (Some("jpg"), Some(true)), "{r}");
|
||||
// With transparency the pixels stay transparent: GIF.
|
||||
let r = optimize_to(&mut s, json!({"format": "jpg", "desiredK": 100, "startWith": "auto", "antiAlias": "none"}));
|
||||
assert_eq!(r["format"].as_str(), Some("gif"), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_says_when_no_setting_fits() {
|
||||
let mut s = many_colours();
|
||||
for format in ["jpg", "gif", "png8"] {
|
||||
let start = json!({"format": format});
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": 0.01})));
|
||||
assert_eq!((r["targetBytes"].as_u64(), r["achieved"].as_bool(), r["format"].as_str()), (Some(10), Some(false), Some(format)), "{r}");
|
||||
let bytes = r["bytes"].as_u64().unwrap() as usize;
|
||||
assert!(bytes > 10 && bytes <= written(&mut s, &start), "{format}: the smallest setting tried: {r}");
|
||||
assert_eq!(written(&mut s, &r["settings"]), bytes);
|
||||
assert!(r["trials"].as_u64().unwrap() as usize <= cmd::webexport::OPTIMIZE_TRIALS);
|
||||
}
|
||||
// GIF tries lossy when 2 colors are over.
|
||||
let r = optimize_to(&mut s, json!({"format": "gif", "desiredK": 0.01}));
|
||||
assert_eq!(r["settings"]["lossy"], json!(100), "{r}");
|
||||
// PNG-24 has nothing to lower.
|
||||
let r = optimize_to(&mut s, json!({"format": "png24", "desiredK": 0.01}));
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(false), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&json!({"format": "png24"})).unwrap().to_json());
|
||||
// Settings that fit stay as they are.
|
||||
let p = json!({"format": "jpg", "quality": 80, "desiredK": 1000});
|
||||
let r = optimize_to(&mut s, p.clone());
|
||||
assert_eq!((r["achieved"].as_bool(), r["trials"].as_u64()), (Some(true), Some(1)), "{r}");
|
||||
assert_eq!(r["settings"], s.web_settings(&p).unwrap().to_json());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_refuses_bad_params_and_changes_nothing() {
|
||||
let mut s = many_colours();
|
||||
run(&mut s, "webExport.settings", json!({"format": "jpg", "quality": 77}));
|
||||
let remembered = s.last_web_settings();
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"desiredK": 0}),
|
||||
json!({"desiredK": -5}),
|
||||
json!({"desiredK": "10"}),
|
||||
json!({"desiredK": null}),
|
||||
json!({"desiredK": 2_000_000}),
|
||||
json!({"desiredK": 10, "startWith": "gif"}),
|
||||
json!({"desiredK": 10, "startWith": 1}),
|
||||
json!({"desiredK": 10, "use": "all"}),
|
||||
json!({"desiredK": 10, "slice": 0}),
|
||||
json!({"desiredK": 10, "slice": "1"}),
|
||||
json!({"desiredK": 10, "slice": 1, "use": "eachSlice"}),
|
||||
json!({"desiredK": 10, "slice": 99}),
|
||||
json!({"desiredK": 10, "percent": 0}),
|
||||
] {
|
||||
assert!(s.execute("webExport.optimizeToFileSize", &p).is_err(), "{p}");
|
||||
}
|
||||
optimize_to(&mut s, json!({"desiredK": 0.5, "format": "jpg"}));
|
||||
assert_eq!(s.last_web_settings(), remembered, "the search changes no remembered setting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_measures_the_slices_as_use_says() {
|
||||
let mut s = session(300.0, 200.0);
|
||||
rect(&mut s, [0.0, 0.0, 300.0, 200.0], "#336699");
|
||||
for i in 0..40 {
|
||||
rect(&mut s, [f64::from(i) * 7.0, f64::from(i) * 4.0, 30.0, 20.0], &format!("#{:02x}{:02x}40", i * 6, 255 - i * 6));
|
||||
}
|
||||
let a = rect(&mut s, [20.0, 20.0, 100.0, 60.0], "#ff8800");
|
||||
run(&mut s, "object.slice.make", json!({"ids": [a]}));
|
||||
let layout = run(&mut s, "slice.list", json!({}))["slices"].as_array().unwrap().clone();
|
||||
let start = json!({"format": "jpg", "quality": 95});
|
||||
let sizes = |s: &mut Session, p: &Value| files(&run(s, "document.exportForWeb", p.clone())).iter().map(|(_, b)| b.len()).collect::<Vec<_>>();
|
||||
let all = sizes(&mut s, &start);
|
||||
assert_eq!(all.len(), layout.len());
|
||||
let total: usize = all.iter().sum();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (total * 3 / 4) as f64 / 1024.0})));
|
||||
assert_eq!((r["achieved"].as_bool(), r["images"].as_u64()), (Some(true), Some(layout.len() as u64)), "{r}");
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(after.iter().sum::<usize>(), r["bytes"].as_u64().unwrap() as usize, "the slice files together");
|
||||
let largest = *all.iter().max().unwrap();
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (largest * 3 / 4) as f64 / 1024.0, "use": "eachSlice"})));
|
||||
let after = sizes(&mut s, &r["settings"]);
|
||||
assert_eq!(*after.iter().max().unwrap(), r["bytes"].as_u64().unwrap() as usize, "the largest slice file");
|
||||
assert!(r["achieved"].as_bool().unwrap() && after.iter().all(|n| *n <= r["targetBytes"].as_u64().unwrap() as usize), "{r}");
|
||||
let n = layout[0]["number"].as_u64().unwrap();
|
||||
let one_slice = written(&mut s, &merge(&start, json!({"slice": n})));
|
||||
let r = optimize_to(&mut s, merge(&start, json!({"desiredK": (one_slice / 2) as f64 / 1024.0, "slice": n})));
|
||||
assert_eq!(r["images"].as_u64(), Some(1));
|
||||
assert_eq!(written(&mut s, &merge(&r["settings"], json!({"slice": n}))), r["bytes"].as_u64().unwrap() as usize, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() {
|
||||
use cmd::webexport::{OPTIMIZE_SAMPLES, WebSettings, highest_within, set_quality};
|
||||
// Sizes that do not fall with the quality: 1 to 20 give 900 bytes, 21 to 70 give 400 to 449,
|
||||
// and 71 and up give over 1000.
|
||||
let size_of = |q: u8| match q {
|
||||
..=20 => 900,
|
||||
21..=70 => 400 + usize::from(q - 21),
|
||||
_ => 1000 + usize::from(q),
|
||||
};
|
||||
let start = WebSettings { quality: 90, ..WebSettings::default() };
|
||||
let mut measured = Vec::new();
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| {
|
||||
measured.push(s.quality);
|
||||
Ok(Some(size_of(s.quality)))
|
||||
};
|
||||
let found = highest_within(&mut size, &start, (1, 90), set_quality, 500, &mut smallest).unwrap();
|
||||
let (settings, bytes) = found.expect("a quality within 500 bytes");
|
||||
assert_eq!((settings.quality, bytes), (70, 449), "measured {measured:?}");
|
||||
assert!(measured.len() <= usize::from(OPTIMIZE_SAMPLES) + 7, "measured {measured:?}");
|
||||
// Nothing fits: the smallest size measured is kept.
|
||||
let mut smallest = None;
|
||||
let mut size = |s: &WebSettings| Ok(Some(size_of(s.quality)));
|
||||
assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none());
|
||||
assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415)));
|
||||
}
|
||||
@@ -3827,6 +3827,83 @@ fn editing_text() -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_meshes_never_panic`]'s cuts and edits: past the end of [`meshes_text`].
|
||||
const MESHES_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two gradient meshes: 2 × 3 patches whose
|
||||
/// rows of points are RGB, CMYK and gray, at half opacity and named; a 1 × 1 mesh with a point at
|
||||
/// 40% opacity; and an instance of a symbol whose art is a 2 × 1 mesh.
|
||||
fn meshes_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshPoint, grid_points, smooth_handles};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
let mesh = |r: Rect, rows: u32, cols: u32, color: &dyn Fn(usize) -> Color| {
|
||||
let pts = grid_points(r, rows, cols);
|
||||
let handles = smooth_handles(rows, cols, &pts);
|
||||
let width = cols as usize + 1;
|
||||
let points = pts
|
||||
.iter()
|
||||
.zip(handles)
|
||||
.enumerate()
|
||||
.map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width), opacity: 1.0, handles: h })
|
||||
.collect();
|
||||
GradientMesh { rows, cols, points }
|
||||
};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let sheet = mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, &|row| match row {
|
||||
0 => Color::rgb(1.0, 0.5, 0.0),
|
||||
1 => Color::cmyk(0.1, 0.6, 0.2, 0.05),
|
||||
_ => Color::gray(0.4),
|
||||
});
|
||||
let mut sheet = Node::new(doc.alloc_id(), NodeKind::Mesh(sheet));
|
||||
(sheet.name, sheet.opacity) = (Some("Sheet".into()), 0.5);
|
||||
doc.insert(Some(layer), usize::MAX, sheet).unwrap();
|
||||
let mut small = mesh(Rect::new(220.0, 20.0, 280.0, 80.0), 1, 1, &|row| Color::rgb(0.0, 0.3, 0.3 + 0.5 * row as f32));
|
||||
small.points[1].opacity = 0.4;
|
||||
let small = Node::new(doc.alloc_id(), NodeKind::Mesh(small));
|
||||
doc.insert(Some(layer), usize::MAX, small).unwrap();
|
||||
let patch = mesh(Rect::new(0.0, 0.0, 40.0, 30.0), 2, 1, &|row| Color::rgb(0.2 * row as f32, 0.6, 0.1));
|
||||
let patch = Node::new(doc.alloc_id(), NodeKind::Mesh(patch));
|
||||
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Patch".into(), art: std::sync::Arc::new(patch) });
|
||||
let instance =
|
||||
Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Patch".into(), xf: vectorcraft_geom::Affine::translate((20.0, 140.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_meshes_never_panic`] damages, as it is, opens with both meshes, the symbol
|
||||
/// with its mesh and its instance, and the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_meshes_fuzz_data_opens_as_meshes() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = meshes_text();
|
||||
assert!(text.chars().count() < MESHES_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI14_BeginSymbol", "%AI5_BeginLayer", "/Mesh X!", "%_[2 3] /Size X#", "%_/DeviceCMYK /CS X#", "/End X!", "/SymbolInstance :"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
let kinds: Vec<&str> = art
|
||||
.iter()
|
||||
.map(|n| match n.kind {
|
||||
NodeKind::Mesh(_) => "mesh",
|
||||
NodeKind::SymbolInstance { .. } => "instance",
|
||||
_ => "other",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds, ["mesh", "mesh", "instance"], "{warnings:?}");
|
||||
let patch = d.symbols.iter().find(|s| s.name == "Patch").map(|s| &s.art.kind);
|
||||
assert!(matches!(patch, Some(NodeKind::Mesh(_))), "{patch:?}");
|
||||
}
|
||||
|
||||
fn zstd(text: &str) -> Vec<u8> {
|
||||
ruzstd::encoding::compress_to_vec(text.as_bytes(), ruzstd::encoding::CompressionLevel::Fastest)
|
||||
}
|
||||
@@ -4482,6 +4559,17 @@ proptest! {
|
||||
survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose gradient meshes, as the writer writes them, are damaged: the record's type,
|
||||
/// size, places, color spaces and corners on `%_` lines, its `/Mesh X!` and `/End X!`, and the
|
||||
/// mesh's transparency and name, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_meshes_never_panic(cut in 0usize..MESHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..MESHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '9', '-', '.', 'e', ' ', '\n', '[', ']', '(', ')', '/', '%', '_', 'X', '!', '#', 'N', 'P', 'E'])), 0..12)) {
|
||||
let text = mutate_text(meshes_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai meshes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai meshes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// The active artboard that a restored `.ai` opens on, read from damaged or hostile editing data.
|
||||
#[test]
|
||||
fn ai_active_artboard_never_panics(cut in 0usize..600, edits in prop::collection::vec((0usize..600, prop::sample::select(vec!['0', '9', '-', ' ', '\n', '/', ':', ';', ',', '%', '_'])), 0..12)) {
|
||||
@@ -5066,6 +5154,81 @@ proptest! {
|
||||
survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose blends, as the writer writes them, are damaged: the keys and spine on `%_`
|
||||
/// lines with their dictionaries, the drawn steps, the record's `XP` and its hex, and the
|
||||
/// blend's transparency, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_blends_never_panic(cut in 0usize..BLENDS_FUZZ_CHARS, edits in prop::collection::vec((0usize..BLENDS_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '8', '9', 'A', 'F', '-', '.', ' ', '\n', '(', ')', '/', ',', ';', '%', '_', 'u', 'U', 'K', 'S', 'X', 'P'])), 0..12)) {
|
||||
let text = mutate_text(blends_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai blends", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai blends, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_blends_never_panic`]'s cuts and edits: past the end of [`blends_text`].
|
||||
const BLENDS_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two blends: red to blue squares with
|
||||
/// three steps and no spine of its own, at half opacity; and three squares 25 pt apart on a spine
|
||||
/// edited on the canvas, aligned to the path.
|
||||
fn blends_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let square = |doc: &mut Document, x: f64, y: f64, c: Color| {
|
||||
Arc::new(Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)),
|
||||
Appearance::basic(Paint::solid(c), Paint::None, 0.0),
|
||||
))
|
||||
};
|
||||
let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0));
|
||||
let keys = vec![square(&mut doc, 20.0, 20.0, red), square(&mut doc, 120.0, 20.0, blue)];
|
||||
let mut fade = Node::new(
|
||||
doc.alloc_id(),
|
||||
NodeKind::Blend { children: keys, spec: Box::new(BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) },
|
||||
);
|
||||
fade.opacity = 0.5;
|
||||
doc.insert(Some(layer), usize::MAX, fade).unwrap();
|
||||
let keys = vec![square(&mut doc, 20.0, 80.0, red), square(&mut doc, 120.0, 80.0, blue), square(&mut doc, 170.0, 80.0, green)];
|
||||
let centers: Vec<Point> = [30.0, 130.0, 180.0].iter().map(|x| Point::new(*x, 90.0)).collect();
|
||||
let spec = BlendSpec {
|
||||
spacing: BlendSpacing::Distance(25.0),
|
||||
orientation: BlendOrientation::AlignToPath,
|
||||
spine: Some(PathData::single(SubPath::polyline(¢ers, false))),
|
||||
key_anchors: vec![0, 1, 2],
|
||||
..BlendSpec::default()
|
||||
};
|
||||
let path = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) });
|
||||
doc.insert(Some(layer), usize::MAX, path).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_blends_never_panic`] damages, as it is, opens with both blends live, and
|
||||
/// the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_blends_fuzz_data_opens_live() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = blends_text();
|
||||
assert!(text.chars().count() < BLENDS_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI5_BeginLayer", "%_(K) /String (ShapeBlendPathType) ,", "%_(S) /String (ShapeBlendPathType) ,", "1 0 92 XP", "1 0 116 XP"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
assert_eq!(art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect::<Vec<_>>(), [true, true], "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`].
|
||||
|
||||
@@ -120,7 +120,9 @@
|
||||
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
|
||||
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
|
||||
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there,
|
||||
//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are
|
||||
//! in the canvas's space with y down.
|
||||
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
|
||||
//! group with live effects or linked to a graphic style is written as its drawn look (`u`, its
|
||||
//! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its
|
||||
@@ -147,6 +149,19 @@
|
||||
//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between
|
||||
//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end;
|
||||
//! any other graph, and a graph with art left out, as its art, with a warning.
|
||||
//! - Gradient meshes, as the reader reads them (`mesh.rs`): `/Mesh X!`, `2 /Version`, the grid's type
|
||||
//! and size, `/Data` (the reader passes over the version and `/Data`), and each patch's place, color
|
||||
//! space and four corners (color, opacity, point and handles) as `X#` entries on `%_` lines,
|
||||
//! `/End X!`; the mesh's transparency before it, its name and opacity mask after it
|
||||
//! (`writer::meshes`). A mesh is written as it is only when the reader reads it back so, when every
|
||||
//! patch turns the same way (a reflected mesh's columns are written in reverse order), and outside
|
||||
//! pattern tiles, art cut to a clipping object and a large canvas.
|
||||
//! - Blends, as the reader reads them (`blend.rs`): the blend's key objects and spine as a group on
|
||||
//! `%_` lines, each key's `/ArtDictionary` naming it a key and its id and the spine's naming it the
|
||||
//! spine (written when the blend has a spine of its own); its steps drawn, a group;
|
||||
//! the blend plugin's `1 0 n XP` line and the blend's record of its spacing, orientation and keys as hex
|
||||
//! on `%` lines; its name and transparency as a group's after its end (`writer::blends`). A blend is
|
||||
//! written live only when the reader reads it back with its settings.
|
||||
//!
|
||||
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
|
||||
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
|
||||
@@ -176,7 +191,10 @@
|
||||
//! and instances of
|
||||
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
|
||||
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
|
||||
//! guides, export types and dynamic type left out, live objects (placed documents included) as their art,
|
||||
//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as
|
||||
//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh
|
||||
//! on a large canvas as their drawn look, blends the reader wouldn't read back live as
|
||||
//! their steps, other live objects (placed documents included) as their art,
|
||||
//! strokes a plain line can't draw and the object's art style doesn't hold
|
||||
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
|
||||
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
|
||||
@@ -289,6 +307,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
let links = writer::style_links(doc);
|
||||
// Before baking, which leaves the wrap objects that may be written as they are unchanged.
|
||||
let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() };
|
||||
// The blends baking leaves as they are, which may be written live.
|
||||
let unbaked_blends = writer::unbaked_blends(doc);
|
||||
// Live geometry effects as their result, as the PDF part draws them.
|
||||
let baked = baked(doc);
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
@@ -319,6 +339,9 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
// On a large canvas the layers' symbol instances are written as their art.
|
||||
w.symbols_live = scale == 1.0;
|
||||
w.brushes_live = scale == 1.0;
|
||||
w.meshes_live = scale == 1.0;
|
||||
w.blends_live = scale == 1.0;
|
||||
w.unbaked_blends = unbaked_blends;
|
||||
w.symbol_doc = symbol_doc;
|
||||
w.max_objects = max_objects;
|
||||
w.wraps_held = wraps_held;
|
||||
|
||||
+1845
-27
File diff suppressed because it is too large.
Load diff
@@ -15,19 +15,26 @@ use vectorcraft_pathops::BoolOp;
|
||||
use crate::ai_ops::{self, unit};
|
||||
use crate::ps;
|
||||
|
||||
mod blends;
|
||||
mod brushes;
|
||||
mod envelopes;
|
||||
mod images;
|
||||
mod meshes;
|
||||
mod paints;
|
||||
mod styles;
|
||||
mod symbols;
|
||||
mod texts;
|
||||
mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) use blends::BLENDS;
|
||||
pub(super) use blends::unbaked_blends;
|
||||
#[cfg(test)]
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
#[cfg(test)]
|
||||
pub(super) use meshes::MESHES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
@@ -58,7 +65,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
@@ -304,6 +311,9 @@ pub(super) struct Writer<'a> {
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
pub(super) brushes_live: bool,
|
||||
/// Gradient meshes may be written as meshes; false on a large canvas, where they are written as
|
||||
/// their drawn look.
|
||||
pub(super) meshes_live: bool,
|
||||
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
|
||||
/// ([`Self::envelope`]).
|
||||
deform: bool,
|
||||
@@ -328,6 +338,14 @@ pub(super) struct Writer<'a> {
|
||||
series_tag: Option<String>,
|
||||
/// Where the `Go` lines of the graph being written start in [`Self::body`].
|
||||
graph_tags: Vec<usize>,
|
||||
/// Blends may be written live; false on a large canvas, where they are written as their steps.
|
||||
pub(super) blends_live: bool,
|
||||
/// How many more objects the reader's blends may lay out ([`crate::import::BLEND_BUDGET`]).
|
||||
blend_budget: usize,
|
||||
/// The entries naming a blend's key object in its dictionary, and the key's id.
|
||||
blend_role: Option<(NodeId, String)>,
|
||||
/// The blends baking left as they are ([`blends::unbaked_blends`]); only these are written live.
|
||||
pub(super) unbaked_blends: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -395,6 +413,7 @@ impl<'a> Writer<'a> {
|
||||
wrap_moved: false,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
meshes_live: true,
|
||||
deform: false,
|
||||
checks_left: crate::import::ENVELOPE_CHECKS,
|
||||
objects: 0,
|
||||
@@ -410,6 +429,10 @@ impl<'a> Writer<'a> {
|
||||
in_graph: false,
|
||||
series_tag: None,
|
||||
graph_tags: vec![],
|
||||
blends_live: true,
|
||||
blend_budget: crate::import::BLEND_BUDGET,
|
||||
blend_role: None,
|
||||
unbaked_blends: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -723,6 +746,11 @@ impl<'a> Writer<'a> {
|
||||
return self.styled_object(n, &orig, &name);
|
||||
}
|
||||
self.effects(n);
|
||||
// A gradient mesh the reader reads as it is; else it is written as its drawn look.
|
||||
let mut mesh = match &n.kind {
|
||||
NodeKind::Mesh(m) => self.mesh_record(m),
|
||||
_ => None,
|
||||
};
|
||||
self.state(n.locked, !n.visible);
|
||||
let mut xy = Xy::of(n);
|
||||
if masked_warp_pieces(n) {
|
||||
@@ -738,6 +766,11 @@ impl<'a> Writer<'a> {
|
||||
let charged = self.charges();
|
||||
match &n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Mesh(_) if mesh.is_some() => {
|
||||
if let Some(record) = mesh.take() {
|
||||
self.write_mesh(&record, xy);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => self.clip_group(children, xy),
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
if self.open_group("u") {
|
||||
@@ -840,7 +873,10 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
|
||||
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
|
||||
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
NodeKind::Mesh(_) => self.drawn_art(n, xy, Some(meshes::MESHES), true),
|
||||
NodeKind::Blend { .. } if self.blend(n, xy) => {}
|
||||
NodeKind::Blend { .. } => self.drawn_art(n, xy, Some(blends::BLENDS), true),
|
||||
NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
self.drawn_art(n, xy, Some(LIVE), true);
|
||||
}
|
||||
// Ruler guides are kept in the document's native copy only.
|
||||
@@ -919,7 +955,8 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
if self.nest < MAX_NEST {
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
@@ -955,9 +992,10 @@ impl<'a> Writer<'a> {
|
||||
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
|
||||
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
|
||||
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]). False when `n` has an opacity mask that is left out: nested too
|
||||
/// deep, or its art doesn't fit.
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]), or is a blend's key object (its part and id after the name, see
|
||||
/// [`blends`]). False when `n` has an opacity mask that is left out: nested too deep, or its art
|
||||
/// doesn't fit.
|
||||
fn dictionary(&mut self, n: &Node) -> bool {
|
||||
let name = n.name.as_deref().filter(|s| !s.is_empty());
|
||||
let moved = std::mem::take(&mut self.wrap_moved);
|
||||
@@ -977,7 +1015,11 @@ impl<'a> Writer<'a> {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() {
|
||||
let role = match &self.blend_role {
|
||||
Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() && role.is_none() {
|
||||
return mask_written;
|
||||
}
|
||||
let start = self.body.len();
|
||||
@@ -998,6 +1040,10 @@ impl<'a> Writer<'a> {
|
||||
self.bound.push((n.id, id, bound));
|
||||
}
|
||||
}
|
||||
let has_role = role.is_some();
|
||||
if let Some(r) = role {
|
||||
self.body.push_str(&r);
|
||||
}
|
||||
if let Some(w) = wrap {
|
||||
self.text_wrap(w);
|
||||
}
|
||||
@@ -1005,7 +1051,7 @@ impl<'a> Writer<'a> {
|
||||
if let Some(m) = mask
|
||||
&& !self.mask(m)
|
||||
{
|
||||
if !has_id && !has_entries && wrap.is_none() {
|
||||
if !has_id && !has_entries && wrap.is_none() && !has_role {
|
||||
self.body.truncate(start);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Blends: a live blend as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, `blend.rs`
|
||||
//! and `read/containers.rs`' `end_blend`).
|
||||
//!
|
||||
//! The blend's own art on `%_` lines: `0 Ae`, a group of its key objects, each with an
|
||||
//! `/ArtDictionary` naming it a key (`ShapeBlendPathType` `K`) and its id (`ShapeBlendPathID`, a
|
||||
//! letter or digit), and its spine as an unpainted path named the spine (`S`), written only when the
|
||||
//! blend has a spine of its own; then its steps drawn, a group on plain lines; then `0 Ae`,
|
||||
//! the `XP` line of the blend plugin ([`BLEND_PLUGIN`], `1 0 n XP`) and the blend's record, `n` bytes
|
||||
//! as hex on `%` lines; then the blend's name in an `/ArtDictionary` and its transparency, as a
|
||||
//! group's after its end. The record
|
||||
//! is `DCBA` and little-endian 32-bit words: 1, the spacing (0 Smooth Color, 1 Specified Steps, 2
|
||||
//! Specified Distance); 2, the distance as a float (Specified Steps: the spine's length shared out
|
||||
//! between the steps; Smooth Color: 4); 4, the steps between the first two keys; 5, the orientation
|
||||
//! (0 Align to Page, a float of 8 and the spine's starting angle in radians for Align to Path); 6,
|
||||
//! the next free id (0 after the 62nd); 9, 1; 10, the number of keys; then six words a key: its id,
|
||||
//! 0, the anchor of the spine it sits on as a float, two words of all ones, and the steps between
|
||||
//! it and the key before it. The reader reads words 1, 2 (for Specified Distance), 5 (0, or 8 or
|
||||
//! more), 10 and the keys' ids; the others are written as the record's form has them.
|
||||
//!
|
||||
//! Each blend is checked with the reader's own reading ([`crate::import::blend_reads`]) before it is
|
||||
//! written: one the reader would read with other settings is written as its steps.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_spine, blend_steps, blend_steps_settled, pin_spine};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy, hide};
|
||||
use crate::import::{BLEND_PLUGIN, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, blend_reads};
|
||||
|
||||
pub(in crate::ai_editing) const BLENDS: &str = "blends with easing, a color shift or start points of their own, blends with effects, an appearance or an opacity mask of their own, blends of objects other than paths, compound paths and groups, of clipping groups, of more than 62 key objects, of hidden key objects, of key objects that hold a blend, of key objects with geometry or Pathfinder effects or a group's own fills and strokes, or of key objects the editing copy would change (empty paths or subpaths, paths and compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with transparency or effects of their own, effects or opacity masks), blends where one key object has a fill or stroke of no paint or a stroke of no width and another has one that draws, blends inside objects with geometry or Pathfinder effects or a group's own fills and strokes, blends whose spine has more than one part, blends whose step count is close to where rounding changes it, blends that would open with other settings or not as they are drawn, blends in opacity masks, pattern tiles, symbols and art cut to a clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live objects, brushed strokes), blends whose art would pass the most objects the reader reads, and every blend on a large canvas are written as their steps in the editing data for other apps";
|
||||
|
||||
/// How far (pt) the lengths a blend counts its steps from may move when written (coordinates are
|
||||
/// written to 4 decimals and read back through art space) without changing a count.
|
||||
const SETTLE_LENGTH: f64 = 0.01;
|
||||
/// How far (pt) each segment of a spine may add to [`SETTLE_LENGTH`]: rounding moves each of its
|
||||
/// points by up to 0.00005 √2 pt, which moves the segment's length by up to six times that.
|
||||
const SETTLE_SEGMENT: f64 = 5e-4;
|
||||
/// How far a key's color (each channel, 0 to 1) may move when written without changing a Smooth
|
||||
/// Color count.
|
||||
const SETTLE_COLOR: f64 = 0.001;
|
||||
|
||||
/// The most dash lengths the reader reads; a stroke with more opens solid.
|
||||
const MAX_DASH_LENGTHS: usize = 64;
|
||||
|
||||
/// The ids the keys take, in their order (letters and digits, as the reader reads them).
|
||||
const IDS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
/// Hex digits on one `%` line of a record.
|
||||
const HEX_LINE: usize = 60;
|
||||
|
||||
/// A blend to write live.
|
||||
pub(super) struct LiveBlend {
|
||||
keys: Vec<Arc<Node>>,
|
||||
ids: Vec<String>,
|
||||
/// Its spine part; `None`: the blend has no spine of its own.
|
||||
spine: Option<PathData>,
|
||||
record: Vec<u8>,
|
||||
steps: Vec<Arc<Node>>,
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Blend `n` as the reader reads it live, or `None` when it would read other settings or none
|
||||
/// (the blend is then written as its steps).
|
||||
pub(super) fn live_blend(&mut self, n: &Node) -> Option<LiveBlend> {
|
||||
let NodeKind::Blend { children: keys, spec } = &n.kind else { return None };
|
||||
// Hidden lines (pattern tiles, opacity masks), symbols' definitions and art cut to a
|
||||
// clipping object aren't read as live blends. (No blend is drawn in a look: styled objects
|
||||
// hold only paths, compound paths and groups of them.)
|
||||
if !self.blends_live || self.hidden > 0 || self.in_symbol || self.clip.is_some() || self.nest >= MAX_NEST {
|
||||
return None;
|
||||
}
|
||||
// Baking changes its keys, or the art it sits in ([`unbaked_blends`]).
|
||||
if !self.unbaked_blends.contains(&n.id) {
|
||||
return None;
|
||||
}
|
||||
if !spec.ease.is_default() || spec.color_shift != 0.0 || !spec.starts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let own = &n.appearance;
|
||||
if !own.items.is_empty() || !own.effects.is_empty() || n.extras().mask.is_some() {
|
||||
return None;
|
||||
}
|
||||
// The reader shows every key object it reads.
|
||||
if keys.len() < 2 || keys.len() > IDS.len().min(MAX_BLEND_KEYS) || !keys.iter().all(|k| k.visible && plain_key(k)) {
|
||||
return None;
|
||||
}
|
||||
// A fill or stroke the editing copy leaves out is read back as none at all, and the steps
|
||||
// blend from it to another key's otherwise.
|
||||
if left_out_against_drawn(keys) {
|
||||
return None;
|
||||
}
|
||||
// The spine written: a replaced spine (no key anchors) with an anchor where each key sits, a
|
||||
// spine edited on the canvas with its keys' anchors moved onto them.
|
||||
let spec: &BlendSpec = spec;
|
||||
// The blend lays out along the spine's first subpath, and only that part is written: a
|
||||
// spine of more parts would open without the others.
|
||||
if spec.spine.as_ref().is_some_and(|s| s.subpaths.len() > 1) {
|
||||
return None;
|
||||
}
|
||||
let written = match &spec.spine {
|
||||
None => BlendSpec { key_anchors: vec![], ..spec.clone() },
|
||||
Some(_) if spec.key_anchors.is_empty() => {
|
||||
let (path, anchors) = pin_spine(keys, spec)?;
|
||||
let anchors = anchors.into_iter().map(u32::try_from).collect::<Result<Vec<u32>, _>>().ok()?;
|
||||
BlendSpec { spine: Some(path), key_anchors: anchors, ..spec.clone() }
|
||||
}
|
||||
Some(_) => BlendSpec { spine: Some(blend_spine(keys, spec)?.0), ..spec.clone() },
|
||||
};
|
||||
// The record holds Specified Distance as a 32-bit float, which the reader reads back as its
|
||||
// shortest decimal (10 mm comes back as 28.346457 pt): the blend is compared with that
|
||||
// distance, and kept live only when it lays out as many steps with it.
|
||||
let written = match written.spacing {
|
||||
BlendSpacing::Distance(d) => {
|
||||
let read: f64 = (d as f32).to_string().parse().ok().filter(|r: &f64| r.is_finite() && *r > 0.0)?;
|
||||
let stored = BlendSpec { spacing: BlendSpacing::Distance(read), ..written.clone() };
|
||||
if blend_steps(keys, &stored) != blend_steps(keys, &written) {
|
||||
return None;
|
||||
}
|
||||
stored
|
||||
}
|
||||
_ => written,
|
||||
};
|
||||
// As many objects as the reader lays out for one blend, twice within what its budget has left,
|
||||
// counted before the steps are drawn.
|
||||
let objects = blend_steps(keys, &written).into_iter().fold(keys.len(), usize::saturating_add);
|
||||
if objects > MAX_BLEND_OBJECTS || objects.saturating_mul(2) > self.blend_budget {
|
||||
return None;
|
||||
}
|
||||
// The reader counts the steps from the keys as written, rounded: a count that rounding can
|
||||
// change may come back other than drawn. Specified Distance counts from the spine's length,
|
||||
// and every segment of the spine adds to how far that may move.
|
||||
let segments = written.spine.as_ref().and_then(|s| s.subpaths.first()).map_or(0, |s| s.segment_count());
|
||||
let settle = match written.spacing {
|
||||
BlendSpacing::Distance(_) => SETTLE_LENGTH + segments as f64 * SETTLE_SEGMENT,
|
||||
_ => SETTLE_LENGTH,
|
||||
};
|
||||
if !blend_steps_settled(keys, &written, settle, SETTLE_COLOR) {
|
||||
return None;
|
||||
}
|
||||
let ids: Vec<String> = IDS.iter().take(keys.len()).map(|c| char::from(*c).to_string()).collect();
|
||||
let record = self.record(keys, &written)?;
|
||||
let steps: Vec<Arc<Node>> = vectorcraft_effects::expand_live_deep(Some(self.doc), n).children().cloned().unwrap_or_default();
|
||||
let drawn: Vec<Node> = steps.iter().map(|s| (**s).clone()).collect();
|
||||
// The spine part as written: the first subpath of the spine laid out.
|
||||
let part = written.spine.as_ref().and_then(|s| s.subpaths.first()).map(|sp| PathData::single(sp.clone()));
|
||||
let mut budget = self.blend_budget;
|
||||
let read = blend_reads(keys, &ids, part.as_ref(), &record, &drawn, &mut budget)?;
|
||||
if read != written {
|
||||
return None;
|
||||
}
|
||||
self.blend_budget = budget;
|
||||
Some(LiveBlend { keys: keys.clone(), ids, spine: part, record, steps })
|
||||
}
|
||||
|
||||
/// The record of a blend of `keys` with the settings `spec` (its spine as written).
|
||||
fn record(&self, keys: &[Arc<Node>], spec: &BlendSpec) -> Option<Vec<u8>> {
|
||||
let (spine, anchors) = blend_spine(keys, spec)?;
|
||||
let steps = blend_steps(keys, spec);
|
||||
let first = u32::try_from(*steps.first()?).ok()?;
|
||||
let (spacing, value) = match spec.spacing {
|
||||
BlendSpacing::SmoothColor => (0, 4.0),
|
||||
BlendSpacing::Steps(n) => (1, spine.length() / (f64::from(n) + 1.0)),
|
||||
BlendSpacing::Distance(d) => (2, d),
|
||||
};
|
||||
let orientation = match spec.orientation {
|
||||
BlendOrientation::AlignToPage => 0.0,
|
||||
BlendOrientation::AlignToPath => 8.0 + self.starting_angle(&spine)?,
|
||||
};
|
||||
let count = u32::try_from(keys.len()).ok()?;
|
||||
let next = IDS.get(keys.len()).copied().map_or(0, u32::from);
|
||||
let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), spacing, (value as f32).to_bits(), 0, first, (orientation as f32).to_bits()];
|
||||
words.extend([next, 0, 0, 1, count]);
|
||||
for (i, id) in IDS.iter().take(keys.len()).enumerate() {
|
||||
let anchor = anchors.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(i);
|
||||
let before = i.checked_sub(1).and_then(|j| steps.get(j)).copied().unwrap_or(0);
|
||||
words.extend([u32::from(*id), 0, (anchor as f32).to_bits(), u32::MAX, u32::MAX, u32::try_from(before).ok()?]);
|
||||
}
|
||||
Some(words.iter().flat_map(|w| w.to_le_bytes()).collect())
|
||||
}
|
||||
|
||||
/// The angle in art space (radians, from 0 to 2π) at which `spine` starts.
|
||||
fn starting_angle(&self, spine: &PathData) -> Option<f64> {
|
||||
let sp = spine.subpaths.first()?;
|
||||
let first = sp.anchors.first()?;
|
||||
let towards = if (first.h_out - first.p).hypot() > 1e-9 { first.h_out } else { sp.anchors.get(1)?.p };
|
||||
let (a, b) = (self.to_art * first.p, self.to_art * towards);
|
||||
let angle = (b.y - a.y).atan2(b.x - a.x);
|
||||
Some(if angle < 0.0 { angle + std::f64::consts::TAU } else { angle })
|
||||
}
|
||||
|
||||
/// Blend `n`, of transparency `xy`, written live ([`Self::live_blend`]): its own art on `%_`
|
||||
/// lines, its steps and its record, then the state block of its transparency, before which the
|
||||
/// object's dictionary (its name, text wrap options and variables) goes. False, writing
|
||||
/// nothing, when it is written as its steps: the reader would read it otherwise, or art in it
|
||||
/// would be left out at the object limit ([`Self::take_objects`]).
|
||||
pub(super) fn blend(&mut self, n: &Node, xy: Xy) -> bool {
|
||||
let budget = self.blend_budget;
|
||||
let Some(b) = self.live_blend(n) else { return false };
|
||||
let start = self.body.len();
|
||||
let (state, gs, charges, bound, warnings) = (self.state, self.gs, self.charges(), self.bound.len(), self.warnings.len());
|
||||
let outer = std::mem::take(&mut self.body);
|
||||
self.hidden += 1;
|
||||
self.line("0 Ae");
|
||||
let opened = self.open_group("u");
|
||||
if opened {
|
||||
for (k, id) in b.keys.iter().zip(&b.ids) {
|
||||
self.blend_role = Some((k.id, format!("%_(K) /String (ShapeBlendPathType) ,\n%_({id}) /String (ShapeBlendPathID) ,\n")));
|
||||
self.node(k);
|
||||
self.blend_role = None;
|
||||
}
|
||||
if let Some(spine) = &b.spine {
|
||||
self.plain_object(spine, FillRule::NonZero, None, None, Xy::OPAQUE);
|
||||
self.body.push_str("%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n%_\n");
|
||||
}
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
self.hidden -= 1;
|
||||
let part = std::mem::replace(&mut self.body, outer);
|
||||
hide(&part, &mut self.body);
|
||||
// Readers of the printed form skip the hidden lines: the steps set their own state.
|
||||
(self.state, self.gs) = (None, None);
|
||||
self.state(n.locked, !n.visible);
|
||||
let steps = self.open_group("u");
|
||||
if steps {
|
||||
// The steps are drawn art: copies of the keys carry no text wrap options of their own.
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for s in &b.steps {
|
||||
self.node(s);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
self.state(n.locked, !n.visible);
|
||||
self.line("U");
|
||||
self.line("9 () XW");
|
||||
}
|
||||
if !opened || !steps || self.left_out_since(charges) {
|
||||
let lines = self.body.split_off(start);
|
||||
self.give_back(charges, &lines);
|
||||
self.bound.truncate(bound);
|
||||
// The warnings of art written as its steps again are those steps'.
|
||||
if !self.left_out_since(charges) {
|
||||
self.warnings.truncate(warnings);
|
||||
}
|
||||
(self.state, self.gs, self.block_end, self.blend_budget) = (state, gs, usize::MAX, budget);
|
||||
return false;
|
||||
}
|
||||
self.line("0 Ae");
|
||||
let hex: String = b.record.iter().map(|x| format!("{x:02X}")).collect();
|
||||
let _ = writeln!(self.body, "({BLEND_PLUGIN}) 1 0 {} XP", b.record.len());
|
||||
for chunk in hex.as_bytes().chunks(HEX_LINE) {
|
||||
self.body.push('%');
|
||||
self.body.push_str(&String::from_utf8_lossy(chunk));
|
||||
self.body.push('\n');
|
||||
}
|
||||
// The blend's dictionary goes after the record and before this block ([`Self::node`]).
|
||||
self.state_block(xy);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The blends on `doc`'s layers that baking leaves as they are: blends with nothing in them that
|
||||
/// [`vectorcraft_effects::needs_bake`] evaluates (geometry and Pathfinder effects, a group's own
|
||||
/// fills and strokes), inside no object that has such things of its own. Baking changes the keys
|
||||
/// of the others, so they are written as their steps.
|
||||
pub(in crate::ai_editing) fn unbaked_blends(doc: &Document) -> HashSet<NodeId> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut HashSet<NodeId>) {
|
||||
for n in nodes {
|
||||
if matches!(n.kind, NodeKind::Blend { .. }) {
|
||||
if !vectorcraft_effects::needs_bake(n) {
|
||||
out.insert(n.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(children) = n.children() else { continue };
|
||||
let mut own = (**n).clone();
|
||||
if let Some(c) = own.children_mut() {
|
||||
c.clear();
|
||||
}
|
||||
if !vectorcraft_effects::needs_bake(&own) {
|
||||
walk(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
walk(&doc.layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Does the reader read stroke `s`'s dashes back as they are (`read/ops.rs`' `d`): at most 64
|
||||
/// lengths, each finite and not negative, and a finite offset? It reads other dashes as a solid
|
||||
/// line.
|
||||
fn dash_read_back(s: &StrokeLayer) -> bool {
|
||||
s.dash
|
||||
.as_ref()
|
||||
.is_none_or(|d| d.pattern.len() <= MAX_DASH_LENGTHS && d.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && d.offset.is_finite())
|
||||
}
|
||||
|
||||
/// Do the keys hold a fill or stroke that the editing copy leaves out (a fill of no paint; a stroke
|
||||
/// of no paint or of no width, as `visible_items` leaves them out) where another holds one of the
|
||||
/// same kind that it writes? The steps blend the width, paint and settings of the one left out, and
|
||||
/// the keys read back blend from no fill or stroke, so the steps would open otherwise.
|
||||
fn left_out_against_drawn(keys: &[Arc<Node>]) -> bool {
|
||||
// [fill, stroke]: is one left out somewhere, is one written somewhere.
|
||||
let mut left_out = [false; 2];
|
||||
let mut drawn = [false; 2];
|
||||
for k in keys {
|
||||
k.walk(&mut |n| {
|
||||
for i in &n.appearance.items {
|
||||
let (kind, out) = match i {
|
||||
AppearanceItem::Fill(f) => (0, f.paint.is_none()),
|
||||
AppearanceItem::Stroke(s) => (1, s.paint.is_none() || !(s.width > 0.0 && s.width.is_finite())),
|
||||
};
|
||||
if out {
|
||||
left_out[kind] = true;
|
||||
} else {
|
||||
drawn[kind] = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
(left_out[0] && drawn[0]) || (left_out[1] && drawn[1])
|
||||
}
|
||||
|
||||
/// Can `k` be a key object written live, as the reader reads it back: paths, compound paths and
|
||||
/// groups other than clipping groups (holding no blend), without effects or opacity masks, each with
|
||||
/// at most one fill and one plain stroke over it (a line the data draws as it is), each fill and
|
||||
/// stroke shown, in a color other than Lab or none, opaque in the normal blending mode? (A group's own fills and
|
||||
/// strokes are baked into art of their own, and such blends aren't [`unbaked_blends`].)
|
||||
fn plain_key(k: &Node) -> bool {
|
||||
let mut plain = true;
|
||||
k.walk(&mut |n| {
|
||||
// A clipping group may be written as its art cut to the clipping object.
|
||||
let kind = match &n.kind {
|
||||
// The writer leaves out a path with nothing to draw and subpaths without anchors, and
|
||||
// writes a path of several subpaths as a compound path.
|
||||
NodeKind::Path { path, guide: false, .. } => matches!(path.subpaths.as_slice(), [one] if !one.anchors.is_empty()),
|
||||
// A compound path is written as one path, and read back with a member for each
|
||||
// subpath.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
!children.is_empty()
|
||||
&& children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1))
|
||||
}
|
||||
NodeKind::Group { clip: false, .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
let items = &n.appearance.items;
|
||||
let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count();
|
||||
let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]);
|
||||
let quiet = items.iter().all(|i| {
|
||||
i.visible()
|
||||
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
|
||||
// A color that names no global or spot swatch is written in RGB, so a Lab color
|
||||
// would come back as another.
|
||||
&& !matches!(i.paint(), Paint::Solid { color: Color::Lab { .. }, .. })
|
||||
&& i.effects().is_empty()
|
||||
&& i.opacity() >= 1.0
|
||||
&& i.blend() == BlendMode::Normal
|
||||
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
|
||||
});
|
||||
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
|
||||
});
|
||||
plain
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use super::{Writer, Xy};
|
||||
use crate::ai_ops;
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const BRUSHES: &str = "Pattern and Bristle brushes, Art brushes that don't run their art from left to right, that overlap or whose width follows the pen, Scatter and Art brushes in Tints and Shades or Hue Shift, brushes whose art or its opacity masks' art holds an empty path or group or more than paths, compound paths and groups with one solid fill and one plain stroke each, or opacity masks on a compound path's members or more than seven deep in one another's art, brushes whose names hold a slash or repeat an earlier brush's name, brushes that would open with other settings, brushes past the number or the amount of art one file's brushes can hold, and every brush on a large canvas are left out of the Brushes panel in the editing data for other apps";
|
||||
|
||||
/// Most brushes written (the reader's limit).
|
||||
const MAX_BRUSHES: usize = 4096;
|
||||
@@ -213,17 +213,38 @@ fn art_params(a: &ArtBrush, art: &str) -> Option<String> {
|
||||
Some(format!("2 / {art}/ / / / / 0 0/ 5 0 0 0 / {}", nums6(&numbers)))
|
||||
}
|
||||
|
||||
/// Most opacity masks in one another's art in a brush's art: a brush's art section writes its art
|
||||
/// one level inside, and masks at [`super::MAX_NEST`] levels are left out ([`super::DEEP_MASKS`]).
|
||||
const MAX_MASK_NEST: u32 = super::MAX_NEST - 1;
|
||||
|
||||
/// Is `art` written as the reader reads it back, within a brush: paths and compound paths with
|
||||
/// points and groups with members (not clipping, without paint of their own), each opaque in the
|
||||
/// normal blending mode, without effects or opacity masks, with at most one fill and one plain
|
||||
/// stroke (no brush, width profile, arrowheads, alignment off the path or dashes fitted to corners)
|
||||
/// over it, each in a color or none? A path without points isn't written ([`Writer::plain_object`]).
|
||||
/// normal blending mode, without effects, with at most one fill and one plain stroke (no brush,
|
||||
/// width profile, arrowheads, alignment off the path or dashes fitted to corners) over it, each in a
|
||||
/// color or none, and opacity masks whose art is such art too, at most [`MAX_MASK_NEST`] deep and
|
||||
/// none on a compound path's members? A path without points isn't written
|
||||
/// ([`Writer::plain_object`]).
|
||||
fn plain_art(art: &Node) -> bool {
|
||||
plain_within(art, MAX_MASK_NEST)
|
||||
}
|
||||
|
||||
/// Does no object of `art` have an opacity mask?
|
||||
fn unmasked(art: &Node) -> bool {
|
||||
let mut unmasked = true;
|
||||
art.walk(&mut |n| unmasked &= n.extras().mask.is_none());
|
||||
unmasked
|
||||
}
|
||||
|
||||
/// [`plain_art`] with at most `masks` opacity masks in one another's art.
|
||||
fn plain_within(art: &Node, masks: u32) -> bool {
|
||||
let mut plain = true;
|
||||
art.walk(&mut |n| {
|
||||
let kind = match &n.kind {
|
||||
NodeKind::Path { path, guide: false, clipping: false, .. } => path.subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
NodeKind::Compound { .. } => super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty()),
|
||||
// A compound path is written as one path of its members' subpaths, without their masks.
|
||||
NodeKind::Compound { children, .. } => {
|
||||
children.iter().all(|c| unmasked(c)) && super::compound_path(n).subpaths.iter().any(|sp| !sp.anchors.is_empty())
|
||||
}
|
||||
NodeKind::Group { children, clip: false } => !children.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
@@ -247,7 +268,7 @@ fn plain_art(art: &Node) -> bool {
|
||||
&& order
|
||||
&& quiet
|
||||
&& n.appearance.effects.is_empty()
|
||||
&& n.extras().mask.is_none()
|
||||
&& n.extras().mask.as_deref().is_none_or(|m| masks > 0 && plain_within(&m.art, masks - 1))
|
||||
&& n.opacity >= 1.0
|
||||
&& n.blend == BlendMode::Normal;
|
||||
});
|
||||
@@ -258,8 +279,13 @@ fn plain_art(art: &Node) -> bool {
|
||||
/// compound path with the subpaths of all its members as one path ([`super::compound_path`]), is
|
||||
/// written as one path when it has one subpath with points and as a compound path when it has more
|
||||
/// ([`Writer::plain_object`]); the reader reads that compound path as one path for each subpath,
|
||||
/// each with the object's paint.
|
||||
/// each with the object's paint. An opacity mask's art is written shown ([`Writer::mask`]).
|
||||
fn as_read(art: &mut Node) {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
let mask_art = Arc::make_mut(&mut m.art);
|
||||
mask_art.visible = true;
|
||||
as_read(mask_art);
|
||||
}
|
||||
let (subpaths, rule) = match &art.kind {
|
||||
NodeKind::Path { path, rule, .. } => (path.subpaths.clone(), *rule),
|
||||
NodeKind::Compound { rule, .. } => (super::compound_path(art).subpaths, *rule),
|
||||
@@ -390,7 +416,7 @@ impl Writer<'_> {
|
||||
}
|
||||
let mut read = a.clone();
|
||||
if *to_section == Affine::IDENTITY {
|
||||
read.transform(Affine::FLIP_Y, false);
|
||||
crate::import::turn_brush_art_over(&mut read);
|
||||
}
|
||||
as_read(&mut read);
|
||||
Some(read)
|
||||
@@ -427,6 +453,9 @@ impl Writer<'_> {
|
||||
// The art is the brush's own: not on `%_` lines, in a drawn look or in a symbol that
|
||||
// first uses the brush.
|
||||
(std::mem::take(&mut self.hidden), std::mem::take(&mut self.in_look), std::mem::take(&mut self.in_symbol)),
|
||||
// The layers' objects written with art styles, by id: none of them is the brush's art,
|
||||
// which may hold objects with the same ids.
|
||||
std::mem::take(&mut self.styled),
|
||||
);
|
||||
(self.to_art, self.grad_space, self.canvas, self.block_end) = (to_section, to_section, to_section, usize::MAX);
|
||||
self.state(false, false);
|
||||
@@ -462,6 +491,7 @@ impl Writer<'_> {
|
||||
(self.clip, self.shown),
|
||||
(self.block_start, self.block_end),
|
||||
(self.hidden, self.in_look, self.in_symbol),
|
||||
self.styled,
|
||||
) = saved;
|
||||
let text = std::mem::replace(&mut self.body, body);
|
||||
if !std::mem::replace(&mut self.warnings, warnings).is_empty() {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
|
||||
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
|
||||
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! contents in an `X=` … `X+` block (in a symbol's art, in the canvas's space with y down; while
|
||||
//! they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side
|
||||
@@ -401,7 +402,13 @@ impl Writer<'_> {
|
||||
if *editing {
|
||||
self.grid(record.grid.as_ref());
|
||||
} else if self.open_group("u") {
|
||||
// In a symbol's art, the contents in the dictionary are in the canvas's space, y down.
|
||||
let to_art = self.to_art;
|
||||
if self.in_symbol {
|
||||
self.to_art = Affine::translate(self.canvas_origin) * to_art;
|
||||
}
|
||||
self.contents(content, true);
|
||||
self.to_art = to_art;
|
||||
self.end_group("U", Xy::PLAIN);
|
||||
}
|
||||
let block = std::mem::replace(&mut self.body, outer);
|
||||
@@ -448,15 +455,17 @@ impl Writer<'_> {
|
||||
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
|
||||
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
|
||||
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
|
||||
/// towards the previous one and a weight, in art space), from its top left one down, across and
|
||||
/// up, and `/E`. One object.
|
||||
/// towards the previous one and a weight, in art space; in a symbol's art, in the space a
|
||||
/// gradient mesh's corners are written in there), from its top left one down, across and up,
|
||||
/// and `/E`. One object.
|
||||
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
|
||||
let Some((rows, cols, pts)) = grid else { return };
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
let (rows, cols, width) = (*rows, *cols, cols + 1);
|
||||
let to_art = self.to_art;
|
||||
// In a symbol's art, corners are written in the space a gradient mesh's are written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
let s = &mut self.body;
|
||||
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
|
||||
let num = |s: &mut String, v: f64| {
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Gradient meshes: a mesh as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader,
|
||||
//! `mesh.rs` and `read/art.rs`' `end_mesh`).
|
||||
//!
|
||||
//! `/Mesh X!`, then on `%_` lines `value /key X#` entries: `2 /Version` (corners with an opacity),
|
||||
//! `/Cartesian /Type`, `[rows cols] /Size`, `/Data` (the patches follow), and for each patch, row by
|
||||
//! row, its place `[row col] /P`, the color space (`/DeviceGray`,
|
||||
//! `/DeviceRGB` or `/DeviceCMYK`) with `/CS` where it changes, its four corners with `/N` and `/E`;
|
||||
//! then `/End X!`. A corner is `[color… opacity x y nx ny 1 px py 1]` in art space (in a symbol's
|
||||
//! art, in the canvas's space turned y up about art space's origin there, as an image's matrix in
|
||||
//! it is): its color (gray as lightness), its opacity, the point, the
|
||||
//! handle towards the next corner and the handle towards the one before it, each with a weight of 1.
|
||||
//! The corners go from the patch's top left mesh point to the one below it, then to the right, then
|
||||
//! up: the first index of `/P` runs along the first edge. The mesh's transparency is set before it
|
||||
//! (`0 XR`, `Xy`), its name and opacity mask follow `/End X!` in an `/ArtDictionary`, then `0 0 Xd`
|
||||
//! and `6 () XW`.
|
||||
//!
|
||||
//! Each record is read back with the reader's mesh reading ([`crate::import::mesh_reads`], the
|
||||
//! patches and how they join; not the rest of the `.ai` reader) before it is written: a mesh it
|
||||
//! would read otherwise is written as its drawn look, as are folded meshes (patches whose corners
|
||||
//! turn different ways, along the handles there, or a corner with no angle), meshes in pattern
|
||||
//! tiles and in art cut to a clipping object, and every mesh on a large canvas. A reflected mesh,
|
||||
//! whose patches all turn the negative way, is written with its columns in reverse order: it draws
|
||||
//! the same patches, and reads back with each row's points in reverse order.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{Writer, Xy};
|
||||
use crate::ai_ops::unit;
|
||||
use crate::import::{MAX_MESH_SIDE, mesh_reads};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const MESHES: &str = "gradient meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes that would not open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every gradient mesh on a large canvas are written as their drawn look in the editing data for other apps";
|
||||
|
||||
/// How far (in the document's units, at a scale of 1) a written point or handle's end may move:
|
||||
/// coordinates are written to 4 decimals, which moves a point at most 0.00005 along each axis.
|
||||
const SETTLE_POINT: f64 = 1e-4;
|
||||
/// How far a written color channel or opacity may move: they are written to 4 decimals too.
|
||||
const SETTLE_COLOR: f32 = 1e-4;
|
||||
|
||||
/// The color space a corner's color is written in.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Space {
|
||||
Gray,
|
||||
Rgb,
|
||||
Cmyk,
|
||||
}
|
||||
|
||||
impl Space {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Space::Gray => "/DeviceGray",
|
||||
Space::Rgb => "/DeviceRGB",
|
||||
Space::Cmyk => "/DeviceCMYK",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Mesh `m`'s record as the reader reads it, or `None` when it would read it otherwise (the
|
||||
/// mesh is then written as its drawn look).
|
||||
pub(super) fn mesh_record(&self, m: &GradientMesh) -> Option<String> {
|
||||
// Art cut to a clipping object is written cut, which a mesh can't be. Meshes in pattern
|
||||
// tiles and on a large canvas are written as their drawn look too. (A mesh holds no objects,
|
||||
// so it is written as a mesh however deep it is nested.) A grid the reader doesn't read as
|
||||
// one mesh is left before its record is built.
|
||||
if !self.meshes_live
|
||||
|| self.clip.is_some()
|
||||
|| !self.defining.is_empty()
|
||||
|| !m.is_valid()
|
||||
|| m.rows as usize > MAX_MESH_SIDE
|
||||
|| m.cols as usize > MAX_MESH_SIDE
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// In a symbol's art, corners are written in the space an image's matrix is written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
// Every patch turns the positive way where it is written: from its first corner, the second
|
||||
// (below it) then the fourth (beside it) go anticlockwise, y up. A reflected mesh, whose
|
||||
// patches all turn the other way, is written with its columns in reverse order, which turns
|
||||
// each of them the positive way and draws the same mesh; any other mesh with a patch that
|
||||
// doesn't turn the positive way is written as its drawn look.
|
||||
let reversed;
|
||||
let m = match turns(m, to_art)? {
|
||||
true => m,
|
||||
false => {
|
||||
reversed = columns_reversed(m);
|
||||
&reversed
|
||||
}
|
||||
};
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
// Version 2: each corner has an opacity.
|
||||
let mut s = String::from("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n");
|
||||
let _ = writeln!(s, "%_[{rows} {cols}] /Size X#\n%_/Data X#");
|
||||
let mut space = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let _ = writeln!(s, "%_[{r} {c}] /P X#");
|
||||
// From the top left point down, right and up; each with its handles towards the
|
||||
// next corner and the one before it.
|
||||
for (p, next, prev) in
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)]
|
||||
{
|
||||
corner(&mut s, &mut space, to_art, p, next, prev)?;
|
||||
}
|
||||
s.push_str("%_/E X#\n");
|
||||
}
|
||||
}
|
||||
s.push_str("/End X!\n");
|
||||
let read = mesh_reads(s.as_bytes(), to_art.inverse())?;
|
||||
same_mesh(&read, m, SETTLE_POINT * to_art.inverse().determinant().abs().sqrt().max(1.0)).then_some(s)
|
||||
}
|
||||
|
||||
/// Mesh `n` written as `record`: its transparency before it (`xy`), the record, and the block
|
||||
/// its name and opacity mask go before ([`Self::node`]). The mesh is one object
|
||||
/// ([`Self::take_objects`]); nothing is written when there is no room for it.
|
||||
pub(super) fn write_mesh(&mut self, record: &str, xy: Xy) {
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
self.set_object_xy(xy.object());
|
||||
self.body.push_str(record);
|
||||
self.block_start = self.body.len();
|
||||
self.line("0 0 Xd\n6 () XW");
|
||||
self.block_end = self.body.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way every patch of `m` turns where `to_art` takes it, at each of its four corners, from
|
||||
/// its top left point to the one below it, then right and up, y up: `Some(true)` when all turn
|
||||
/// anticlockwise, `Some(false)` when all turn clockwise, and `None` when they differ (a patch
|
||||
/// folded across itself, or patches folded over each other) or a corner has no angle. Each corner
|
||||
/// is measured twice: along the straight lines to the next corners, and along its handles (towards
|
||||
/// the next corners where a handle is zero), where the patch's edges leave it.
|
||||
fn turns(m: &GradientMesh, to_art: Affine) -> Option<bool> {
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
let mut way = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
// Each corner with the slots of its handles towards the next corner and the one before it.
|
||||
let corners =
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)];
|
||||
for i in 0..4 {
|
||||
let (before, (here, next, prev), after) = (corners[(i + 3) % 4].0, corners[i], corners[(i + 1) % 4].0);
|
||||
let line = |to: &MeshPoint| to_art * to.p - to_art * here.p;
|
||||
let along = |h: usize, to: &MeshPoint| -> Option<Vec2> {
|
||||
let h = *here.handles.get(h)?;
|
||||
Some(if h == Vec2::ZERO { line(to) } else { to_art * (here.p + h) - to_art * here.p })
|
||||
};
|
||||
for cross in [line(after).cross(line(before)), along(next, after)?.cross(along(prev, before)?)] {
|
||||
let positive = match cross {
|
||||
x if x > 0.0 => true,
|
||||
x if x < 0.0 => false,
|
||||
_ => return None,
|
||||
};
|
||||
if *way.get_or_insert(positive) != positive {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
way
|
||||
}
|
||||
|
||||
/// `m` with its columns in reverse order: each row's points from the last to the first, each
|
||||
/// point's handles to the right and left swapped. It draws the same mesh.
|
||||
fn columns_reversed(m: &GradientMesh) -> GradientMesh {
|
||||
let width = m.cols as usize + 1;
|
||||
let points = m
|
||||
.points
|
||||
.chunks(width)
|
||||
.flat_map(|row| {
|
||||
row.iter().rev().map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.handles.swap(H_RIGHT, H_LEFT);
|
||||
p
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
GradientMesh { rows: m.rows, cols: m.cols, points }
|
||||
}
|
||||
|
||||
/// A corner `p` of a patch: its color space when it changes (in `space`), then `[color… opacity x y
|
||||
/// nx ny 1 px py 1] /N X#` with its handles `next` and `prev`, `to_art` taking the document to the
|
||||
/// space the corners are written in.
|
||||
fn corner(s: &mut String, space: &mut Option<Space>, to_art: Affine, p: &MeshPoint, next: usize, prev: usize) -> Option<()> {
|
||||
let (sp, values): (Space, Vec<f32>) = match p.color {
|
||||
// The format's gray is lightness.
|
||||
Color::Gray { k } => (Space::Gray, vec![1.0 - unit(k)]),
|
||||
Color::Rgb { r, g, b } => (Space::Rgb, vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (Space::Cmyk, vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
// The reader reads no Lab mesh colors.
|
||||
Color::Lab { .. } => return None,
|
||||
};
|
||||
if *space != Some(sp) {
|
||||
let _ = writeln!(s, "%_{} /CS X#", sp.name());
|
||||
*space = Some(sp);
|
||||
}
|
||||
let art = |q: Point| to_art * q;
|
||||
let (at, n, b) = (art(p.p), art(p.p + *p.handles.get(next)?), art(p.p + *p.handles.get(prev)?));
|
||||
s.push_str("%_[");
|
||||
for v in values {
|
||||
ps::push_num(s, f64::from(v));
|
||||
s.push(' ');
|
||||
}
|
||||
ps::push_num(s, f64::from(unit(p.opacity)));
|
||||
for v in [at.x, at.y, n.x, n.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1");
|
||||
for v in [b.x, b.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1] /N X#\n");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether `read` is `m` as written: the same grid, each point within `tol` of its place, each
|
||||
/// handle that points into the grid within `tol` (the reader gives the others none, and they draw
|
||||
/// nothing), each color in the same model and within [`SETTLE_COLOR`] a channel, and each opacity
|
||||
/// within it.
|
||||
fn same_mesh(read: &GradientMesh, m: &GradientMesh, tol: f64) -> bool {
|
||||
if (read.rows, read.cols) != (m.rows, m.cols) || read.points.len() != m.points.len() {
|
||||
return false;
|
||||
}
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let near = |a: Point, b: Point| (a - b).hypot() <= tol * (1.0 + 1e-9 * a.to_vec2().hypot());
|
||||
read.points.iter().zip(&m.points).enumerate().all(|(i, (a, b))| {
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
let inside = [c < cols, c > 0, r < rows, r > 0];
|
||||
let handles = [H_RIGHT, H_LEFT, H_DOWN, H_UP].iter().zip(inside).all(|(&h, inside)| {
|
||||
!inside || near(a.p + a.handles.get(h).copied().unwrap_or(Vec2::ZERO), b.p + b.handles.get(h).copied().unwrap_or(Vec2::ZERO))
|
||||
});
|
||||
near(a.p, b.p) && handles && same_color(&a.color, &b.color) && (a.opacity - unit(b.opacity)).abs() <= SETTLE_COLOR
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `a` is `b` as written: the same model, each channel within [`SETTLE_COLOR`] of `b`'s
|
||||
/// clamped to 0 to 1.
|
||||
fn same_color(a: &Color, b: &Color) -> bool {
|
||||
let close = |x: &[f32], y: &[f32]| x.iter().zip(y).all(|(x, y)| (x - unit(*y)).abs() <= SETTLE_COLOR);
|
||||
match (a, b) {
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => close(&[*k], &[*k2]),
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => close(&[*r, *g, *b], &[*r2, *g2, *b2]),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => close(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,10 @@ pub use ai::NameEncoding;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::objects_read;
|
||||
pub(crate) use ai::{
|
||||
BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object,
|
||||
read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS,
|
||||
MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads,
|
||||
brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list,
|
||||
style_moves_with, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN};
|
||||
|
||||
@@ -34,14 +34,20 @@ use std::io::Read as _;
|
||||
use super::lex::find;
|
||||
use crate::ps;
|
||||
|
||||
pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object};
|
||||
pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads};
|
||||
pub(crate) use brush::{
|
||||
BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over,
|
||||
};
|
||||
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
|
||||
pub(crate) use envelope::MAX_CHECKED;
|
||||
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
|
||||
pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright};
|
||||
pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID};
|
||||
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
|
||||
#[cfg(test)]
|
||||
pub(crate) use frames::TEXT_FRAME_SCANS;
|
||||
pub(crate) use frames::text_frames;
|
||||
pub(crate) use mesh::{MAX_SIDE as MAX_MESH_SIDE, mesh_reads};
|
||||
pub use obj::{NameEncoding, Names};
|
||||
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
|
||||
#[cfg(test)]
|
||||
@@ -50,14 +56,14 @@ pub(crate) use read::objects_read;
|
||||
pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame,
|
||||
slot_of, style_moves_with, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
pub(crate) use read::{
|
||||
MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, slot_of,
|
||||
style_moves_with, symbol_art_member,
|
||||
};
|
||||
|
||||
pub(crate) use read::is_look_slot;
|
||||
pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number};
|
||||
|
||||
@@ -15,11 +15,14 @@
|
||||
//!
|
||||
//! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is
|
||||
//! Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2
|
||||
//! is the distance in points, as a 32-bit float. Word 10 is the number of keys, and the words after
|
||||
//! it are a record of six words per key that starts with the key's id. For Specified Steps, the
|
||||
//! steps between two keys are counted from the steps drawn. The orientation is taken from the steps
|
||||
//! drawn: whichever one lays the blend out as they are drawn. A blend whose parts don't agree,
|
||||
//! whose spacing isn't one of these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
//! is the distance in points, as a 32-bit float. Word 5 is 0 for Align to Page and, for Align to
|
||||
//! Path, a 32-bit float of 8 or more. Word 10 is the number of keys, and the words after it are a
|
||||
//! record of six words per key that starts with the key's id. For Specified Steps, the steps
|
||||
//! between two keys are counted from the steps drawn. The orientation is the record's when it lays
|
||||
//! the blend out as the steps are drawn, else whichever one does (the closest when both do). A blend
|
||||
//! with no spine part whose record names its keys in their order has no spine of its own: it runs
|
||||
//! straight between its keys' centers. A blend whose parts don't agree, whose spacing isn't one of
|
||||
//! these, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -28,19 +31,19 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::blend::{blend_expand, blend_steps};
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
use vectorcraft_geom::{ParamCurve, PathData, Point, SubPath};
|
||||
|
||||
/// The plugin that writes blends.
|
||||
pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
pub(crate) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
/// The most bytes of a blend's record read.
|
||||
pub(super) const MAX_RECORD: usize = 4096;
|
||||
/// The most keys read from one blend.
|
||||
const MAX_KEYS: usize = 64;
|
||||
pub(crate) const MAX_KEYS: usize = 64;
|
||||
/// The most steps between two keys (Blend Options' limit).
|
||||
const MAX_STEPS: usize = 1000;
|
||||
/// The most objects (keys and steps) one blend may lay out to be read live; more keep their
|
||||
/// drawn steps.
|
||||
pub(super) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
pub(crate) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
/// How far (pt) a step laid out here may be from where the file draws it.
|
||||
const PLACE_TOLERANCE: f64 = 0.5;
|
||||
/// How far a step's colour (each channel, 0 to 1) may be from the drawn one.
|
||||
@@ -66,6 +69,8 @@ pub(super) struct Record {
|
||||
pub(super) ids: Vec<String>,
|
||||
/// `None`: Specified Steps, whose steps the reader counts from the drawn ones.
|
||||
pub(super) spacing: Option<BlendSpacing>,
|
||||
/// The orientation word 5 names, when it names one.
|
||||
pub(super) orientation: Option<BlendOrientation>,
|
||||
}
|
||||
|
||||
/// A blend's record, or `None` for a record that isn't one or whose spacing isn't read: an
|
||||
@@ -82,7 +87,18 @@ pub(super) fn record(bytes: &[u8]) -> Option<Record> {
|
||||
_ => return None,
|
||||
};
|
||||
let ids = record_ids(&words)?;
|
||||
Some(Record { ids, spacing })
|
||||
let orientation = words.get(5).and_then(|w| orientation(*w));
|
||||
Some(Record { ids, spacing, orientation })
|
||||
}
|
||||
|
||||
/// The orientation in a record's word 5: 0 is Align to Page, a 32-bit float of 8 or more Align to
|
||||
/// Path; anything else names none.
|
||||
fn orientation(bits: u32) -> Option<BlendOrientation> {
|
||||
if bits == 0 {
|
||||
return Some(BlendOrientation::AlignToPage);
|
||||
}
|
||||
let a = f32::from_bits(bits);
|
||||
(a.is_finite() && a >= 8.0).then_some(BlendOrientation::AlignToPath)
|
||||
}
|
||||
|
||||
/// The distance in a record's word `bits` (a 32-bit float), as the shortest decimal that reads
|
||||
@@ -131,6 +147,7 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if keys.len() < 2 || named.len() != keys.len() || ids.len() != keys.len() {
|
||||
return None;
|
||||
}
|
||||
let in_order = named.iter().zip(ids).all(|(n, id)| *n == id.as_str());
|
||||
named.sort_unstable();
|
||||
let mut listed: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
listed.sort_unstable();
|
||||
@@ -150,12 +167,20 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
})
|
||||
.collect();
|
||||
// A blend whose spine was never edited has none written: its spine is the straight lines
|
||||
// between the keys' centres, in the record's order.
|
||||
let spine = match spine {
|
||||
Some(spine) => spine,
|
||||
None => straight_spine(&keys, ids, roles)?,
|
||||
// between the keys' centers, in the record's order. With the keys in that order it is the
|
||||
// spine of a blend that has none of its own.
|
||||
let (spine, key_anchors) = match spine {
|
||||
Some(spine) => {
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
None if in_order => (None, vec![]),
|
||||
None => {
|
||||
let spine = straight_spine(&keys, ids, roles)?;
|
||||
let anchors = on_spine(&keys, &spine)?;
|
||||
(Some(spine), anchors)
|
||||
}
|
||||
};
|
||||
let key_anchors = on_spine(&keys, &spine)?;
|
||||
let spacing = match record.spacing {
|
||||
// Specified Steps: the steps between two keys are the drawn objects that aren't keys,
|
||||
// shared out.
|
||||
@@ -170,26 +195,68 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol
|
||||
if cost > *budget {
|
||||
return None;
|
||||
}
|
||||
let spec = BlendSpec { spacing, spine: Some(spine), key_anchors, ..BlendSpec::default() };
|
||||
let spec = BlendSpec { spacing, spine, key_anchors, ..BlendSpec::default() };
|
||||
// As many objects as the spacing lays out between each pair of keys (the orientation doesn't
|
||||
// change how many), counted before anything is laid out: as many as are drawn.
|
||||
if blend_steps(&keys, &spec).into_iter().fold(keys.len(), usize::saturating_add) != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
*budget -= cost;
|
||||
// The drawn steps' centres and paints, once.
|
||||
let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::<Option<_>>()?;
|
||||
// The orientation that lays the steps out as drawn, the closest when both do.
|
||||
[BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
// The drawn steps as the check compares them, once.
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d)).collect::<Option<_>>()?;
|
||||
// The orientations that lay the steps out as drawn (the check compares the steps' centers, which
|
||||
// turning the steps along the spine leaves in place). Of those that also lay them out at their
|
||||
// drawn sizes and turned as drawn, the record's, else the closest; when none does, the closest
|
||||
// of them all.
|
||||
let fits: Vec<(f64, BlendSpec, Vec<Node>)> = [BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
.into_iter()
|
||||
.filter_map(|orientation| {
|
||||
let spec = BlendSpec { orientation, ..spec.clone() };
|
||||
let laid = blend_expand(&keys, &spec);
|
||||
let off = how_far(&laid, &drawn)?;
|
||||
Some((off, spec))
|
||||
let off = how_far(&laid, &drawn, false)?;
|
||||
Some((off, spec, laid))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, spec)| NodeKind::Blend { children: keys, spec: Box::new(spec) })
|
||||
.collect();
|
||||
let as_drawn: Vec<&(f64, BlendSpec, Vec<Node>)> = fits.iter().filter(|(_, _, laid)| how_far(laid, &drawn, true).is_some()).collect();
|
||||
as_drawn
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(_, s, _)| Some(s.orientation) == record.orientation)
|
||||
.or_else(|| as_drawn.iter().copied().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.or_else(|| fits.iter().min_by(|a, b| a.0.total_cmp(&b.0)))
|
||||
.map(|(_, spec, _)| NodeKind::Blend { children: keys, spec: Box::new(spec.clone()) })
|
||||
}
|
||||
|
||||
/// What the reader makes of a blend written as the key objects `keys`, named by `ids` in their
|
||||
/// order, the spine `spine` (`None`: no spine part), the record `bytes` and the drawn steps `drawn`:
|
||||
/// the live blend's settings, or `None` where it keeps the drawn steps. Takes from `budget` as
|
||||
/// [`live_blend`] does.
|
||||
pub(crate) fn blend_reads(
|
||||
keys: &[Arc<Node>],
|
||||
ids: &[String],
|
||||
spine: Option<&PathData>,
|
||||
bytes: &[u8],
|
||||
drawn: &[Node],
|
||||
budget: &mut usize,
|
||||
) -> Option<BlendSpec> {
|
||||
let record = record(bytes)?;
|
||||
let mut roles = Roles::new();
|
||||
let mut parts: Vec<Arc<Node>> = Vec::with_capacity(keys.len() + 1);
|
||||
for (k, id) in keys.iter().zip(ids) {
|
||||
roles.insert(k.id, ("K".to_string(), Some(id.clone())));
|
||||
parts.push(k.clone());
|
||||
}
|
||||
if let Some(s) = spine {
|
||||
let id = NodeId(u64::MAX);
|
||||
roles.insert(id, ("S".to_string(), None));
|
||||
parts.push(Arc::new(Node::path(id, s.clone(), Default::default())));
|
||||
}
|
||||
let edit = Node::new(NodeId(u64::MAX - 1), NodeKind::Group { children: parts, clip: false });
|
||||
let drawn = Node::new(NodeId(u64::MAX - 2), NodeKind::Group { children: drawn.iter().cloned().map(Arc::new).collect(), clip: false });
|
||||
match live_blend(&edit, &drawn, &record, &roles, budget)? {
|
||||
NodeKind::Blend { spec, .. } => Some(*spec),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a
|
||||
@@ -227,6 +294,117 @@ fn centre(n: &Node) -> Option<Point> {
|
||||
n.geometric_bounds().map(|b| b.center()).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// The most anchors of an object's paths the check compares; an object with more is compared by its
|
||||
/// size alone.
|
||||
const MAX_MARK_ANCHORS: usize = 64;
|
||||
/// The most drawn objects whose outlines one check compares, spread evenly from the first to the
|
||||
/// last; the rest are compared by their sizes alone (the orientation turns every step alike).
|
||||
const MAX_OUTLINE_CHECKS: usize = 16;
|
||||
/// The most outline comparisons one check makes (a drawn object compared can have more than one
|
||||
/// laid object in its place); past them, a drawn object whose outline is to be compared matches
|
||||
/// none.
|
||||
const MAX_OUTLINE_COMPARISONS: usize = 4 * MAX_OUTLINE_CHECKS;
|
||||
|
||||
/// An object as the check compares it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Drawn<'a> {
|
||||
centre: Point,
|
||||
fill: Fill,
|
||||
/// Its width and height.
|
||||
size: Point,
|
||||
/// The object, for its paths' outline ([`outline`]), which turning it moves.
|
||||
node: &'a Node,
|
||||
}
|
||||
|
||||
/// `n` as the check compares it, or `None` when it has no finite bounds.
|
||||
fn drawn_as(n: &Node) -> Option<Drawn<'_>> {
|
||||
let size = n.geometric_bounds().map(|b| Point::new(b.width(), b.height())).filter(|p| p.x.is_finite() && p.y.is_finite())?;
|
||||
Some(Drawn { centre: centre(n)?, fill: fill(n), size, node: n })
|
||||
}
|
||||
|
||||
/// How the check compares an object's turn.
|
||||
enum Outline {
|
||||
/// By its outline: every subpath of more than one anchor of its paths, in any order, each with
|
||||
/// its path's fill, so that a turn that trades the places of paths painted differently doesn't
|
||||
/// pass.
|
||||
Paths(Vec<(Fill, SubPath)>),
|
||||
/// By its size alone: it holds art whose drawing isn't its members (a blend, an envelope, a
|
||||
/// repeat), art past eight levels down, more than [`MAX_MARK_ANCHORS`] anchors or no subpath to
|
||||
/// compare.
|
||||
Size,
|
||||
}
|
||||
|
||||
/// How the check compares `n`'s turn (the members of its groups and compound paths looked through,
|
||||
/// at most eight levels down; a compound path's members take its fill).
|
||||
fn outline(n: &Node) -> Outline {
|
||||
/// What the walk found.
|
||||
#[derive(Default)]
|
||||
struct Walk {
|
||||
subpaths: Vec<(Fill, SubPath)>,
|
||||
anchors: usize,
|
||||
/// Art compared by the size alone, or too many anchors.
|
||||
size_only: bool,
|
||||
}
|
||||
fn add(n: &Node, depth: usize, painted: Option<Fill>, w: &mut Walk) {
|
||||
if w.size_only {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
// A subpath of one anchor has no segment to compare with.
|
||||
for s in path.subpaths.iter().filter(|s| s.anchors.len() > 1) {
|
||||
w.anchors = w.anchors.saturating_add(s.anchors.len());
|
||||
if w.anchors > MAX_MARK_ANCHORS {
|
||||
w.size_only = true;
|
||||
return;
|
||||
}
|
||||
w.subpaths.push((f, s.clone()));
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } if depth < 8 => {
|
||||
for c in children {
|
||||
add(c, depth + 1, painted, w);
|
||||
}
|
||||
}
|
||||
NodeKind::Compound { children, .. } if depth < 8 => {
|
||||
let f = painted.unwrap_or_else(|| fill(n));
|
||||
for c in children {
|
||||
add(c, depth + 1, Some(f), w);
|
||||
}
|
||||
}
|
||||
_ => w.size_only = true,
|
||||
}
|
||||
}
|
||||
let mut w = Walk::default();
|
||||
add(n, 0, None, &mut w);
|
||||
if w.size_only || w.subpaths.is_empty() { Outline::Size } else { Outline::Paths(w.subpaths) }
|
||||
}
|
||||
|
||||
/// Do two outlines ([`Outline::Paths`]) draw the same lines in the same fills: each anchor of one,
|
||||
/// and the points a quarter, half and three quarters along each of its segments (which show how a
|
||||
/// curved side bends), within `tolerance` of the other's subpaths of a fill that matches its own?
|
||||
/// Where a path starts, how many anchors it has on a straight or curved stretch, and the order of
|
||||
/// the paths don't count.
|
||||
fn same_outline(a: &[(Fill, SubPath)], b: &[(Fill, SubPath)], tolerance: f64) -> bool {
|
||||
let on = |from: &[(Fill, SubPath)], to: &[(Fill, SubPath)]| {
|
||||
from.iter().all(|(f, s)| {
|
||||
// Fills the check can't compare (gradients, patterns) are compared with each other by
|
||||
// their outline alone.
|
||||
let to = PathData::new(
|
||||
to.iter().filter(|(g, _)| same_fill(*f, *g) || (*f == Fill::Other && *g == Fill::Other)).map(|(_, t)| t.clone()).collect(),
|
||||
);
|
||||
let near = |p: Point| to.nearest(p).is_some_and(|(.., d)| d <= tolerance);
|
||||
s.anchors.iter().all(|p| near(p.p))
|
||||
&& (0..s.segment_count()).all(|i| {
|
||||
let c = s.segment(i);
|
||||
[0.25, 0.5, 0.75].into_iter().all(|t| near(c.eval(t)))
|
||||
})
|
||||
})
|
||||
};
|
||||
on(a, b) && on(b, a)
|
||||
}
|
||||
|
||||
/// An object's fill, as far as the check compares it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fill {
|
||||
@@ -267,31 +445,76 @@ fn same_fill(a: Fill, b: Fill) -> bool {
|
||||
/// farthest, each drawn object matched to a laid one of its own within the tolerance (each laid
|
||||
/// one matches one drawn one: the nearest still free; through a grid of cells the tolerance wide,
|
||||
/// so each finds its neighbours without looking at them all), when they are as many and each
|
||||
/// matches in place and fill; else `None` (also when that matching leaves one out).
|
||||
fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option<f64> {
|
||||
/// matches in place and fill, and with `turned` also in width and height and, for at most
|
||||
/// [`MAX_OUTLINE_CHECKS`] drawn objects spread from the first to the last, in the outline of its
|
||||
/// paths (each within twice the tolerance), which turning an object changes; else `None` (also when
|
||||
/// that matching leaves one out, and when it would take more than [`MAX_OUTLINE_COMPARISONS`]
|
||||
/// outline comparisons).
|
||||
fn how_far(laid: &[Node], drawn: &[Drawn], turned: bool) -> Option<f64> {
|
||||
if laid.len() != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
let cell = |p: Point| ((p.x / PLACE_TOLERANCE).floor() as i64, (p.y / PLACE_TOLERANCE).floor() as i64);
|
||||
let laid: Vec<(Point, Fill)> = laid.iter().map(|l| Some((centre(l)?, fill(l)))).collect::<Option<_>>()?;
|
||||
let laid: Vec<Drawn> = laid.iter().map(drawn_as).collect::<Option<_>>()?;
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::with_capacity(laid.len());
|
||||
for (i, (p, _)) in laid.iter().enumerate() {
|
||||
grid.entry(cell(*p)).or_default().push(i);
|
||||
for (i, l) in laid.iter().enumerate() {
|
||||
grid.entry(cell(l.centre)).or_default().push(i);
|
||||
}
|
||||
let close = |a: Point, b: Point| (a.x - b.x).abs() <= 2.0 * PLACE_TOLERANCE && (a.y - b.y).abs() <= 2.0 * PLACE_TOLERANCE;
|
||||
// The drawn objects whose outlines are compared: all of them, or as many as the limit allows,
|
||||
// spread evenly so that the first and the last are among them.
|
||||
let mut compare_outline = vec![drawn.len() <= MAX_OUTLINE_CHECKS; drawn.len()];
|
||||
if drawn.len() > MAX_OUTLINE_CHECKS {
|
||||
for j in 0..MAX_OUTLINE_CHECKS {
|
||||
if let Some(c) = compare_outline.get_mut(j * (drawn.len() - 1) / (MAX_OUTLINE_CHECKS - 1)) {
|
||||
*c = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let outlines_compared = std::cell::Cell::new(0usize);
|
||||
let same_turn = |l: &Drawn, d: &Drawn, compare: bool| {
|
||||
if !turned {
|
||||
return true;
|
||||
}
|
||||
if !close(l.size, d.size) || !compare {
|
||||
return close(l.size, d.size);
|
||||
}
|
||||
// An outline that isn't compared doesn't count as the same.
|
||||
if outlines_compared.get() >= MAX_OUTLINE_COMPARISONS {
|
||||
return false;
|
||||
}
|
||||
outlines_compared.set(outlines_compared.get() + 1);
|
||||
match (outline(l.node), outline(d.node)) {
|
||||
(Outline::Paths(a), Outline::Paths(b)) => same_outline(&a, &b, 2.0 * PLACE_TOLERANCE),
|
||||
// Live art against its drawing, too many anchors, or no paths: compared by the size
|
||||
// alone.
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let mut used = vec![false; laid.len()];
|
||||
let mut worst: f64 = 0.0;
|
||||
for &(c, f) in drawn {
|
||||
for (k, d) in drawn.iter().enumerate() {
|
||||
let (c, f) = (d.centre, d.fill);
|
||||
let compare = compare_outline.get(k).copied().unwrap_or(false);
|
||||
let (cx, cy) = cell(c);
|
||||
// Coordinates far out saturate the cells: the neighbours' keys saturate too.
|
||||
let (i, near) = (-1i64..=1)
|
||||
let candidates = (-1i64..=1)
|
||||
.flat_map(|dx| (-1i64..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy))))
|
||||
.filter_map(|k| grid.get(&k))
|
||||
.flatten()
|
||||
.filter(|&&i| !used.get(i).copied().unwrap_or(true))
|
||||
.filter_map(|&i| laid.get(i).map(|l| (i, l)))
|
||||
.filter(|(_, (p, lf))| (*p - c).hypot() <= PLACE_TOLERANCE && same_fill(*lf, f))
|
||||
.map(|(i, (p, _))| (i, (*p - c).hypot()))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
.filter(|(_, l)| (l.centre - c).hypot() <= PLACE_TOLERANCE && same_fill(l.fill, f));
|
||||
let (i, near) = if turned && compare {
|
||||
// Outlines are tried nearest first, so that steps crowded in one place don't spend the
|
||||
// outline comparisons on candidates farther off.
|
||||
let mut nearest: Vec<(usize, f64)> =
|
||||
candidates.filter(|(_, l)| close(l.size, d.size)).map(|(i, l)| (i, (l.centre - c).hypot())).collect();
|
||||
nearest.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
nearest.into_iter().find(|(i, _)| laid.get(*i).is_some_and(|l| same_turn(l, d, true)))?
|
||||
} else {
|
||||
candidates.filter(|(_, l)| same_turn(l, d, false)).map(|(i, l)| (i, (l.centre - c).hypot())).min_by(|a, b| a.1.total_cmp(&b.1))?
|
||||
};
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
@@ -364,7 +587,7 @@ mod tests {
|
||||
let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false });
|
||||
let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false });
|
||||
let mut budget = 1;
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
assert!(live_blend(&edit, &drawn, &record, &Roles::new(), &mut budget).is_none());
|
||||
assert_eq!(budget, 1);
|
||||
}
|
||||
@@ -396,7 +619,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_blend_takes_from_the_budget_only_when_it_is_laid_out() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None };
|
||||
let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: None };
|
||||
let mut budget = 10;
|
||||
assert!(matches!(live_blend(&edit, &drawn, &steps, &roles, &mut budget), Some(NodeKind::Blend { .. })));
|
||||
assert_eq!(budget, 0);
|
||||
@@ -417,7 +640,7 @@ mod tests {
|
||||
let NodeKind::Group { children, .. } = &drawn.kind else { panic!("a group") };
|
||||
let keys_alone = [children[0].clone(), children[4].clone()];
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: keys_alone.to_vec(), clip: false });
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)) };
|
||||
let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)), orientation: None };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &far, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.spacing, BlendSpacing::Distance(150.0));
|
||||
@@ -427,6 +650,44 @@ mod tests {
|
||||
assert_eq!(budget, 6);
|
||||
}
|
||||
|
||||
/// Word 5 names the orientation: 0 Align to Page, a 32-bit float of 8 or more (8 and an angle)
|
||||
/// Align to Path; any other value names none, and a record too short to hold it names none.
|
||||
#[test]
|
||||
fn records_say_their_orientation() {
|
||||
let magic = u32::from_le_bytes(*b"DCBA");
|
||||
let words = |w5: u32| {
|
||||
[magic, 1, 50f32.to_bits(), 0, 3, w5, 'C' as u32, 0, 0, 1, 2, 'A' as u32, 0, 0, u32::MAX, u32::MAX, 0, 'B' as u32, 0, 1f32.to_bits()]
|
||||
.into_iter()
|
||||
.chain([u32::MAX, u32::MAX, 3])
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect::<Vec<u8>>()
|
||||
};
|
||||
let orientation = |w5: u32| record(&words(w5)).map(|r| r.orientation);
|
||||
assert_eq!(orientation(0), Some(Some(BlendOrientation::AlignToPage)));
|
||||
assert_eq!(orientation(8f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
assert_eq!(orientation(11.141593f32.to_bits()), Some(Some(BlendOrientation::AlignToPath)));
|
||||
for other in [1f32.to_bits(), 7.9f32.to_bits(), (-9f32).to_bits(), f32::NAN.to_bits(), f32::INFINITY.to_bits()] {
|
||||
assert_eq!(orientation(other), Some(None), "{other:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a level straight spine both orientations lay two squares' steps out alike: the blend takes
|
||||
/// the record's orientation, and Align to Page when the record names none.
|
||||
#[test]
|
||||
fn the_records_orientation_is_kept_where_both_lay_out_alike() {
|
||||
let (edit, drawn, roles) = two_keys();
|
||||
for (named, want) in [
|
||||
(Some(BlendOrientation::AlignToPath), BlendOrientation::AlignToPath),
|
||||
(Some(BlendOrientation::AlignToPage), BlendOrientation::AlignToPage),
|
||||
(None, BlendOrientation::AlignToPage),
|
||||
] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: named };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, want, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two drawn steps on one laid object don't both match it: each laid object matches one drawn
|
||||
/// one, so a drawing the blend doesn't lay out isn't taken for it.
|
||||
#[test]
|
||||
@@ -435,12 +696,261 @@ mod tests {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
// `laid` against the objects `drawn` as the check compares them.
|
||||
let check = |laid: &[Node], drawn: &[Node], turned: bool| {
|
||||
let drawn: Vec<Drawn> = drawn.iter().map(|d| drawn_as(d).expect("bounds")).collect();
|
||||
how_far(laid, &drawn, turned)
|
||||
};
|
||||
let laid = [square(0.0), square(50.0)];
|
||||
let c = |x: f64| (Point::new(x + 5.0, 5.0), Fill::None);
|
||||
assert!(how_far(&laid, &[c(0.0), c(50.0)]).is_some());
|
||||
assert!(how_far(&laid, &[c(0.0), c(0.1)]).is_none(), "both drawn steps near the first laid one");
|
||||
assert!(check(&laid, &[square(0.0), square(50.0)], true).is_some());
|
||||
assert!(check(&laid, &[square(0.0), square(0.1)], false).is_none(), "both drawn steps near the first laid one");
|
||||
// Sizes and outlines count only when asked for: a wider rectangle with the same center, and
|
||||
// a triangle turned a half turn.
|
||||
let wide = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, 2.5, x + 15.0, 7.5));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[wide(0.0), wide(50.0)], true).is_none());
|
||||
// Steps on one center match by their size, in whichever order they are drawn.
|
||||
let big = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x - 5.0, -5.0, x + 15.0, 15.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
assert!(check(&[square(0.0), big(0.0)], &[big(0.0), square(0.0)], true).is_some());
|
||||
// A group's members in close reds match in whichever order they are drawn.
|
||||
let reds = |x: f64, order: [usize; 3]| {
|
||||
let member = |k: usize| {
|
||||
let left = x + k as f64 * 10.0;
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(left, 0.0, left + 8.0, 8.0));
|
||||
let red = [0.25, 0.265, 0.28].get(k).copied().unwrap_or(0.0);
|
||||
Arc::new(Node::path(NodeId(0), path, vectorcraft_doc::Appearance::basic(Paint::solid(Color::rgb(red, 0.0, 0.0)), Paint::None, 0.0)))
|
||||
};
|
||||
Node::group(NodeId(0), order.iter().map(|k| member(*k)).collect())
|
||||
};
|
||||
assert!(check(&[reds(0.0, [0, 1, 2]), reds(50.0, [0, 1, 2])], &[reds(0.0, [1, 0, 2]), reds(50.0, [1, 0, 2])], true).is_some());
|
||||
// A triangle turned a half turn has its anchors elsewhere.
|
||||
let polygon = |points: &[Point]| Node::path(NodeId(0), PathData::single(SubPath::polyline(points, true)), Default::default());
|
||||
let triangle = |x: f64, turn: f64| {
|
||||
let mut n = polygon(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [triangle(0.0, 0.0), triangle(50.0, 0.0)];
|
||||
let turned = |x: f64| triangle(x, std::f64::consts::PI);
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], false).is_some());
|
||||
assert!(check(&laid, &[turned(0.0), turned(50.0)], true).is_none());
|
||||
// So has one in a group, filled with a gradient, which the check compares by its outline.
|
||||
let graded = |x: f64, turn: f64| {
|
||||
let mut t = triangle(x, turn);
|
||||
let gradient = vectorcraft_color::gradient::GradientPaint::new(vectorcraft_color::gradient::Gradient::default());
|
||||
t.appearance.set_fill(Paint::Gradient(Box::new(gradient)));
|
||||
Node::group(NodeId(0), vec![Arc::new(t)])
|
||||
};
|
||||
let in_groups = [graded(0.0, 0.0), graded(50.0, 0.0)];
|
||||
assert!(check(&in_groups, &[graded(0.0, 0.0), graded(50.0, 0.0)], true).is_some());
|
||||
assert!(check(&in_groups, &[graded(0.0, std::f64::consts::PI), graded(50.0, std::f64::consts::PI)], true).is_none());
|
||||
// The same triangle drawn from another of its anchors matches.
|
||||
let shifted = |x: f64| polygon(&[Point::new(x + 10.0, 5.0), Point::new(x, 0.0), Point::new(x, 10.0)]);
|
||||
assert!(check(&laid, &[shifted(0.0), shifted(50.0)], true).is_some());
|
||||
// So does the same triangle drawn with another anchor on one of its sides.
|
||||
let split = |x: f64| polygon(&[Point::new(x, 0.0), Point::new(x, 5.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)]);
|
||||
assert!(check(&laid, &[split(0.0), split(50.0)], true).is_some());
|
||||
// A square with its top side bent inward has the same corners as its half turn, whose bent
|
||||
// side is at the bottom: the points along its sides tell them apart.
|
||||
let bent = |x: f64, turn: f64| {
|
||||
let (tl, tr) = (Point::new(x, 0.0), Point::new(x + 10.0, 0.0));
|
||||
let anchors = vec![
|
||||
vectorcraft_geom::Anchor::with_handles(tl, tl, Point::new(x + 3.0, 4.0)),
|
||||
vectorcraft_geom::Anchor::with_handles(tr, Point::new(x + 7.0, 4.0), tr),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x + 10.0, 10.0)),
|
||||
vectorcraft_geom::Anchor::corner(Point::new(x, 10.0)),
|
||||
];
|
||||
let mut n = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, true)), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let upright = [bent(0.0, 0.0), bent(50.0, 0.0)];
|
||||
assert!(check(&upright, &[bent(0.0, 0.0), bent(50.0, 0.0)], true).is_some());
|
||||
let half = std::f64::consts::PI;
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], false).is_some());
|
||||
assert!(check(&upright, &[bent(0.0, half), bent(50.0, half)], true).is_none(), "the bent side at the bottom");
|
||||
// Past the limit of outlines compared, the last object is still among them.
|
||||
let row = |last: Node| {
|
||||
let mut row: Vec<Node> = (0..MAX_OUTLINE_CHECKS).map(|i| square(20.0 * i as f64)).collect();
|
||||
row.push(last);
|
||||
row
|
||||
};
|
||||
let end = 20.0 * MAX_OUTLINE_CHECKS as f64;
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, 0.0)), true).is_some());
|
||||
assert!(check(&row(bent(end, 0.0)), &row(bent(end, half)), true).is_none(), "the last one turned");
|
||||
// A hundred steps crowded within the tolerance of each other match their drawn copies:
|
||||
// each drawn one is compared with the nearest laid one first.
|
||||
let crowd = |turn: f64| (0..100u32).map(|i| triangle(0.4 * f64::from(i) / 99.0, turn)).collect::<Vec<_>>();
|
||||
assert!(check(&crowd(0.0), &crowd(0.0), true).is_some());
|
||||
assert!(check(&crowd(0.0), &crowd(half), true).is_none(), "the crowd turned");
|
||||
// A compound path matches with its contours in another order, and not turned a half turn.
|
||||
let pair = |x: f64, flip: bool, turn: f64| {
|
||||
let a = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 4.0), Point::new(x + 10.0, 2.0)], true);
|
||||
let b = SubPath::polyline(&[Point::new(x, 6.0), Point::new(x, 10.0), Point::new(x + 4.0, 8.0)], true);
|
||||
let subpaths = if flip { vec![b, a] } else { vec![a, b] };
|
||||
let mut n = Node::path(NodeId(0), PathData::new(subpaths), Default::default());
|
||||
n.transform(vectorcraft_geom::Affine::rotate_about(turn, Point::new(x + 5.0, 5.0)), false);
|
||||
n
|
||||
};
|
||||
let laid = [pair(0.0, false, 0.0), pair(50.0, false, 0.0)];
|
||||
assert!(check(&laid, &[pair(0.0, true, 0.0), pair(50.0, true, 0.0)], true).is_some());
|
||||
assert!(check(&laid, &[pair(0.0, true, std::f64::consts::PI), pair(50.0, true, std::f64::consts::PI)], true).is_none());
|
||||
// A lone anchor in a path draws nothing: the same path with one matches itself.
|
||||
let dotted = |x: f64| {
|
||||
let triangle = SubPath::polyline(&[Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 10.0, 5.0)], true);
|
||||
let dot = SubPath::polyline(&[Point::new(x + 3.0, 5.0)], false);
|
||||
Node::path(NodeId(0), PathData::new(vec![triangle, dot]), Default::default())
|
||||
};
|
||||
assert!(check(&[dotted(0.0), dotted(50.0)], &[dotted(0.0), dotted(50.0)], true).is_some());
|
||||
// A live blend draws more than its keys: one is compared with its drawn copy by size alone.
|
||||
let blend = |x: f64| {
|
||||
let keys = vec![Arc::new(triangle(x, 0.0)), Arc::new(triangle(x, 0.0))];
|
||||
Node::new(NodeId(0), NodeKind::Blend { children: keys, spec: Box::default() })
|
||||
};
|
||||
let expanded = |x: f64| {
|
||||
let inside = SubPath::polyline(&[Point::new(x + 3.0, 4.0), Point::new(x + 3.0, 6.0)], false);
|
||||
let inside = Node::path(NodeId(0), PathData::single(inside), Default::default());
|
||||
Node::group(NodeId(0), vec![Arc::new(triangle(x, 0.0)), Arc::new(inside)])
|
||||
};
|
||||
assert!(check(&[blend(0.0), blend(50.0)], &[expanded(0.0), expanded(50.0)], true).is_some());
|
||||
// Coordinates far out don't overflow the grid.
|
||||
let far = [square(1e300), square(-1e300)];
|
||||
let _ = how_far(&far, &[c(1e300), c(-1e300)]);
|
||||
let _ = check(&far, &[square(1e300), square(-1e300)], false);
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine running right to left, with their steps drawn pointing
|
||||
/// right: Align to Path would turn each one (keys included) a half turn, which leaves their
|
||||
/// centers and sizes as they are but not their points. A record naming Align to Path doesn't
|
||||
/// make the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_turned_as_drawn() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 100.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| triangle(20 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Triangles pointing right on a spine 1 pt long running right to left, with 998 steps drawn
|
||||
/// unturned, so that every step sits within the tolerance of each one. Align to Path would turn
|
||||
/// each one to point left. A record naming Align to Path doesn't make the blend Align to Path,
|
||||
/// however many steps one step's place matches; a record naming Align to Page keeps it.
|
||||
#[test]
|
||||
fn the_records_orientation_is_checked_on_crowded_steps() {
|
||||
let triangle = |id: u64, x: f64| {
|
||||
let points = [Point::new(x, 0.0), Point::new(x, 10.0), Point::new(x + 20.0, 5.0)];
|
||||
Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, true)), Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(11.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![triangle(1, 1.0), triangle(2, 0.0), spine], clip: false });
|
||||
let steps = (0..1000u32).map(|i| triangle(20 + u64::from(i), 1.0 - f64::from(i) / 999.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = MAX_BLEND_OBJECTS;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups of a red square on the left and a blue one on the right, on a spine running right to
|
||||
/// left, with their steps drawn unturned: Align to Path would give each a half turn, which keeps
|
||||
/// the group's outline but trades the squares' places. A record naming Align to Path doesn't make
|
||||
/// the blend Align to Path.
|
||||
#[test]
|
||||
fn the_records_orientation_must_keep_each_member_where_it_is_drawn() {
|
||||
let square = |id: u64, x: f64, color: Color| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, vectorcraft_doc::Appearance::basic(Paint::solid(color), Paint::None, 0.0)))
|
||||
};
|
||||
let pair = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(1.0, 0.0, 0.0)), square(id * 10 + 1, x + 10.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(110.0, 5.0), Point::new(10.0, 5.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(4), NodeKind::Group { children: vec![pair(1, 100.0), pair(2, 0.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| pair(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
// Drawn turned, blue on the left: the blend is Align to Path, whichever orientation the
|
||||
// record names.
|
||||
let turned = |id: u64, x: f64| {
|
||||
let children = vec![square(id * 10, x, Color::rgb(0.0, 0.0, 1.0)), square(id * 10 + 1, x + 10.0, Color::rgb(1.0, 0.0, 0.0))];
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::Group { children, clip: false }))
|
||||
};
|
||||
let steps = (0..5u32).map(|i| turned(30 + u64::from(i), 100.0 - f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(5), NodeKind::Group { children: steps, clip: false });
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 100;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPath, "{named:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Rectangles 20 pt wide and 10 pt high on a vertical spine, with their steps drawn upright: Align
|
||||
/// to Path would turn each one (keys included) a quarter turn, which leaves the centers in place
|
||||
/// but not the sizes. A record naming Align to Path doesn't make the blend Align to Path; a
|
||||
/// record naming Align to Page does.
|
||||
#[test]
|
||||
fn the_records_orientation_must_lay_the_steps_out_at_their_drawn_sizes() {
|
||||
let rect = |id: u64, y: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, y, 20.0, y + 10.0));
|
||||
Arc::new(Node::path(NodeId(id), path, Default::default()))
|
||||
};
|
||||
let spine = vectorcraft_geom::shapes::line(Point::new(10.0, 5.0), Point::new(10.0, 105.0));
|
||||
let spine = Arc::new(Node::path(NodeId(3), spine, Default::default()));
|
||||
let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![rect(1, 0.0), rect(2, 100.0), spine], clip: false });
|
||||
let steps = (0..5u32).map(|i| rect(20 + u64::from(i), f64::from(i) * 25.0)).collect();
|
||||
let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false });
|
||||
let roles = Roles::from([
|
||||
(NodeId(1), ("K".to_string(), Some("A".to_string()))),
|
||||
(NodeId(2), ("K".to_string(), Some("B".to_string()))),
|
||||
(NodeId(3), ("S".to_string(), None)),
|
||||
]);
|
||||
for named in [BlendOrientation::AlignToPath, BlendOrientation::AlignToPage] {
|
||||
let record = Record { ids: vec!["A".into(), "B".into()], spacing: None, orientation: Some(named) };
|
||||
let mut budget = 10;
|
||||
let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &record, &roles, &mut budget) else { panic!("a live blend") };
|
||||
assert_eq!(spec.orientation, BlendOrientation::AlignToPage, "{named:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@
|
||||
//! at None so the art keeps its own colors.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::Affine;
|
||||
use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation};
|
||||
@@ -474,6 +475,30 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result<
|
||||
Ok(BrushDraft { name: name.to_string(), kind })
|
||||
}
|
||||
|
||||
/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with
|
||||
/// their objects too: the art changes the space it is in, and no object moves over its mask.
|
||||
pub(crate) fn turn_over(art: &mut Node) {
|
||||
art.transform(Affine::scale_non_uniform(1.0, -1.0), false);
|
||||
turn_unlinked_masks(art);
|
||||
}
|
||||
|
||||
/// Turn over the art of the opacity masks in `n` that a transform of `n` leaves in place (the masks
|
||||
/// that don't move with their objects), in members and in other masks' art too.
|
||||
fn turn_unlinked_masks(n: &mut Node) {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
let linked = m.linked;
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
if linked {
|
||||
turn_unlinked_masks(art);
|
||||
} else {
|
||||
turn_over(art);
|
||||
}
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
turn_unlinked_masks(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
|
||||
/// The brushes of `drafts`, their art from the sections `art` (by name), in the brush manager's
|
||||
/// `order` (brushes it doesn't list after those it does, in the order of their objects), each
|
||||
/// kept within its ranges → the brushes and how many were left out: those whose art isn't read,
|
||||
@@ -553,7 +578,7 @@ pub(super) fn finish_brushes_within(
|
||||
DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| {
|
||||
// The side of the section with y up draws on the right of the path, and a brush
|
||||
// draws art's y (down here) on the left of the path.
|
||||
a.transform(Affine::scale_non_uniform(1.0, -1.0), false);
|
||||
turn_over(&mut a);
|
||||
if let ArtScale::BetweenGuides { start, end } = &mut brush.scale {
|
||||
// Guides that leave no art between them stretch the whole art.
|
||||
let length = a.geometric_bounds().map_or(0.0, |b| b.width());
|
||||
|
||||
@@ -21,9 +21,17 @@ const MAX_OBJECTS: usize = 100_000;
|
||||
const MAX_OBJECT: usize = 256 << 10;
|
||||
const OBJECT: &[u8] = b"/AI11Text :";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`text_frames`] has scanned an editing copy on this thread.
|
||||
pub(crate) static TEXT_FRAME_SCANS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The `/Art` path of each text object of `data` (an editing copy's document text), in art space
|
||||
/// (y up), by its story and frame. Objects without a readable path are left out.
|
||||
pub(crate) fn text_frames(data: &[u8]) -> HashMap<(u32, usize), BezPath> {
|
||||
#[cfg(test)]
|
||||
TEXT_FRAME_SCANS.set(TEXT_FRAME_SCANS.get() + 1);
|
||||
let mut out = HashMap::new();
|
||||
let mut at = 0;
|
||||
while let Some(i) = data.get(at..).and_then(|d| find(d, OBJECT)) {
|
||||
|
||||
@@ -25,7 +25,7 @@ const MAX_PATCHES: usize = 16_384;
|
||||
const MAX_POINTS: usize = MAX_PATCHES * 16;
|
||||
|
||||
/// The largest grid `/Size` read as one mesh, a side.
|
||||
const MAX_SIDE: usize = 128;
|
||||
pub(crate) const MAX_SIDE: usize = 128;
|
||||
/// The most inks of an `/NChannel` colour space read.
|
||||
const MAX_INKS: usize = 32;
|
||||
/// The most rows or columns a mesh stitched from its patches may have once the lines through the
|
||||
@@ -556,6 +556,14 @@ impl Path {
|
||||
|
||||
/// `a` towards `b` by `t`, in their own colour model where they share one.
|
||||
fn mix(a: &Color, b: &Color, t: f32) -> Color {
|
||||
// At either end, that end's own color in its own model: a mesh point of a patch whose corners
|
||||
// differ in model keeps its color.
|
||||
if t <= 0.0 {
|
||||
return *a;
|
||||
}
|
||||
if t >= 1.0 {
|
||||
return *b;
|
||||
}
|
||||
let l = |x: f32, y: f32| x + (y - x) * t;
|
||||
match (a, b) {
|
||||
(Color::Rgb { r, g, b: bl }, Color::Rgb { r: r2, g: g2, b: b2 }) => Color::rgb(l(*r, *r2), l(*g, *g2), l(*bl, *b2)),
|
||||
@@ -565,6 +573,51 @@ fn mix(a: &Color, b: &Color, t: f32) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most values one entry of [`mesh_reads`]' record holds (a corner of [`MAX_INKS`] inks has
|
||||
/// 41).
|
||||
const MAX_ENTRY: usize = 64;
|
||||
|
||||
/// The gradient mesh the reader reads from `record`, a mesh's lines (`/Mesh X!` … `/End X!`,
|
||||
/// entries on `%_` lines or not), with `to_doc` taking art space to the document: one mesh, or
|
||||
/// `None` where the reader would read none or a group of its patches.
|
||||
pub(crate) fn mesh_reads(record: &[u8], to_doc: Affine) -> Option<GradientMesh> {
|
||||
use super::lex::{Lexer, Tok};
|
||||
let mut lex = Lexer::new(record);
|
||||
let mut m: Option<MeshReader> = None;
|
||||
let mut stack: Vec<V> = vec![];
|
||||
let mut marks: Vec<usize> = vec![];
|
||||
while let Some(t) = lex.next_token() {
|
||||
match t.tok {
|
||||
Tok::Num(v) => stack.push(V::Num(v)),
|
||||
Tok::Name(n) => stack.push(V::Name(super::obj::text(n))),
|
||||
Tok::Str(s) | Tok::Hex(s) => stack.push(V::Str(s)),
|
||||
Tok::Word(b"[") => marks.push(stack.len()),
|
||||
Tok::Word(b"]") => {
|
||||
let at = marks.pop()?;
|
||||
let items = stack.split_off(at.min(stack.len()));
|
||||
stack.push(V::Arr(items));
|
||||
}
|
||||
Tok::Word(b"X!") => match (stack.last().and_then(V::text).as_deref(), m.take()) {
|
||||
(Some("Mesh"), None) => m = Some(MeshReader::default()),
|
||||
(Some("End"), Some(read)) => {
|
||||
if read.unread || read.patches.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return read.one_mesh().ok();
|
||||
}
|
||||
_ => return None,
|
||||
},
|
||||
Tok::Word(b"X#") => m.as_mut()?.entry(&std::mem::take(&mut stack), to_doc),
|
||||
Tok::Comment(_) => {}
|
||||
_ => return None,
|
||||
}
|
||||
if stack.len() > MAX_ENTRY {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -885,6 +938,51 @@ mod tests {
|
||||
assert!(!reader.unread && reader.patches[0].points[0].color == Color::gray(1.0));
|
||||
}
|
||||
|
||||
/// `/Version` and `/Data` entries, before or after the patches, are passed over: corners with
|
||||
/// and without an opacity are read by their count of values either way.
|
||||
#[test]
|
||||
fn version_and_data_entries_are_passed_over() {
|
||||
for (with_opacity, data_first) in [(true, true), (false, true), (true, false), (false, false)] {
|
||||
let mut reader = MeshReader::default();
|
||||
for (value, key) in [(V::Name("Cartesian".into()), "Type"), (nums(&[1.0, 1.0]), "Size")] {
|
||||
reader.entry(&[value, V::Name(key.into())], Affine::IDENTITY);
|
||||
}
|
||||
if data_first {
|
||||
reader.entry(&[V::Num(2.0), V::Name("Version".into())], Affine::IDENTITY);
|
||||
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
|
||||
}
|
||||
reader.entry(&[nums(&[0.0, 0.0]), V::Name("P".into())], Affine::IDENTITY);
|
||||
let colors: [&[f64]; 4] =
|
||||
if with_opacity { [&[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25]] } else { [&[0.5], &[0.5], &[0.5], &[0.5]] };
|
||||
square(&mut reader, colors, Default::default());
|
||||
if !data_first {
|
||||
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
|
||||
reader.entry(&[V::Num(1.0), V::Name("Version".into())], Affine::IDENTITY);
|
||||
}
|
||||
assert!(!reader.unread, "{with_opacity} {data_first}");
|
||||
let mesh = reader.one_mesh().unwrap();
|
||||
let want = if with_opacity { 0.25 } else { 1.0 };
|
||||
assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A patch whose corners differ in color space keeps each corner's color in its own model when
|
||||
/// the patches are stitched into one mesh.
|
||||
#[test]
|
||||
fn stitched_corners_keep_their_own_color_models() {
|
||||
let cs = |n: &str| (V::Name(n.into()), "CS");
|
||||
let mut reader = MeshReader::default();
|
||||
let first = vec![(nums(&[1.0, 1.0]), "Size"), (nums(&[0.0, 0.0]), "P"), cs("DeviceRGB")];
|
||||
square(
|
||||
&mut reader,
|
||||
[&[1.0, 0.0, 0.0], &[0.25], &[0.0, 1.0, 0.0, 0.0], &[0.0, 0.0, 1.0]],
|
||||
[first, vec![cs("DeviceGray")], vec![cs("DeviceCMYK")], vec![cs("DeviceRGB")]],
|
||||
);
|
||||
let mesh = reader.one_mesh().unwrap();
|
||||
let colors: Vec<Color> = mesh.points.iter().map(|p| p.color).collect();
|
||||
assert_eq!(colors, [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::gray(0.75), Color::cmyk(0.0, 1.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// A named colour (`[c m y k /DeviceCMYK (name) /Process]`) paints at each corner's tint, 1 its
|
||||
/// full colour; `/NChannel` inks overprint at their tints. Ones that don't add up stay unread.
|
||||
#[test]
|
||||
|
||||
@@ -97,7 +97,9 @@
|
||||
//! have is the object's own appearance, not a link.
|
||||
//!
|
||||
//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the
|
||||
//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
|
||||
//! symbol's space, y down; an image's matrix and a gradient mesh's corners in the canvas's space
|
||||
//! turned y up about art space's origin there, an envelope's contents in its dictionary in the
|
||||
//! canvas's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
|
||||
//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of
|
||||
//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names
|
||||
//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx
|
||||
@@ -156,9 +158,10 @@ use graph::Graph;
|
||||
pub(crate) use ops::{read_art_style, read_style_list, style_moves_with};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::with_image_limits;
|
||||
pub(crate) use types::BLEND_BUDGET;
|
||||
pub(crate) use types::MAX_NODES;
|
||||
pub use types::PlacedPage;
|
||||
use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
#[cfg(test)]
|
||||
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
|
||||
pub(super) use types::{blend_mode, blend_name};
|
||||
|
||||
@@ -277,6 +277,18 @@ impl<'a> Reader<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A gradient mesh's `X#` entry `vals`. In a symbol's art, corners are in the space an image's
|
||||
/// matrix is in there; a mesh there in a file that doesn't say where the canvas is is unread.
|
||||
pub(super) fn mesh_entry(&mut self, vals: &[V]) {
|
||||
let to_doc = self.image_space();
|
||||
if let Some((m, _)) = self.mesh.as_mut() {
|
||||
match to_doc {
|
||||
Some(to_doc) => m.entry(vals, to_doc),
|
||||
None => m.unread = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `/End X!`: the gradient mesh read, as one object.
|
||||
pub(super) fn end_mesh(&mut self) -> Result<(), String> {
|
||||
let Some((m, hidden)) = self.mesh.take() else { return Ok(()) };
|
||||
@@ -351,11 +363,15 @@ impl<'a> Reader<'a> {
|
||||
pub(super) fn set_instance(&mut self, i: &Instance) {
|
||||
let mut to_doc = self.space();
|
||||
// In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's
|
||||
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are.
|
||||
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are, an envelope's
|
||||
// contents' included (which `space` moves alone).
|
||||
if (self.pattern.is_some() || self.symbol.is_some())
|
||||
&& i.has_matrix()
|
||||
&& let Some(t) = self.template
|
||||
{
|
||||
if self.pattern.is_none() && !self.envelope_blocks.is_empty() {
|
||||
to_doc = Affine::IDENTITY;
|
||||
}
|
||||
let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0);
|
||||
to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]);
|
||||
}
|
||||
|
||||
@@ -923,12 +923,17 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// Art space → where the art being read goes: the document, or while a pattern's definition is
|
||||
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space.
|
||||
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space,
|
||||
/// except an envelope's contents in its dictionary (its `AIDeformArtKey` block), which are in the
|
||||
/// canvas's space, y down (in the symbol's space in a file without a template box).
|
||||
pub(crate) fn space(&mut self) -> Affine {
|
||||
if self.pattern.is_some() {
|
||||
FLIP
|
||||
} else if self.symbol.is_some() {
|
||||
Affine::IDENTITY
|
||||
match self.canvas_origin() {
|
||||
Some(o) if !self.envelope_blocks.is_empty() => Affine::translate(-o.to_vec2()),
|
||||
_ => Affine::IDENTITY,
|
||||
}
|
||||
} else {
|
||||
self.ensure_space()
|
||||
}
|
||||
|
||||
@@ -226,10 +226,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
("X!", Some("End")) if self.mesh.is_some() => return self.end_mesh(),
|
||||
("X#", _) => {
|
||||
let to_doc = self.space();
|
||||
if let Some((m, _)) = self.mesh.as_mut() {
|
||||
m.entry(&vals, to_doc);
|
||||
}
|
||||
self.mesh_entry(&vals);
|
||||
return Ok(());
|
||||
}
|
||||
_ if self.mesh.is_some() => return Ok(()),
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(crate) const MAX_NODES: usize = 4_000_000;
|
||||
|
||||
/// The most objects all the blends of one import may lay out to be checked (each twice) and made
|
||||
/// live; past it, blends keep their drawn steps.
|
||||
pub(super) const BLEND_BUDGET: usize = 50_000;
|
||||
pub(crate) const BLEND_BUDGET: usize = 50_000;
|
||||
|
||||
/// Most points in one path.
|
||||
pub(super) const MAX_POINTS: usize = 4_000_000;
|
||||
|
||||
@@ -5251,6 +5251,62 @@ fn an_image_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
assert_eq!(r.unread.len(), 1, "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
// The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). A
|
||||
// mesh's corners in a symbol's art are in the canvas's space turned y up about that point, as an
|
||||
// image's matrix there is: (-8096, 8244.5) is (-5, -2.5) in the symbol's art.
|
||||
let corners: String = [(-8096.0, 8244.5), (-8096.0, 8239.5), (-8086.0, 8239.5), (-8086.0, 8244.5)]
|
||||
.iter()
|
||||
.map(|(x, y)| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n"))
|
||||
.collect();
|
||||
let mesh = format!(
|
||||
"/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[1 1] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n"
|
||||
);
|
||||
let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Patch", &mesh, 5)), layer(""))).doc;
|
||||
assert_eq!(doc.symbols.len(), 1);
|
||||
let mut found = vec![];
|
||||
let mut stack = vec![doc.symbols[0].art.clone()];
|
||||
while let Some(n) = stack.pop() {
|
||||
match &n.kind {
|
||||
NodeKind::Mesh(m) => found.push(m.points.iter().map(|p| p.p).collect::<Vec<_>>()),
|
||||
_ => stack.extend(n.children().into_iter().flatten().cloned()),
|
||||
}
|
||||
}
|
||||
assert_eq!(found.len(), 1, "{:?}", doc.symbols[0].art);
|
||||
let want = [Point::new(-5.0, -2.5), Point::new(5.0, -2.5), Point::new(-5.0, 2.5), Point::new(5.0, 2.5)];
|
||||
assert!(want.iter().all(|w| found[0].iter().any(|p| (*p - *w).hypot() < 1e-9)), "{:?}", found[0]);
|
||||
// Without a template box the mesh can't be placed, as an image there can't: the symbol isn't read
|
||||
// whole and its instance comes in as the page draws it.
|
||||
let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Patch", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0));
|
||||
let r = read_ok(&(symbols(&symbol("Patch", &mesh, 5)) + &layer(&group)));
|
||||
assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
|
||||
assert!(!r.unread.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_envelope_in_a_symbols_art_is_read_from_the_canvas() {
|
||||
// An envelope's grid in a symbol's art is read in the space a gradient mesh's corners are read
|
||||
// in there. A grid and contents written in the symbol's own space, as earlier VectorCraft builds
|
||||
// wrote them, don't meet there: the envelope opens as the art it draws.
|
||||
let drawn = format!("{RED}{}f\n", rect_path(30.0, 10.0, 170.0, 90.0));
|
||||
let env = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn);
|
||||
let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Bent", &env, 5)), layer(""))).doc;
|
||||
assert_eq!(doc.symbols.len(), 1);
|
||||
let mut envelopes = 0;
|
||||
doc.symbols[0].art.walk(&mut |n| envelopes += usize::from(matches!(n.kind, NodeKind::Envelope { .. })));
|
||||
assert_eq!(envelopes, 0, "{:?}", doc.symbols[0].art);
|
||||
let mut paths = 0;
|
||||
doc.symbols[0].art.walk(&mut |n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert!(paths > 0, "{:?}", doc.symbols[0].art);
|
||||
// Without a template box the grid can't be placed, as a gradient mesh there can't: the symbol
|
||||
// isn't read whole and its instance comes in as the page draws it.
|
||||
let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Bent", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0));
|
||||
let r = read_ok(&(symbols(&symbol("Bent", &env, 5)) + &layer(&group)));
|
||||
assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
|
||||
assert!(!r.unread.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_keeps_its_hide_lock_transparency_and_clip() {
|
||||
let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0];
|
||||
@@ -6462,6 +6518,30 @@ fn a_brushs_opacity_mask_art_takes_ids_of_the_document() {
|
||||
assert_eq!(unique.len(), all.len(), "{all:?}");
|
||||
}
|
||||
|
||||
/// An Art brush's art is turned over with the art of its opacity mask, whether the mask moves with
|
||||
/// its object or not: the mask's art stays over the part of the object it is over in the section.
|
||||
#[test]
|
||||
fn an_art_brushs_opacity_mask_art_turns_over_with_its_object() {
|
||||
let mut read = vec![];
|
||||
for linked in [true, false] {
|
||||
let mask_art: String = format!("1 g\n{}f\n", rect_path(0.0, 0.0, 40.0, 3.0)).lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let options = format!("%_1 /Bool (Clipping) ,\n%_{} /Bool (Linked) ,\n", u8::from(linked));
|
||||
let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n{mask_art}%_X+\n%_(Art) ,\n{options}%_; (AI9_Mask) ,\n%_;\n");
|
||||
let section = format!("%AI8_BeginBrushPattern\n(Ribbon art)\n0 A\n0 g\n{}f\n{mask}%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, 40.0, 8.0));
|
||||
let shape = format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0));
|
||||
let r = read_ok(&format!("{section}{}{}", plugin_object(ART_BRUSH, "Ribbon", RIBBON), layer(&shape)));
|
||||
let lib = vectorcraft_brush::library(&r.doc);
|
||||
let vectorcraft_brush::BrushKind::Art(brush) = brush_named(&lib, "Ribbon") else { panic!("art: {:?}", r.warnings) };
|
||||
let m = brush.art.extras().mask.as_deref().unwrap_or_else(|| panic!("the mask is read: {:#?}", brush.art));
|
||||
assert_eq!(m.linked, linked);
|
||||
let (object, over) = (brush.art.geometric_bounds().unwrap(), m.art.geometric_bounds().unwrap());
|
||||
assert!((object.height() - 8.0).abs() < 1e-6 && (over.height() - 3.0).abs() < 1e-6, "linked {linked}: {over:?} over {object:?}");
|
||||
assert!(over.y0 > object.y0 - 1e-6 && over.y1 < object.y1 + 1e-6, "linked {linked}: {over:?} over {object:?}");
|
||||
read.push((object, over));
|
||||
}
|
||||
assert_eq!(read[0], read[1], "a mask is in the same place whether it moves with its object or not");
|
||||
}
|
||||
|
||||
/// An art styles section inside a symbol's, a pattern's or a brush's art is skipped: the file's own
|
||||
/// art styles still style the layers' objects read after the definition.
|
||||
#[test]
|
||||
@@ -9354,8 +9434,10 @@ fn a_blend_comes_in_as_a_live_blend() {
|
||||
}
|
||||
|
||||
/// A blend whose spine was never edited has no spine written, only its keys: its spine is the
|
||||
/// straight line between the keys' centres, in the record's order (here the left key, named `B`,
|
||||
/// first), and the blend comes in live.
|
||||
/// straight line between the keys' centers, in the record's order, and the blend comes in live.
|
||||
/// With the record naming the keys in their order (here the left key, named `B`, first) the blend
|
||||
/// has no spine of its own, which runs the same way; in the other order its spine is that line,
|
||||
/// from the right key to the left one.
|
||||
#[test]
|
||||
fn a_blend_with_no_spine_written_runs_straight_between_its_keys() {
|
||||
let spine_part = format!("%_N\n{}", blend_part("S", None));
|
||||
@@ -9365,12 +9447,20 @@ fn a_blend_with_no_spine_written_runs_straight_between_its_keys() {
|
||||
let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) };
|
||||
assert!(!warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}");
|
||||
assert_eq!(spec.spacing, vectorcraft_doc::live::BlendSpacing::Steps(3));
|
||||
let spine = spec.spine.as_ref().and_then(|p| p.subpaths.first()).expect("a spine");
|
||||
let points: Vec<(f64, f64)> = spine.anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
|
||||
assert_eq!((&spec.spine, &spec.key_anchors), (&None, &vec![]), "a blend with no spine of its own");
|
||||
let (spine, _) = vectorcraft_doc::blend::blend_spine(children, spec).expect("a spine");
|
||||
let points: Vec<(f64, f64)> = spine.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
|
||||
assert_eq!(points.len(), 2, "{points:?}");
|
||||
assert!((points[0].0 - 10.0).abs() < 0.01 && (points[1].0 - 110.0).abs() < 0.01, "from the left key to the right one: {points:?}");
|
||||
assert_eq!(spec.key_anchors, vec![0, 1]);
|
||||
assert_eq!(vectorcraft_doc::blend::blend_expand(children, spec).len(), 5);
|
||||
|
||||
let body = blend_file("", [Some("B"), Some("A")], &blend_record(&['A', 'B']));
|
||||
let (blend, warnings) = read_blend(&body.replace(&spine_part, ""));
|
||||
let NodeKind::Blend { spec, .. } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) };
|
||||
let spine = spec.spine.as_ref().and_then(|p| p.subpaths.first()).expect("a spine");
|
||||
let points: Vec<(f64, f64)> = spine.anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
|
||||
assert!((points[0].0 - 110.0).abs() < 0.01 && (points[1].0 - 10.0).abs() < 0.01, "from the right key to the left one: {points:?}");
|
||||
assert_eq!(spec.key_anchors, vec![1, 0]);
|
||||
}
|
||||
|
||||
/// The tags after a blend's drawn steps are the live blend's.
|
||||
|
||||
@@ -576,6 +576,12 @@ impl DocFont {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`Texts::read`] has read a text document on this thread.
|
||||
pub(super) static TEXTS_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The text document of an editing copy.
|
||||
pub(super) struct Texts {
|
||||
stories: Vec<Val>,
|
||||
@@ -615,6 +621,8 @@ impl Texts {
|
||||
fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> {
|
||||
h.get(from..)?.windows(n.len()).position(|w| w == n).map(|p| p + from)
|
||||
}
|
||||
#[cfg(test)]
|
||||
TEXTS_READS.set(TEXTS_READS.get() + 1);
|
||||
let start = find(data, b"%AI11_BeginTextDocument", 0)?;
|
||||
let from = find(data, b"/ASCII85Decode", start)? + b"/ASCII85Decode".len();
|
||||
let end = find(data, b"~>", from)? + 2;
|
||||
|
||||
@@ -47,6 +47,8 @@ mod layers;
|
||||
mod plan;
|
||||
mod slots;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use build::READ_AFRESH;
|
||||
#[cfg(test)]
|
||||
use build::{Frame, MADE, prune_unseen};
|
||||
pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
|
||||
@@ -116,13 +116,20 @@ pub(super) type Built = Result<(Document, Vec<String>), String>;
|
||||
/// look draws), no object is unread or has another placement or drawn art that the page would
|
||||
/// choose, no linked image shows a placeholder, and its artboards are the pages, one for one and of their size, in points or in the pages'
|
||||
/// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for
|
||||
/// [`build_from`] with the page.
|
||||
pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result<Built, Box<Structure>> {
|
||||
let Some(scale) = alone_scale(&structure, data, pages, unit) else {
|
||||
/// [`build_from`] with the page. `text` keeps what was read of the text of `data` for the check and
|
||||
/// the build, and for any later build of `data`.
|
||||
pub(super) fn build_without_page(
|
||||
structure: Structure,
|
||||
data: &[u8],
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
text: &mut ReadText,
|
||||
) -> Result<Built, Box<Structure>> {
|
||||
let Some(scale) = alone_scale(&structure, data, pages, unit, text) else {
|
||||
return Err(Box::new(structure));
|
||||
};
|
||||
let (styles, own_size) = (structure.styles_read, structure.symbols_own_size);
|
||||
let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| {
|
||||
let built = build_weighing(structure, data, None, Page::Artboard, false, false, 1.0, &mut None, text).map(|(mut doc, notes)| {
|
||||
if scale != 1.0 {
|
||||
// The graphic styles read from the file are drawn in its units too.
|
||||
scale_read_document(&mut doc, scale, styles, own_size);
|
||||
@@ -133,9 +140,56 @@ pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f6
|
||||
}
|
||||
|
||||
/// The scale [`build_without_page`] draws `structure` (the editing copy `data` read) at on `pages`
|
||||
/// in units of `unit` points, when it builds it without the page.
|
||||
pub(super) fn alone_scale(structure: &Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Option<f64> {
|
||||
page_scale_alone(structure, pages, unit).filter(|_| nothing_waits_on_page(structure) && type_all_made(structure, data))
|
||||
/// in units of `unit` points, when it builds it without the page. `text` keeps what was read of the
|
||||
/// text of `data`.
|
||||
pub(super) fn alone_scale(structure: &Structure, data: &[u8], pages: &[(f64, f64)], unit: f64, text: &mut ReadText) -> Option<f64> {
|
||||
page_scale_alone(structure, pages, unit).filter(|_| nothing_waits_on_page(structure) && type_all_made(structure, data, text))
|
||||
}
|
||||
|
||||
/// The text objects' frames and the text document of an editing copy, each read the first time it
|
||||
/// is asked for and kept for every later check and build of the same copy.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ReadText {
|
||||
/// [`ai::text_frames`] of the copy, once scanned.
|
||||
frames: Option<std::collections::HashMap<(u32, usize), kurbo::BezPath>>,
|
||||
/// [`Texts::read`] of the copy, once read: `Some(None)` when it has no text document that can
|
||||
/// be read.
|
||||
texts: Option<Option<Texts>>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// While set, [`ReadText`] keeps nothing on this thread: each check and build reads the text afresh.
|
||||
pub(crate) static READ_AFRESH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
impl ReadText {
|
||||
/// Forgets what was read while [`READ_AFRESH`] is set (only in tests).
|
||||
fn forget_in_tests(&mut self) {
|
||||
#[cfg(test)]
|
||||
if READ_AFRESH.get() {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/Art` path of each text object of `data` ([`ai::text_frames`]).
|
||||
fn frames(&mut self, data: &[u8]) -> &std::collections::HashMap<(u32, usize), kurbo::BezPath> {
|
||||
self.forget_in_tests();
|
||||
self.frames.get_or_insert_with(|| ai::text_frames(data))
|
||||
}
|
||||
|
||||
/// The text document of `data` ([`Texts::read`]), if it has one that can be read.
|
||||
fn texts(&mut self, data: &[u8]) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
|
||||
}
|
||||
|
||||
/// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]).
|
||||
fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns));
|
||||
self.texts.insert(texts).as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its
|
||||
@@ -152,17 +206,18 @@ fn nothing_waits_on_page(structure: &Structure) -> bool {
|
||||
|
||||
/// Does the text document of `data` (read as `structure`) make the type of every text object, those
|
||||
/// that don't show included, with at least one that shows, and none of them type that a look draws?
|
||||
fn type_all_made(structure: &Structure, data: &[u8]) -> bool {
|
||||
/// The frames and the text document are read into `text` when it doesn't have them yet.
|
||||
fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> bool {
|
||||
let mut infos = vec![];
|
||||
collect_slots(&structure.doc.layers, true, &mut infos);
|
||||
if !infos.iter().any(|i| i.shown) || infos.iter().any(|i| i.look.is_some()) {
|
||||
return false;
|
||||
}
|
||||
let frames = ai::text_frames(data);
|
||||
let frames = text.frames(data);
|
||||
for info in &mut infos {
|
||||
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone())));
|
||||
}
|
||||
let Some(texts) = Texts::read(data) else { return false };
|
||||
let Some(texts) = text.texts(data) else { return false };
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
.iter()
|
||||
@@ -244,13 +299,14 @@ pub(super) fn build_from(
|
||||
trust: bool,
|
||||
unit: f64,
|
||||
) -> Result<(Document, Vec<String>), String> {
|
||||
build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None)
|
||||
build_weighing(structure, data, visible, page, outlined, trust, unit, &mut None, &mut ReadText::default())
|
||||
}
|
||||
|
||||
/// [`build_from`]. When the layers with their live envelopes don't draw as the page, and don't with
|
||||
/// the drawn art of every live envelope put back either, `free` is set to the envelopes of type
|
||||
/// (by their place among them, as read) that opened live and that the page doesn't hold against
|
||||
/// them ([`held_back`]), whether or not the layers are then used, and however.
|
||||
/// them ([`held_back`]), whether or not the layers are then used, and however. The text of `data`
|
||||
/// is taken from `text`, and read into it when it doesn't have it yet.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn build_weighing(
|
||||
structure: Structure,
|
||||
@@ -261,6 +317,7 @@ pub(super) fn build_weighing(
|
||||
trust: bool,
|
||||
unit: f64,
|
||||
free: &mut Option<Vec<usize>>,
|
||||
text: &mut ReadText,
|
||||
) -> Result<(Document, Vec<String>), String> {
|
||||
let Structure {
|
||||
mut doc,
|
||||
@@ -425,7 +482,7 @@ pub(super) fn build_weighing(
|
||||
collect_slots(&doc.layers, true, &mut infos);
|
||||
super::slots::limit_look_slots(&mut doc.layers, &mut infos, shown.len(), outlined);
|
||||
// Each text object's own frame or path, by its story and frame.
|
||||
let frames = ai::text_frames(data);
|
||||
let frames = text.frames(data);
|
||||
for info in &mut infos {
|
||||
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(to_doc * p.clone())));
|
||||
}
|
||||
@@ -439,14 +496,14 @@ pub(super) fn build_weighing(
|
||||
// The page's type that needs no text object of the layers: the layers' own legacy text, or
|
||||
// placed files that show it.
|
||||
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
|
||||
let texts = Texts::read(data).map(|t| t.with_patterns(text_patterns));
|
||||
let texts = text.texts_with(data, text_patterns);
|
||||
// Each story is read once, however many text objects name it.
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let n = i.story?;
|
||||
read.entry(n).or_insert_with(|| texts.as_ref().and_then(|t| t.story(n as usize)).map(Arc::new)).clone()
|
||||
read.entry(n).or_insert_with(|| texts.and_then(|t| t.story(n as usize)).map(Arc::new)).clone()
|
||||
})
|
||||
.collect();
|
||||
if stories.iter().flatten().map(|s| s.len()).sum::<usize>() > MAX_TEXT {
|
||||
@@ -3311,4 +3368,72 @@ mod candidate_tests {
|
||||
assert!(typed && kept.node(drawn[0].0).is_none() && kept.node(drawn[1].0).is_some());
|
||||
assert!(!notes.iter().any(|n| n.starts_with(DREW_DIFFERENTLY)), "{notes:?}");
|
||||
}
|
||||
|
||||
/// The editing copy of a 100 × 100 file whose one layer holds a square and `stories` objects of
|
||||
/// point type, each its own story, with the text document that makes them.
|
||||
fn many_stories(stories: u32) -> Vec<u8> {
|
||||
use crate::import::tests_native::{Story, layer, native_with_text, square, text_object, unsplit_text_document};
|
||||
let texts: Vec<String> = (0..stories).map(|i| format!("Story {i}\r")).collect();
|
||||
let anchor = |i: u32| (8170.0 + f64::from(i % 40), 8180.0 + f64::from(i / 40 % 40));
|
||||
let list: Vec<Story<'_>> = (0..stories).zip(&texts).map(|(i, t)| (t.as_str(), 0, anchor(i), (0.0, 0.0), 0.0)).collect();
|
||||
let objects: String = (0..stories).map(text_object).collect();
|
||||
native_with_text(&layer("Art", true, &format!("{}\n{objects}", square(10, 10))), &unsplit_text_document(&list)).into_bytes()
|
||||
}
|
||||
|
||||
/// The check and the build of layers that open without the page, each reading the text of the
|
||||
/// editing copy afresh, as [`build_without_page`] did before it read it once for both.
|
||||
fn alone_reading_twice(structure: Structure, data: &[u8], pages: &[(f64, f64)]) -> Option<Built> {
|
||||
let scale = alone_scale(&structure, data, pages, 1.0, &mut ReadText::default())?;
|
||||
assert_eq!(scale, 1.0);
|
||||
Some(build_from(structure, data, None, Page::Artboard, false, false, 1.0))
|
||||
}
|
||||
|
||||
/// Layers that open without the page, their text read once for the check and the build, come in
|
||||
/// as they do with the text read afresh for each.
|
||||
#[test]
|
||||
fn layers_alone_read_their_text_once_and_come_in_as_with_two_reads() {
|
||||
let data = many_stories(12);
|
||||
let read = || ai::read_over_page(&data, false, ai::NameEncoding::default()).unwrap();
|
||||
let pages = [(100.0, 100.0)];
|
||||
let Some(Ok(twice)) = alone_reading_twice(read(), &data, &pages) else { panic!("didn't open without the page") };
|
||||
let Ok(Ok(once)) = build_without_page(read(), &data, &pages, 1.0, &mut ReadText::default()) else { panic!("didn't open without the page") };
|
||||
assert_eq!(once, twice);
|
||||
let mut texts = vec![];
|
||||
once.0.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
texts.push(t.plain_text());
|
||||
}
|
||||
});
|
||||
assert_eq!(texts.len(), 12, "{:?}", once.1);
|
||||
assert!(texts.iter().enumerate().all(|(i, t)| *t == format!("Story {i}")), "{texts:?}");
|
||||
}
|
||||
|
||||
/// The check and the build of layers that open without the page, 2,000 objects of point type in
|
||||
/// them, timed with the text read afresh for each and read once for both, alternating, seven runs
|
||||
/// of each: `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture text_read_once_timing`.
|
||||
#[test]
|
||||
#[ignore = "a timing, run by hand"]
|
||||
fn text_read_once_timing() {
|
||||
let data = many_stories(2000);
|
||||
let read = || ai::read_over_page(&data, false, ai::NameEncoding::default()).unwrap();
|
||||
let pages = [(100.0, 100.0)];
|
||||
let (mut twice, mut once) = (vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
let structure = read();
|
||||
let start = std::time::Instant::now();
|
||||
let Some(Ok(a)) = alone_reading_twice(structure, &data, &pages) else { panic!("didn't open without the page") };
|
||||
twice.push(start.elapsed());
|
||||
let structure = read();
|
||||
let start = std::time::Instant::now();
|
||||
let Ok(Ok(b)) = build_without_page(structure, &data, &pages, 1.0, &mut ReadText::default()) else {
|
||||
panic!("didn't open without the page")
|
||||
};
|
||||
once.push(start.elapsed());
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
println!("read twice: {twice:?}\nread once: {once:?}");
|
||||
twice.sort();
|
||||
once.sort();
|
||||
println!("median: read twice {:?}, read once {:?}", twice[3], once[3]);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::build::{
|
||||
PAGE_MOVE, Page, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art, scale_symbol_art,
|
||||
PAGE_MOVE, Page, ReadText, alone_scale, build, build_from, build_on_page, build_weighing, build_without_page, reid_page_art, scale_symbol_art,
|
||||
};
|
||||
use super::slots::LAYERS_UNREAD;
|
||||
use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai};
|
||||
@@ -149,7 +149,7 @@ pub fn layered_ai_from(
|
||||
all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part"));
|
||||
all
|
||||
};
|
||||
let AiLayers { data, structure, alone } = layers;
|
||||
let AiLayers { data, structure, alone, mut text } = layers;
|
||||
let data = match data {
|
||||
Ok(data) => data,
|
||||
Err(why) => return (visible, unread(warnings, &why), false),
|
||||
@@ -194,7 +194,7 @@ pub fn layered_ai_from(
|
||||
let (mut free, mut count) = (None, 0);
|
||||
let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| {
|
||||
count = structure.warped_type.envelope_count();
|
||||
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free)
|
||||
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
|
||||
});
|
||||
// Layers that waited on the page only for their envelopes of type open alone, as they would
|
||||
// have without them, unless one opened live with the layers drawing as the page. Alone, each
|
||||
@@ -210,7 +210,7 @@ pub fn layered_ai_from(
|
||||
if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) {
|
||||
structure.warped_type.open_alone(free, count);
|
||||
}
|
||||
build_without_page(structure, &data, &pages, unit).ok()?.ok()
|
||||
build_without_page(structure, &data, &pages, unit, &mut text).ok()?.ok()
|
||||
})
|
||||
{
|
||||
done.setup.bleed = visible.setup.bleed;
|
||||
@@ -248,27 +248,28 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
|
||||
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
let data = match ai::decode_private(private) {
|
||||
Ok(data) => data,
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None }),
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
|
||||
};
|
||||
if !has_layers(&data) {
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None });
|
||||
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() });
|
||||
}
|
||||
// An image past the hard limits is read as an unread box, which the PDF part's art replaces.
|
||||
let structure = match ai::read_over_page(&data, false, names) {
|
||||
Ok(structure) => structure,
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None }),
|
||||
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }),
|
||||
};
|
||||
let mut text = Box::<ReadText>::default();
|
||||
// An envelope of type opens live only where the layers with it draw as the page, as the other
|
||||
// live envelopes do: the PDF part is imported to compare them with. Should none open live, the
|
||||
// layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]).
|
||||
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit).is_some() {
|
||||
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() {
|
||||
let alone = Some((pages.to_vec(), unit));
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone });
|
||||
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text });
|
||||
}
|
||||
match build_without_page(structure, &data, pages, unit) {
|
||||
match build_without_page(structure, &data, pages, unit, &mut text) {
|
||||
Ok(Ok((doc, notes))) => Ok((doc, notes)),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None }),
|
||||
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }),
|
||||
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,12 +284,14 @@ pub struct AiLayers {
|
||||
/// The pages and their unit the layers open on without the PDF part, when they wait on it only
|
||||
/// for their envelopes of type ([`ai_layers_alone`]).
|
||||
alone: Option<(Vec<(f64, f64)>, f64)>,
|
||||
/// The text objects' frames and the text document of the editing copy, as far as they were read.
|
||||
text: Box<ReadText>,
|
||||
}
|
||||
|
||||
impl AiLayers {
|
||||
/// The editing copy `private` (as [`layered_ai`] takes it), decoded.
|
||||
pub fn decode(private: &[u8]) -> Self {
|
||||
Self { data: ai::decode_private(private), structure: None, alone: None }
|
||||
Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,12 +44,12 @@ fn native_large_canvas(size: f64, scale: f64, layers: &str) -> String {
|
||||
}
|
||||
|
||||
/// A layer as the format writes it.
|
||||
fn layer(name: &str, visible: bool, body: &str) -> String {
|
||||
pub(super) fn layer(name: &str, visible: bool, body: &str) -> String {
|
||||
format!("%AI5_BeginLayer\n{} 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n({name}) Ln\n{body}\nLB\n%AI5_EndLayer--\n", u8::from(visible))
|
||||
}
|
||||
|
||||
/// A yellow square of 4 points at (`x`, `y`) in the format's operators.
|
||||
fn square(x: u32, y: u32) -> String {
|
||||
pub(super) fn square(x: u32, y: u32) -> String {
|
||||
format!("0 0 1 0 k\n{x} {y} m\n{} {y} L\n{} {} L\n{x} {} L\nf", x + 4, x + 4, y + 4, y + 4)
|
||||
}
|
||||
|
||||
@@ -3243,9 +3243,9 @@ fn custom_colours_open_paths_and_planar_group_marks_are_read() {
|
||||
/// A text document of `stories` (each as the text, its alignment code, its anchor and the frame's
|
||||
/// translation, and the start of its first line from the anchor), one font and a 14 point default.
|
||||
/// A story: its text, alignment code, anchor, frame translation and first line's start.
|
||||
type Story<'a> = (&'a str, u8, (f64, f64), (f64, f64), f64);
|
||||
pub(super) type Story<'a> = (&'a str, u8, (f64, f64), (f64, f64), f64);
|
||||
|
||||
fn text_document(stories: &[Story<'_>]) -> String {
|
||||
pub(super) fn text_document(stories: &[Story<'_>]) -> String {
|
||||
let story = |(text, align, anchor, _t, start): &Story<'_>| {
|
||||
let n = text.chars().count();
|
||||
format!(
|
||||
@@ -3290,7 +3290,7 @@ fn named_text_document(stories: &[Story<'_>]) -> String {
|
||||
|
||||
/// The editing copy of a 100 × 100 file with `layers` and the text `document`; its template box is
|
||||
/// centred at (50, 50).
|
||||
fn native_with_text(layers: &str, document: &str) -> String {
|
||||
pub(super) fn native_with_text(layers: &str, document: &str) -> String {
|
||||
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
format!(
|
||||
"%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI3_TemplateBox: 50 50 50 50\n\
|
||||
@@ -3299,8 +3299,18 @@ fn native_with_text(layers: &str, document: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// [`text_document`] of `stories`, padded so that [`native_with_text`] doesn't split the end of its
|
||||
/// data, `~>`, across two lines.
|
||||
pub(super) fn unsplit_text_document(stories: &[Story<'_>]) -> String {
|
||||
let mut doc = text_document(stories);
|
||||
while ascii85(doc.as_bytes()).len() % 60 == 1 {
|
||||
doc.push('\n');
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// A text object of story `story`, as the layers hold it.
|
||||
fn text_object(story: u32) -> String {
|
||||
pub(super) fn text_object(story: u32) -> String {
|
||||
format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n2 /TextAntialiasing ,\n;\n")
|
||||
}
|
||||
|
||||
@@ -6058,6 +6068,94 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
|
||||
assert_eq!(loose, [("Note".to_string(), true)], "{notes:?}");
|
||||
}
|
||||
|
||||
/// What `f` returns, with how many times it read a text document and scanned the text objects'
|
||||
/// frames of an editing copy on this thread; with `afresh`, each check and build reads them anew,
|
||||
/// keeping nothing for the next.
|
||||
fn text_reads<T>(afresh: bool, f: impl FnOnce() -> T) -> (T, u64, u64) {
|
||||
crate::import::ate::TEXTS_READS.set(0);
|
||||
crate::import::ai::TEXT_FRAME_SCANS.set(0);
|
||||
crate::import::native::READ_AFRESH.set(afresh);
|
||||
let out = f();
|
||||
crate::import::native::READ_AFRESH.set(false);
|
||||
(out, crate::import::ate::TEXTS_READS.get(), crate::import::ai::TEXT_FRAME_SCANS.get())
|
||||
}
|
||||
|
||||
/// A `.ai` that opens without its PDF part reads its text document and scans its text objects'
|
||||
/// frames once, for the check that its text document makes all of its type and for the build, and
|
||||
/// comes in as it does when each reads them anew.
|
||||
#[test]
|
||||
fn layers_that_open_alone_read_their_text_once() {
|
||||
let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]);
|
||||
let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1)));
|
||||
let file = private(&native_with_text(&art, &doc));
|
||||
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok();
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
let Some((d, notes)) = opened else { panic!("didn't open without the page") };
|
||||
assert_eq!((texts, frames), (1, 1), "{notes:?}");
|
||||
assert_eq!(text_of(&d.layers[0]).iter().map(|t| t.plain_text()).collect::<Vec<_>>(), ["Hi there", "Mid"], "{notes:?}");
|
||||
let (afresh, texts, frames) = text_reads(true, open);
|
||||
assert_eq!((texts, frames), (2, 2));
|
||||
assert_eq!(afresh, Some((d, notes)));
|
||||
}
|
||||
|
||||
/// Layers whose text document can't be read wait on the PDF part, which then doesn't read the text
|
||||
/// document or scan the frames again, and come in as they do when each check and build reads them
|
||||
/// anew.
|
||||
#[test]
|
||||
fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() {
|
||||
let art = layer("Art", true, &format!("{}\n{}", square(10, 10), text_object(0)));
|
||||
let file = private(&native_with_text(&art, "not a text document"));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = || {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names)
|
||||
};
|
||||
let (opened, texts, frames) = text_reads(false, open);
|
||||
assert_eq!((texts, frames), (1, 1), "{:?}", opened.1);
|
||||
let (afresh, texts, frames) = text_reads(true, open);
|
||||
assert_eq!((texts, frames), (2, 2), "{:?}", afresh.1);
|
||||
assert_eq!(opened, afresh);
|
||||
}
|
||||
|
||||
/// An envelope of type that waits on the PDF part reads the text document and scans the frames
|
||||
/// once, for the check before the PDF part is imported, the build with it, and the build without it
|
||||
/// that follows when the envelope doesn't open live, and the file comes in as it does when each of
|
||||
/// them reads them anew.
|
||||
#[test]
|
||||
fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() {
|
||||
let Some(family) = installed_family() else { return };
|
||||
let stories = [("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0), ("Note\r", 0, (8170.0, 8220.0), (0.0, 0.0), 0.0)];
|
||||
let mut doc = text_document(&stories).replace("(Helvetica)", &format!("({family})"));
|
||||
while ascii85(doc.as_bytes()).len() % 60 == 1 {
|
||||
doc.push('\n');
|
||||
}
|
||||
let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&doc), 30.0));
|
||||
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
|
||||
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
|
||||
let names = crate::NameEncoding::default();
|
||||
let open = |page: Document| {
|
||||
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
|
||||
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
|
||||
};
|
||||
// A PDF part the layers don't draw as: they open alone, after a build with the page and one without.
|
||||
let (opened, texts, frames) = text_reads(false, || open(pdf_part(80.0, 80.0)));
|
||||
assert_eq!((texts, frames), (1, 1), "{:?}", opened.1);
|
||||
let (afresh, texts, frames) = text_reads(true, || open(pdf_part(80.0, 80.0)));
|
||||
assert_eq!((texts, frames), (4, 4), "{:?}", afresh.1);
|
||||
assert_eq!(opened, afresh);
|
||||
let (envelopes, _) = envelopes_and_type(&opened.0);
|
||||
assert!(opened.2 && envelopes.is_empty(), "{envelopes:?} {:?}", opened.1);
|
||||
// A PDF part that draws as those layers, with the drawn art: the envelope opens live.
|
||||
let page = opened.0;
|
||||
let (opened, texts, frames) = text_reads(false, || open(page.clone()));
|
||||
assert_eq!((texts, frames), (1, 1), "{:?}", opened.1);
|
||||
let (afresh, texts, frames) = text_reads(true, || open(page));
|
||||
assert_eq!((texts, frames), (2, 2), "{:?}", afresh.1);
|
||||
assert_eq!(opened, afresh);
|
||||
let (envelopes, _) = envelopes_and_type(&opened.0);
|
||||
assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", opened.1);
|
||||
}
|
||||
|
||||
/// The hidden type outside envelopes in the layers of `d`: each text object's name.
|
||||
fn loose_type_names(d: &Document) -> Vec<Option<String>> {
|
||||
let mut out = vec![];
|
||||
|
||||
@@ -728,6 +728,51 @@ fn images_are_written_in_the_form_the_specification_shows() {
|
||||
assert!(rgb.iter().zip([247.0, 148.0, 29.0]).all(|(c, want)| (c * 255.0 - want).abs() < 0.1), "{rgb:?}");
|
||||
}
|
||||
|
||||
/// An image's samples are written as upper-case hex on `%` comment lines (§8.1, §8.4) of 60
|
||||
/// digits, the last line shorter, each line ending with a newline: no samples write no line, and
|
||||
/// samples that fill their last line exactly write no empty `%` line after it.
|
||||
#[test]
|
||||
fn image_samples_are_written_as_hex_lines() {
|
||||
let hex = |samples: &[u8]| {
|
||||
let mut s = String::new();
|
||||
super::writer::Writer::push_hex(&mut s, samples);
|
||||
s
|
||||
};
|
||||
let mut samples = vec![0x00, 0x09, 0x0A, 0xAF, 0xFF];
|
||||
samples.extend(0x10..=0x29);
|
||||
assert_eq!(hex(&samples), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n%29\n");
|
||||
assert_eq!(hex(&samples[..30]), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n");
|
||||
assert_eq!(hex(&samples[..29]), "%00090AAFFF101112131415161718191A1B1C1D1E1F2021222324252627\n");
|
||||
assert_eq!(hex(&[0xAB]), "%AB\n");
|
||||
assert_eq!(hex(&[]), "");
|
||||
// Appended after what is already written.
|
||||
let mut s = String::from("0 0 1 1 1 1 8 3 0 0 0 0 XI\n");
|
||||
super::writer::Writer::push_hex(&mut s, &[0xC0, 0xFF, 0xEE]);
|
||||
assert_eq!(s, "0 0 1 1 1 1 8 3 0 0 0 0 XI\n%C0FFEE\n");
|
||||
}
|
||||
|
||||
/// The hex lines are the same as formatting each sample with `{:02X}` and breaking the digits
|
||||
/// into lines of [`HEX_LINE`], for every length up to three lines and one more sample, and for
|
||||
/// every byte value.
|
||||
#[test]
|
||||
fn image_hex_matches_formatted_samples() {
|
||||
let formatted = |samples: &[u8]| {
|
||||
let digits: String = samples.iter().map(|c| format!("{c:02X}")).collect();
|
||||
let lines: Vec<String> = digits.as_bytes().chunks(HEX_LINE).map(|l| format!("%{}\n", std::str::from_utf8(l).unwrap())).collect();
|
||||
lines.concat()
|
||||
};
|
||||
let all: Vec<u8> = (0..=255u8).cycle().skip(7).take(3 * HEX_LINE / 2 + 1).collect();
|
||||
for n in 0..=all.len() {
|
||||
let mut s = String::new();
|
||||
super::writer::Writer::push_hex(&mut s, &all[..n]);
|
||||
assert_eq!(s, formatted(&all[..n]), "{n} samples");
|
||||
}
|
||||
let every: Vec<u8> = (0..=255u8).collect();
|
||||
let mut s = String::new();
|
||||
super::writer::Writer::push_hex(&mut s, &every);
|
||||
assert_eq!(s, formatted(&every));
|
||||
}
|
||||
|
||||
/// The pieces of an image cut into a raster mesh warp (as Object › Expand leaves a Warp on an
|
||||
/// image) are written as the image whole once, then each as the part of it that its triangle shows,
|
||||
/// and the file draws as the document does ([`write`] runs it).
|
||||
|
||||
@@ -1213,32 +1213,35 @@ impl<'a> Writer<'a> {
|
||||
coverage
|
||||
}
|
||||
|
||||
/// Appends `samples` to `s` as upper-case hex digits on comment lines: each line starts with `%`,
|
||||
/// holds [`HEX_LINE`] digits (the last line may hold fewer) and ends with a newline. An empty
|
||||
/// `samples` appends no line.
|
||||
pub(super) fn push_hex(s: &mut String, samples: &[u8]) {
|
||||
const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
|
||||
const PER_LINE: usize = HEX_LINE / 2;
|
||||
const _: () = assert!(HEX_LINE > 0 && HEX_LINE.is_multiple_of(2));
|
||||
let lines = samples.len().div_ceil(PER_LINE);
|
||||
s.reserve(samples.len().saturating_mul(2).saturating_add(lines.saturating_mul(2)));
|
||||
for line in samples.chunks(PER_LINE) {
|
||||
s.push('%');
|
||||
for &c in line {
|
||||
s.push(char::from(DIGITS[usize::from(c >> 4)]));
|
||||
s.push(char::from(DIGITS[usize::from(c & 0x0F)]));
|
||||
}
|
||||
s.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/// An image's lines (§8.4): `%AI5_File:`, `%AI5_BeginRaster`, matrix `m` as `[ a b c d tx ty ]`
|
||||
/// and the numbers `operands` with `XI`, `samples` in hex on comment lines of [`HEX_LINE`]
|
||||
/// digits, `%AI5_EndRaster`, then `F`.
|
||||
fn raster(&mut self, m: Affine, operands: &str, samples: &[u8]) {
|
||||
let mut hex = String::with_capacity(samples.len() * 2 + samples.len() / HEX_LINE * 2 + 2);
|
||||
hex.push('%');
|
||||
let mut on_line = 0;
|
||||
for c in samples {
|
||||
let _ = write!(hex, "{c:02X}");
|
||||
on_line += 2;
|
||||
if on_line >= HEX_LINE {
|
||||
hex.push_str("\n%");
|
||||
on_line = 0;
|
||||
}
|
||||
}
|
||||
if hex.ends_with('%') {
|
||||
hex.pop();
|
||||
} else {
|
||||
hex.push('\n');
|
||||
}
|
||||
let [a, b, c, d, e, f] = m.as_coeffs();
|
||||
let s = &mut self.body;
|
||||
s.push_str("%AI5_File:\n%AI5_BeginRaster\n[ ");
|
||||
ps::push_nums(s, &[a, b, c, d, e, f]);
|
||||
let _ = writeln!(s, "] {operands} XI");
|
||||
s.push_str(&hex);
|
||||
Self::push_hex(s, samples);
|
||||
s.push_str("%AI5_EndRaster\nF\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1336,7 +1336,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`): its fields go back to their defaults and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open or the open one has no 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)",
|
||||
),
|
||||
(
|
||||
"ui.justification",
|
||||
|
||||
@@ -48,6 +48,42 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
|
||||
(within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// `(s, t)` moved to where `a` and `b` cross exactly, by Newton's method on a(s) = b(t), or as it
|
||||
/// was when that doesn't settle within both segments, closer than it started, and within the
|
||||
/// distance a piece bent by [`FLAT`] can shift a crossing at their angle there.
|
||||
fn refined(a: &CubicBez, b: &CubicBez, (s0, t0): (f64, f64)) -> (f64, f64) {
|
||||
let gap = |s: f64, t: f64| a.eval(s).distance(b.eval(t));
|
||||
let start = gap(s0, t0);
|
||||
if start <= 1e-12 || !start.is_finite() {
|
||||
return (s0, t0);
|
||||
}
|
||||
let (da, db) = (a.deriv(), b.deriv());
|
||||
let (mut s, mut t) = (s0, t0);
|
||||
for _ in 0..8 {
|
||||
let f = a.eval(s) - b.eval(t);
|
||||
let (u, v) = (da.eval(s).to_vec2(), db.eval(t).to_vec2());
|
||||
// a(s + ds) - b(t + dt) ≈ f + u ds - v dt, which is zero for these steps.
|
||||
let den = u.cross(v);
|
||||
let (ds, dt) = (-f.cross(v) / den, u.cross(f) / den);
|
||||
if !(ds.is_finite() && dt.is_finite()) {
|
||||
return (s0, t0);
|
||||
}
|
||||
(s, t) = (s + ds, t + dt);
|
||||
if !(-1e-12..=1.0 + 1e-12).contains(&s) || !(-1e-12..=1.0 + 1e-12).contains(&t) {
|
||||
return (s0, t0);
|
||||
}
|
||||
if gap(s, t) <= 1e-12 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (s, t) = (s.clamp(0.0, 1.0), t.clamp(0.0, 1.0));
|
||||
let (u, v) = (da.eval(s).to_vec2(), db.eval(t).to_vec2());
|
||||
let sin = u.cross(v).abs() / (u.hypot() * v.hypot());
|
||||
let reach = 4.0 * FLAT / sin + SAME;
|
||||
let moved = a.eval(s).distance(a.eval(s0)).max(b.eval(t).distance(b.eval(t0)));
|
||||
if gap(s, t) < start.min(1e-9) && moved <= reach { (s, t) } else { (s0, t0) }
|
||||
}
|
||||
|
||||
/// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control
|
||||
/// boxes meet until each piece is straight. `None` once `budget` steps are spent.
|
||||
fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
|
||||
@@ -80,6 +116,11 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V
|
||||
stack.extend([(a0, a1, b0, bm, d), (a0, a1, bm, b1, d)]);
|
||||
}
|
||||
}
|
||||
// A piece counts as straight while it bends by up to FLAT, so where the curves meet at a shallow
|
||||
// angle the chords cross some way along from where the curves do.
|
||||
for f in &mut found {
|
||||
*f = refined(a, b, *f);
|
||||
}
|
||||
found.sort_by(|x, y| x.0.total_cmp(&y.0));
|
||||
// The same crossing found by neighbouring pieces counts once.
|
||||
found.dedup_by(|x, y| a.eval(x.0).distance(a.eval(y.0)) < SAME && b.eval(x.1).distance(b.eval(y.1)) < SAME);
|
||||
|
||||
@@ -244,6 +244,42 @@ fn crossings_are_found_on_both_paths() {
|
||||
assert!(near(hits[1][0].2, 0.0, 1e-6) && near(b.subpaths[0].segment(0).eval(hits[0][0].2).x, 50.0, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shallow_crossing_is_placed_where_the_curves_meet() {
|
||||
// Lines square to the middle of a quarter circle of radius 100, just inside it: each crosses the
|
||||
// arc twice, at under a degree for the nearest one.
|
||||
let arc = PathData::single(quarter());
|
||||
let k = std::f64::consts::FRAC_1_SQRT_2;
|
||||
for gap in [0.5, 0.05, 0.005, 0.0005] {
|
||||
let mid = pt((100.0 - gap) * k, (100.0 - gap) * k);
|
||||
let (from, to) = (mid + Vec2::new(-k, k) * 60.0, mid + Vec2::new(k, -k) * 60.0);
|
||||
let across = PathData::single(line(&[(from.x, from.y), (to.x, to.y)], false));
|
||||
let exact: Vec<Point> = kurbo::PathSeg::Cubic(arc.subpaths[0].segment(0))
|
||||
.intersect_line(kurbo::Line::new(from, to))
|
||||
.iter()
|
||||
.map(|x| from.lerp(to, x.line_t))
|
||||
.collect();
|
||||
assert_eq!(exact.len(), 2, "{gap}");
|
||||
let on = |p: &PathData, other: &PathData| -> Vec<Point> {
|
||||
crossings_on(p, &[other]).unwrap().iter().map(|q| p.subpaths[0].segment(q.1).eval(q.2)).collect()
|
||||
};
|
||||
let both = crossings(&[&arc, &across], false).unwrap();
|
||||
let found = [
|
||||
on(&arc, &across),
|
||||
on(&across, &arc),
|
||||
both[0].iter().map(|q| arc.subpaths[0].segment(q.1).eval(q.2)).collect(),
|
||||
both[1].iter().map(|q| across.subpaths[0].segment(q.1).eval(q.2)).collect(),
|
||||
];
|
||||
for places in found {
|
||||
assert_eq!(places.len(), 2, "{gap}: {places:?}");
|
||||
for x in &exact {
|
||||
let off = places.iter().map(|p| p.distance(*x)).fold(f64::INFINITY, f64::min);
|
||||
assert!(off < 1e-6, "{gap}: {off} pt from {x:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_at_keeps_the_shape_and_names_the_new_anchors() {
|
||||
let sp = line(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false);
|
||||
|
||||
@@ -991,7 +991,7 @@ impl<'p> Builder<'p> {
|
||||
self.flush_type3();
|
||||
if let (Some(s), Some(line)) = (&look.stroke, &mut self.text)
|
||||
&& look.fill.is_none()
|
||||
&& line.stroke_last(font_key, at, s.clone(), overprint)
|
||||
&& line.stroke_filled(font_key, at, opacity, &text, s.clone(), overprint)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -1153,9 +1153,13 @@ impl<'p> Builder<'p> {
|
||||
// A stroke over the glyph just filled (fill and stroke rendering).
|
||||
if let (Some(s), Some(line)) = (&look.stroke, &mut self.text)
|
||||
&& look.fill.is_none()
|
||||
&& line.stroke_last(key, at, s.clone(), overprint)
|
||||
&& line.stroke_filled(key, at, opacity, &text, s.clone(), overprint)
|
||||
{
|
||||
self.keep_glyph(o, m, drawn, opacity, scale, overprint);
|
||||
// Upright glyphs aren't kept as outlines (nor, below, are those filled only): a
|
||||
// vertical line that came in as its outlines would lose the ones filled only.
|
||||
if top.is_none() {
|
||||
self.keep_glyph(o, m, drawn, opacity, scale, overprint);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if !self.text.as_mut().is_some_and(place) {
|
||||
|
||||
+225
-15
@@ -61,6 +61,17 @@ impl Placement {
|
||||
fn up(&self) -> Vec2 {
|
||||
Vec2::new(self.dir.y, -self.dir.x)
|
||||
}
|
||||
|
||||
/// Is a glyph placed with `other` drawn where this one is, the same size, width, slant and
|
||||
/// direction (a stroke the reader draws over a glyph it filled has the very same placement;
|
||||
/// the tolerances only allow for rounding)?
|
||||
fn same_as(&self, other: &Placement) -> bool {
|
||||
(self.origin - other.origin).hypot() < self.size * 1e-3
|
||||
&& (self.size - other.size).abs() <= self.size * 1e-3
|
||||
&& (self.h_scale - other.h_scale).abs() < 0.05
|
||||
&& (self.slant - other.slant).abs() < 1e-3
|
||||
&& self.dir.dot(other.dir) > 1.0 - 1e-6
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph set vertically (WMode 1: no horizontal advance) and the top centre of its em box: a
|
||||
@@ -100,16 +111,21 @@ pub(crate) struct Look {
|
||||
}
|
||||
|
||||
impl Look {
|
||||
/// Can a glyph drawn with `other` join a run drawn with this? A fill joins a run whose
|
||||
/// glyphs were also stroked over (fill and stroke rendering draws each glyph twice); invisible
|
||||
/// text (neither fill nor stroke) joins only invisible text.
|
||||
/// Can a glyph drawn with `other` join a run drawn with this? Only a run drawn alike: fill,
|
||||
/// stroke and overprints. A glyph filled only never joins a run whose glyphs were also stroked
|
||||
/// over: it takes a stroke only when one is drawn over it later
|
||||
/// ([`TextLine::stroke_filled`]), which then joins it to the run before if that is stroked
|
||||
/// alike (fill and stroke rendering draws each glyph twice), and a glyph filled only after
|
||||
/// one filled and stroked stays unstroked (#8300). Invisible text (neither fill nor stroke)
|
||||
/// joins only invisible text.
|
||||
fn takes(&self, other: &Look) -> bool {
|
||||
self.font == other.font
|
||||
&& (self.size - other.size).abs() <= self.size * 0.01
|
||||
&& (self.h_scale - other.h_scale).abs() < 0.5
|
||||
&& self.fill == other.fill
|
||||
&& self.overprint_fill == other.overprint_fill
|
||||
&& ((other.stroke.is_none() && other.fill.is_some()) || (self.stroke == other.stroke && self.overprint_stroke == other.overprint_stroke))
|
||||
&& self.stroke == other.stroke
|
||||
&& self.overprint_stroke == other.overprint_stroke
|
||||
}
|
||||
|
||||
fn style(&self) -> CharStyle {
|
||||
@@ -219,6 +235,17 @@ pub(crate) struct TextLine {
|
||||
authored: Vec<bool>,
|
||||
/// Fill callbacks in an authored span, for the reader's later stroke pass.
|
||||
actual_fills: HashMap<(u128, u64, u64), Option<usize>>,
|
||||
/// The glyphs filled without a stroke, in drawing order, for a stroke drawn over them later
|
||||
/// ([`stroke_filled`](Self::stroke_filled)).
|
||||
filled: Vec<Filled>,
|
||||
/// The first of [`filled`](Self::filled) a stroke may still be drawn over: a stroke matches
|
||||
/// glyphs in the order they were filled, and each at most once.
|
||||
stroked: usize,
|
||||
/// Glyphs stroked so far that are still to be restyled: a stroke pass over a word restyles it
|
||||
/// once, as a whole ([`flush_stroke`](Self::flush_stroke)).
|
||||
pending: Option<PendingStroke>,
|
||||
/// The last glyph's placement.
|
||||
last_at: Placement,
|
||||
/// The first glyph was set vertically ([`Upright`]).
|
||||
upright: Option<Upright>,
|
||||
/// The glyphs make a column (vertical type), each below the last.
|
||||
@@ -251,6 +278,28 @@ struct Slot {
|
||||
advance: Option<f64>,
|
||||
}
|
||||
|
||||
/// A glyph filled without a stroke: its font and placement, and where its text is in the line's
|
||||
/// runs (the run's index, the text's byte offset in it and its length).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Filled {
|
||||
font: u128,
|
||||
at: Placement,
|
||||
run: usize,
|
||||
start: usize,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
/// Glyphs next to each other in one run that a stroke is drawn over, not yet restyled
|
||||
/// ([`TextLine::stroke_filled`]): the run's index, the text's byte range in it, and the stroke.
|
||||
#[derive(Clone, Debug)]
|
||||
struct PendingStroke {
|
||||
run: usize,
|
||||
start: usize,
|
||||
end: usize,
|
||||
stroke: TypeStroke,
|
||||
overprint: bool,
|
||||
}
|
||||
|
||||
/// What a finished line of type tells beyond its text object (see [`crate::import_lines`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct LineFacts {
|
||||
@@ -283,6 +332,10 @@ impl TextLine {
|
||||
slots: vec![],
|
||||
authored: vec![],
|
||||
actual_fills: HashMap::new(),
|
||||
filled: vec![],
|
||||
stroked: 0,
|
||||
pending: None,
|
||||
last_at: at,
|
||||
upright: None,
|
||||
column: false,
|
||||
ink: vec![],
|
||||
@@ -313,12 +366,15 @@ impl TextLine {
|
||||
}
|
||||
|
||||
pub fn push_upright_content(&mut self, look: &Look, at: Placement, opacity: f32, upright: Upright, content: TextContent<'_>) -> bool {
|
||||
self.flush_stroke();
|
||||
let text = content.text();
|
||||
if !text.is_empty() && self.authored.is_empty() && self.upright.is_some() {
|
||||
// Suppressed vertical glyphs likewise provide no text anchor.
|
||||
self.at = at;
|
||||
self.opacity = opacity;
|
||||
self.runs.clear();
|
||||
self.filled.clear();
|
||||
self.stroked = 0;
|
||||
self.column = false;
|
||||
}
|
||||
let down = -self.at.up();
|
||||
@@ -327,8 +383,9 @@ impl TextLine {
|
||||
self.runs.push((look.clone(), 0.0, text.to_string()));
|
||||
self.last_start = 0;
|
||||
self.record_actual_fill(look, at, content);
|
||||
self.record_filled(look, at, content);
|
||||
self.authored.extend(text.chars().map(|_| content.authored()));
|
||||
(self.upright, self.next, self.last) = (Some(upright), at.origin + down * at.size, at.origin);
|
||||
(self.upright, self.next, self.last, self.last_at) = (Some(upright), at.origin + down * at.size, at.origin, at);
|
||||
return true;
|
||||
};
|
||||
let across = (at.origin - self.at.origin).dot(self.at.dir);
|
||||
@@ -364,9 +421,11 @@ impl TextLine {
|
||||
self.last_start = 0;
|
||||
}
|
||||
self.record_actual_fill(look, at, content);
|
||||
self.record_filled(look, at, content);
|
||||
self.authored.extend(text.chars().map(|_| content.authored()));
|
||||
self.next = at.origin + down * at.size;
|
||||
self.last = at.origin;
|
||||
self.last_at = at;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -377,6 +436,7 @@ impl TextLine {
|
||||
}
|
||||
|
||||
pub fn push_content(&mut self, look: &Look, at: Placement, opacity: f32, advance: f64, content: TextContent<'_>) -> bool {
|
||||
self.flush_stroke();
|
||||
let text = content.text();
|
||||
let pen = matches!(content, TextContent::Pen);
|
||||
// A vertical line (even a single upright glyph) takes no horizontal glyphs.
|
||||
@@ -394,6 +454,8 @@ impl TextLine {
|
||||
self.last_size = at.size;
|
||||
self.baseline.clear();
|
||||
self.runs.clear();
|
||||
self.filled.clear();
|
||||
self.stroked = 0;
|
||||
}
|
||||
let bytes = self.text_bytes;
|
||||
let glyph = self.baseline.len();
|
||||
@@ -461,6 +523,7 @@ impl TextLine {
|
||||
self.last_start = 0;
|
||||
}
|
||||
self.record_actual_fill(look, at, content);
|
||||
self.record_filled(look, at, content);
|
||||
self.text_bytes = self.text_bytes.saturating_add(text.len());
|
||||
if !pen {
|
||||
let one = text.chars().count() == 1 && !content.authored();
|
||||
@@ -475,6 +538,7 @@ impl TextLine {
|
||||
self.visible = self.next;
|
||||
}
|
||||
self.last = at.origin;
|
||||
self.last_at = at;
|
||||
self.last_dir = at.dir;
|
||||
self.last_size = at.size;
|
||||
self.baseline.push(at.origin);
|
||||
@@ -488,10 +552,22 @@ impl TextLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Note glyph `content` just added to the last run, filled without a stroke, for a stroke
|
||||
/// drawn over it later.
|
||||
fn record_filled(&mut self, look: &Look, at: Placement, content: TextContent<'_>) {
|
||||
let len = content.text().len();
|
||||
if content.authored() || len == 0 || look.fill.is_none() || look.stroke.is_some() {
|
||||
return;
|
||||
}
|
||||
let run = self.runs.len().saturating_sub(1);
|
||||
self.filled.push(Filled { font: look.font, at, run, start: self.last_start, len });
|
||||
}
|
||||
|
||||
/// The reader fills a whole Tj/TJ before replaying its glyphs as strokes. A replay
|
||||
/// must neither consume the replacement nor rewind the pen. Only the first glyph's
|
||||
/// style belongs to the replacement; suppressed glyphs have no text to restyle.
|
||||
pub fn stroke_actual(&mut self, font: u128, at: Placement, stroke: TypeStroke, overprint: bool) -> bool {
|
||||
self.flush_stroke();
|
||||
let key = (font, at.origin.x.to_bits(), at.origin.y.to_bits());
|
||||
let Some(run) = self.actual_fills.remove(&key) else { return false };
|
||||
if let Some((look, ..)) = run.and_then(|i| self.runs.get_mut(i)) {
|
||||
@@ -529,19 +605,152 @@ impl TextLine {
|
||||
Some(bp)
|
||||
}
|
||||
|
||||
/// A stroke (`stroke`: paint, width, cap, join and miter limit) over the glyph just drawn at
|
||||
/// `at` in `font` (fill and stroke rendering), which `overprint`s or not: that glyph is
|
||||
/// stroked. `false`: it isn't that glyph.
|
||||
/// A stroke (`stroke`: paint, width, cap, join and miter limit) over glyph `text` drawn at
|
||||
/// `at` in `font` at `opacity`, which `overprint`s or not, after the glyph was filled (fill
|
||||
/// and stroke rendering): that glyph is stroked. `false`: no glyph on the line was filled so.
|
||||
///
|
||||
/// A filled glyph joins a run of the same fill whatever its stroke ([`Look::takes`]), so the
|
||||
/// run can hold glyphs before it that are stroked otherwise or not at all: then the glyph's
|
||||
/// text becomes a run of its own with this stroke, and the glyphs before it keep theirs
|
||||
/// (#7741). The line's text is the same either way, so the characters' slots, gaps and
|
||||
/// authored flags, kept along the whole line, still line up.
|
||||
pub fn stroke_last(&mut self, font: u128, at: Placement, stroke: TypeStroke, overprint: bool) -> bool {
|
||||
/// The reader fills all the glyphs a text-showing operator (`Tj`, `TJ`, `'`, `"`) draws
|
||||
/// before it strokes them (#8015), or fills and strokes glyph by glyph: either way each
|
||||
/// stroke is matched to the next glyph filled with the same placement (where, how large, how
|
||||
/// wide, slanted and turned), in the same font with the same text, in order. Only that
|
||||
/// glyph's text takes the stroke; strokes over glyphs next to each other in a run gather and
|
||||
/// restyle their text as one run, so a word filled whole and stroked whole stays one run. The
|
||||
/// glyphs around them keep their own stroke or none (#7741).
|
||||
///
|
||||
/// Only opaque type takes its stroke: the file composites a translucent fill and stroke
|
||||
/// apiece, darker where they overlap, while one object's opacity applies to its fill and
|
||||
/// stroke together. Translucent fill and stroke stay type objects of their own, as do a fill
|
||||
/// and stroke at different opacities.
|
||||
pub fn stroke_filled(&mut self, font: u128, at: Placement, opacity: f32, text: &str, stroke: TypeStroke, overprint: bool) -> bool {
|
||||
// A stroke at another opacity than the fill's (`CA` and `ca` differ), or over a
|
||||
// translucent fill, is type of its own.
|
||||
let opaque = opacity >= 0.999 && self.opacity >= 0.999;
|
||||
let rest = if opaque { self.filled.get(self.stroked..) } else { None };
|
||||
let found = rest.and_then(|rest| {
|
||||
rest.iter().position(|g| {
|
||||
g.font == font
|
||||
&& g.at.same_as(&at)
|
||||
&& self.runs.get(g.run).and_then(|(.., t)| t.get(g.start..g.start.saturating_add(g.len))) == Some(text)
|
||||
})
|
||||
});
|
||||
let Some(index) = found.map(|i| self.stroked.saturating_add(i)) else {
|
||||
// Stroked text of its own (stroke rendering): no later stroke goes back over the
|
||||
// glyphs filled before it, so no stroke looks through them again.
|
||||
self.stroked = self.filled.len();
|
||||
// Nor does a translucent stroke join the glyph just filled.
|
||||
return opaque && self.stroke_last(font, at, text, stroke, overprint);
|
||||
};
|
||||
let continues = self
|
||||
.pending
|
||||
.as_ref()
|
||||
.zip(self.filled.get(index))
|
||||
.is_some_and(|(p, g)| p.run == g.run && p.end == g.start && p.stroke == stroke && p.overprint == overprint);
|
||||
if continues {
|
||||
let end = self.filled.get(index).map(|g| g.start.saturating_add(g.len));
|
||||
if let (Some(p), Some(end)) = (&mut self.pending, end) {
|
||||
p.end = end;
|
||||
}
|
||||
} else {
|
||||
// Restyling what was gathered can move this glyph's text to another run: look it up after.
|
||||
self.flush_stroke();
|
||||
if let Some(g) = self.filled.get(index) {
|
||||
self.pending = Some(PendingStroke { run: g.run, start: g.start, end: g.start.saturating_add(g.len), stroke, overprint });
|
||||
}
|
||||
}
|
||||
self.stroked = index.saturating_add(1);
|
||||
true
|
||||
}
|
||||
|
||||
/// Restyle the glyphs gathered for a stroke ([`stroke_filled`](Self::stroke_filled)): their
|
||||
/// text becomes a run of its own with the stroke, unless the run is stroked so already, and the
|
||||
/// text before and after it in the run keeps its stroke. Text that comes right after a run
|
||||
/// drawn alike joins it, a run made up of it whole too: fill and stroke rendering glyph by
|
||||
/// glyph fills each glyph as a run of its own ([`Look::takes`]) before its stroke (#8300).
|
||||
fn flush_stroke(&mut self) {
|
||||
let Some(PendingStroke { run, start, end, stroke, overprint }) = self.pending.take() else { return };
|
||||
let last = run.saturating_add(1) == self.runs.len();
|
||||
let previous = run.checked_sub(1).and_then(|i| self.runs.get(i)).map(|(l, sh, t)| (l.clone(), *sh, t.len()));
|
||||
let Some((look, shift, text)) = self.runs.get_mut(run) else { return };
|
||||
if look.stroke.as_ref() == Some(&stroke) && look.overprint_stroke == overprint {
|
||||
return;
|
||||
}
|
||||
if !(start < end && end <= text.len() && text.is_char_boundary(start) && text.is_char_boundary(end)) {
|
||||
return;
|
||||
}
|
||||
let tail = text.split_off(end);
|
||||
let glyphs = text.split_off(start);
|
||||
let head = std::mem::take(text);
|
||||
let mut own = look.clone();
|
||||
(own.stroke, own.overprint_stroke) = (Some(stroke), overprint);
|
||||
let (old, shift) = (look.clone(), *shift);
|
||||
// The stroked text joins the run before when nothing is left before it in its own run and
|
||||
// that run is drawn alike.
|
||||
let joins = match &previous {
|
||||
Some((l, sh, _)) => head.is_empty() && *l == own && (sh - shift).abs() < 1e-3,
|
||||
None => false,
|
||||
};
|
||||
let joined_at = previous.as_ref().map_or(0, |(.., len)| *len);
|
||||
let mut pieces = vec![];
|
||||
if !head.is_empty() {
|
||||
pieces.push((old.clone(), shift, head.clone()));
|
||||
}
|
||||
// Where each part of the run's text goes: its run and how far its new run's text starts
|
||||
// before it (bytes), for the head, the stroked glyphs and the tail.
|
||||
let head_at = (run, 0usize);
|
||||
let glyphs_at = if joins {
|
||||
(run.saturating_sub(1), joined_at)
|
||||
} else {
|
||||
pieces.push((own, shift, glyphs.clone()));
|
||||
(run.saturating_add(pieces.len()).saturating_sub(1), 0)
|
||||
};
|
||||
if !tail.is_empty() {
|
||||
pieces.push((old, shift, tail));
|
||||
}
|
||||
let tail_at = run.saturating_add(pieces.len()).saturating_sub(1);
|
||||
let count = pieces.len();
|
||||
if joins && let Some((.., t)) = run.checked_sub(1).and_then(|i| self.runs.get_mut(i)) {
|
||||
t.push_str(&glyphs);
|
||||
}
|
||||
self.runs.splice(run..run.saturating_add(1), pieces);
|
||||
let moved = |r: usize, at: usize| -> (usize, usize) {
|
||||
if r > run {
|
||||
(r.saturating_add(count).saturating_sub(1), at)
|
||||
} else if r < run {
|
||||
(r, at)
|
||||
} else if at < start {
|
||||
(head_at.0, at)
|
||||
} else if at < end {
|
||||
(glyphs_at.0, at.saturating_sub(start).saturating_add(glyphs_at.1))
|
||||
} else {
|
||||
(tail_at, at.saturating_sub(end))
|
||||
}
|
||||
};
|
||||
let from = self.stroked.min(self.filled.len());
|
||||
for g in self.filled.iter_mut().skip(from) {
|
||||
(g.run, g.start) = moved(g.run, g.start);
|
||||
}
|
||||
for i in self.actual_fills.values_mut().flatten() {
|
||||
*i = moved(*i, 0).0;
|
||||
}
|
||||
if last {
|
||||
self.last_start = moved(run, self.last_start).1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke over glyph `glyph` just drawn at `at` in `font`, which `overprint`s or not: that
|
||||
/// glyph is stroked. `false`: it isn't that glyph (another place, font or text).
|
||||
///
|
||||
/// The glyph's run can hold glyphs before it, filled alike and not stroked
|
||||
/// ([`Look::takes`]): then the glyph's text becomes a run of its own with this stroke, and
|
||||
/// the glyphs before it stay unstroked (#7741). The line's text is the same either way, so
|
||||
/// the characters' slots, gaps and authored flags, kept along the whole line, still line up.
|
||||
fn stroke_last(&mut self, font: u128, at: Placement, glyph: &str, stroke: TypeStroke, overprint: bool) -> bool {
|
||||
self.flush_stroke();
|
||||
let start = self.last_start;
|
||||
let last_at = self.last_at;
|
||||
// The glyph just filled, in the same font and placement, with the same text.
|
||||
let Some((look, shift, text)) =
|
||||
self.runs.last_mut().filter(|(l, ..)| l.font == font && (at.origin - self.last).hypot() < self.at.size * 1e-3)
|
||||
self.runs.last_mut().filter(|(l, _, t)| l.font == font && last_at.same_as(&at) && t.get(start..) == Some(glyph))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
@@ -563,6 +772,7 @@ impl TextLine {
|
||||
|
||||
/// The point type object, its opacity and what else the line tells.
|
||||
pub fn finish(mut self) -> Option<(TextObject, f32, LineFacts)> {
|
||||
self.flush_stroke();
|
||||
let mut facts = LineFacts { ink: std::mem::take(&mut self.ink), ..LineFacts::default() };
|
||||
// Turned along a curve: type on a path through the glyphs.
|
||||
let path = if self.curved() { self.baseline_path() } else { None };
|
||||
|
||||
+20
-3
@@ -6,7 +6,7 @@
|
||||
//! transparency (the app flattens it before writing), no layers, PDF 1.3.
|
||||
//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3.
|
||||
//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the
|
||||
//! XMP metadata names the standard too.
|
||||
//! XMP metadata names the standard too and carries `xmp:MetadataDate`.
|
||||
//! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a
|
||||
//! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the
|
||||
//! document information, a title and dates, embedded fonts (or text as outlines), no editing
|
||||
@@ -120,8 +120,9 @@ pub(crate) fn info_entries(standard: Standard) -> String {
|
||||
}
|
||||
|
||||
/// Edit the XMP metadata of a PDF/X file (the catalog's `/Metadata` stream; `root` is the
|
||||
/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped and a version
|
||||
/// id (PDF 1.3 files say so in [`finish`]). Files without metadata are left as they are.
|
||||
/// catalog dictionary's contents) into `patch`: PDF/X-4 adds the standard, Trapped, a version id
|
||||
/// and the metadata date (PDF 1.3 files say so in [`finish`]). Files without metadata are left as
|
||||
/// they are.
|
||||
pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Patch, standard: Standard, trapped: bool) -> Result<(), PdfError> {
|
||||
if !standard.is_pdfx() {
|
||||
return Ok(());
|
||||
@@ -145,6 +146,22 @@ pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Pat
|
||||
"<pdfxid:GTS_PDFXVersion xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\">{version}</pdfxid:GTS_PDFXVersion><pdf:Trapped>{trapped}</pdf:Trapped><xmpMM:VersionID>1</xmpMM:VersionID>"
|
||||
);
|
||||
edits.push((close, close, props.into_bytes()));
|
||||
// When the packet has no `<xmp:MetadataDate>` element, this adds one after the writer's
|
||||
// `<xmp:ModifyDate>` element with the same value. The search expects the writer's form:
|
||||
// properties written as elements with the `xmp` prefix, and `<` in text written as `<`.
|
||||
// The writer's description declares the `xmp` prefix there, and
|
||||
// [`crate::post::modification_date`] keeps the two dates equal.
|
||||
if find(xml, b"<xmp:MetadataDate>", 0).is_none()
|
||||
&& let Some(at) = find(xml, b"<xmp:ModifyDate>", 0).map(|i| i + b"<xmp:ModifyDate>".len())
|
||||
&& let Some(to) = find(xml, b"</xmp:ModifyDate>", at)
|
||||
{
|
||||
let date = xml.get(at..to).ok_or_else(bad)?;
|
||||
let mut prop = b"<xmp:MetadataDate>".to_vec();
|
||||
prop.extend_from_slice(date);
|
||||
prop.extend_from_slice(b"</xmp:MetadataDate>");
|
||||
let after = to + b"</xmp:ModifyDate>".len();
|
||||
edits.push((after, after, prop));
|
||||
}
|
||||
}
|
||||
// Every edit grows the stream (or keeps its length).
|
||||
let grown: usize = edits.iter().map(|(s, e, new)| new.len().saturating_sub(e - s)).sum();
|
||||
|
||||
@@ -84,8 +84,9 @@ pub(crate) fn user_units(pdf: Vec<u8>, units: &[f64]) -> Result<Vec<u8>, PdfErro
|
||||
/// `pdf` dated as modified at `modified` (Unix seconds, UTC), its creation dates kept: the
|
||||
/// document information's `/ModDate` (a PDF date, ISO 32000-1 §7.9.4) and every `xmp:ModifyDate`,
|
||||
/// `xmp:MetadataDate` and `stEvt:when` of the catalog's XMP metadata (ISO 8601 dates), in UTC as
|
||||
/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate` and
|
||||
/// `stEvt:when` the creation date.
|
||||
/// the PDF writer writes the creation date. The writer gives `/ModDate`, `xmp:ModifyDate`,
|
||||
/// `stEvt:when` and, in a PDF/X-4 file, `xmp:MetadataDate` ([`crate::pdfx::xmp`]) the creation
|
||||
/// date.
|
||||
pub(crate) fn modification_date(pdf: Vec<u8>, modified: i64) -> Result<Vec<u8>, PdfError> {
|
||||
let failed = |why: &str| PdfError::Write(format!("can't write the file's modification date: {why}"));
|
||||
let Parsed { xref, objects, trailer, root, .. } = linearize::parse(&pdf).map_err(failed)?;
|
||||
|
||||
+12
-4
@@ -12,7 +12,8 @@
|
||||
//! - Marks and bleed as PDF export draws them ([`crate::MarkSettings`], [`crate::BleedSettings`]),
|
||||
//! around the artboard on the paper, at the paper's scale.
|
||||
//! - Output: composite, or separations, one page per ink that prints ([`print_inks`]) in the
|
||||
//! grey of its coverage (overprints honoured, spot colours as process if asked), emulsion down
|
||||
//! gray of its coverage (overprints honored, every spot color or chosen ones as process if
|
||||
//! asked), emulsion down
|
||||
//! (mirrored), negative (inverted).
|
||||
//! - Colour management: the printer profile composite colours are converted to (and
|
||||
//! separations separate with), the rendering intent, and whether CMYK colours keep their
|
||||
@@ -43,7 +44,7 @@ use vectorcraft_doc::overprint::{OverprintBlack, clear_overprints, darken_overpr
|
||||
use vectorcraft_doc::{ColorMode, Document, Node, NodeKind};
|
||||
|
||||
pub use layout::{MAX_COPIES_PER_SHEET, MAX_TILES, TileGrid};
|
||||
pub use plates::print_inks;
|
||||
pub use plates::{document_inks, print_inks};
|
||||
pub use settings::*;
|
||||
pub use tiling::{TilingPage, tiling};
|
||||
|
||||
@@ -132,6 +133,9 @@ pub struct PrintPreview {
|
||||
pub tiles: Vec<TileGrid>,
|
||||
/// The inks of a separation (empty for composite output).
|
||||
pub inks: Vec<PrintInk>,
|
||||
/// Every ink of the document as a separation lists it, the spot inks printing as process
|
||||
/// (which `inks` leaves out) included ([`document_inks`]); empty for composite output.
|
||||
pub document_inks: Vec<PrintInk>,
|
||||
/// What the job leaves out of the document or prints differently.
|
||||
pub warnings: Vec<String>,
|
||||
/// Notes on the options: one the job doesn't apply or applies another way. They aren't
|
||||
@@ -148,6 +152,8 @@ struct Job<'a> {
|
||||
tiles: Vec<TileGrid>,
|
||||
/// The inks of a separation (every one, printed or not).
|
||||
inks: Vec<PrintInk>,
|
||||
/// Every ink of the document, the spot inks printing as process included.
|
||||
document_inks: Vec<PrintInk>,
|
||||
/// The inks that print (indices into `inks`): each a plate.
|
||||
plates: Vec<usize>,
|
||||
/// One copy's pages: (layout, plate).
|
||||
@@ -444,8 +450,9 @@ impl<'a> Job<'a> {
|
||||
let (mut warnings, mut setting_notes) = (vec![], vec![]);
|
||||
let (layouts, tiles) = layout::layout(&doc, set, &mut warnings, &mut setting_notes)?;
|
||||
let separations = set.output.mode == OutputMode::Separations;
|
||||
let (inks, more) = if separations { print_inks(&doc, set) } else { Default::default() };
|
||||
let (document_inks, more) = if separations { document_inks(&doc, set) } else { Default::default() };
|
||||
setting_notes.extend(more);
|
||||
let inks: Vec<PrintInk> = document_inks.iter().filter(|i| !i.convert_to_process).cloned().collect();
|
||||
let plates: Vec<usize> = (0..inks.len()).filter(|i| inks[*i].print).collect();
|
||||
let printed: Vec<Option<usize>> = if separations { (0..plates.len()).map(Some).collect() } else { vec![None] };
|
||||
if printed.is_empty() {
|
||||
@@ -474,7 +481,7 @@ impl<'a> Job<'a> {
|
||||
if !postscript && !set.graphics.auto_flatness {
|
||||
setting_notes.push("a fixed flatness is not written yet: the output device flattens curves".into());
|
||||
}
|
||||
Ok(Self { doc, layouts, tiles, inks, plates, sheets, warnings, setting_notes })
|
||||
Ok(Self { doc, layouts, tiles, inks, document_inks, plates, sheets, warnings, setting_notes })
|
||||
}
|
||||
|
||||
/// The ink of plate `plate` (`None`: composite).
|
||||
@@ -526,6 +533,7 @@ pub fn preview(doc: &Document, set: &PrintSettings) -> Result<PrintPreview, PdfE
|
||||
sheets,
|
||||
tiles: job.tiles,
|
||||
inks: job.inks,
|
||||
document_inks: job.document_inks,
|
||||
warnings: job.warnings,
|
||||
setting_notes: job.setting_notes,
|
||||
})
|
||||
|
||||
@@ -2,58 +2,80 @@
|
||||
//! colour (and image pixel) replaced by the grey of that ink's coverage. An image placed from a
|
||||
//! DCS file prints its own plates ([`vectorcraft_doc::separated`]).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::cms::{self, Cms, Model, ProfileKind};
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors};
|
||||
use vectorcraft_doc::overprint::{darken_overprints, is_white};
|
||||
use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white};
|
||||
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind};
|
||||
|
||||
use super::{DEFAULT_FREQUENCY, PrintInk, PrintSettings};
|
||||
use super::{DEFAULT_FREQUENCY, InkSettings, PrintInk, PrintSettings};
|
||||
|
||||
/// The inks of a separation of `doc`: the process inks, then one per spot swatch (none when
|
||||
/// spots print as process), with the options of [`super::PrintOutput::inks`]; and a warning
|
||||
/// naming the options that name no ink.
|
||||
pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) {
|
||||
let out = &set.output;
|
||||
// Options by ink name, the first for a name winning: looked up, not searched for each ink.
|
||||
let mut options = std::collections::HashMap::new();
|
||||
for o in &out.inks {
|
||||
/// The options of [`super::PrintOutput::inks`] by ink name, the first for a name winning: looked
|
||||
/// up, not searched for each ink.
|
||||
fn ink_options(set: &PrintSettings) -> HashMap<&str, &InkSettings> {
|
||||
let mut options = HashMap::new();
|
||||
for o in &set.output.inks {
|
||||
options.entry(o.name.as_str()).or_insert(o);
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// The inks of a separation of `doc`: the process inks, then one per spot swatch (none for a spot
|
||||
/// ink that prints as process, [`document_inks`]), with the options of
|
||||
/// [`super::PrintOutput::inks`]; and the notes of [`document_inks`].
|
||||
pub fn print_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) {
|
||||
let (mut list, notes) = document_inks(doc, set);
|
||||
list.retain(|p| !p.convert_to_process);
|
||||
(list, notes)
|
||||
}
|
||||
|
||||
/// Every ink of `doc` as a separation lists it: the process inks, then one per spot swatch, with
|
||||
/// the options of [`super::PrintOutput::inks`]. A spot ink prints as process inks
|
||||
/// ([`PrintInk::convert_to_process`]) with Convert All Spot Colors to Process or its own
|
||||
/// `convertToProcess`; its other options are kept for when it prints as a spot ink again. Notes:
|
||||
/// one warning naming the options that name no ink, and one naming the process inks whose
|
||||
/// options ask for a conversion they don't take.
|
||||
pub fn document_inks(doc: &Document, set: &PrintSettings) -> (Vec<PrintInk>, Vec<String>) {
|
||||
let out = &set.output;
|
||||
let options = ink_options(set);
|
||||
let list: Vec<PrintInk> = plates(doc)
|
||||
.into_iter()
|
||||
.filter(|p| !(p.spot && out.spots_to_process))
|
||||
.map(|p| {
|
||||
let o = options.get(p.name.as_str()).copied();
|
||||
PrintInk {
|
||||
print: o.is_none_or(|o| o.print),
|
||||
frequency: o.and_then(|o| o.frequency).unwrap_or(DEFAULT_FREQUENCY),
|
||||
angle: o.and_then(|o| o.angle).unwrap_or_else(|| PrintInk::default_angle(&p.name)),
|
||||
convert_to_process: p.spot && (out.spots_to_process || o.is_some_and(|o| o.convert_to_process)),
|
||||
spot: p.spot,
|
||||
name: p.name,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let few = |all: Vec<&str>| {
|
||||
let more = all.len().saturating_sub(MAX_NAMED);
|
||||
let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
|
||||
if more > 0 { format!("{shown} and {more} more") } else { shown }
|
||||
};
|
||||
// One warning for all the options naming no ink, each list cut short: the options and the
|
||||
// inks both come from the file.
|
||||
// inks both come from the file. A spot ink printing as process is still an ink of the job.
|
||||
let names: BTreeSet<&str> = list.iter().map(|p| p.name.as_str()).collect();
|
||||
let unknown: Vec<&str> = out.inks.iter().map(|i| i.name.as_str()).filter(|n| !names.contains(n)).collect();
|
||||
let warnings = if unknown.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
let few = |all: Vec<&str>| {
|
||||
let more = all.len().saturating_sub(MAX_NAMED);
|
||||
let shown = all.into_iter().take(MAX_NAMED).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
|
||||
if more > 0 { format!("{shown} and {more} more") } else { shown }
|
||||
};
|
||||
let mut notes = vec![];
|
||||
if !unknown.is_empty() {
|
||||
let inks = few(list.iter().map(|p| p.name.as_str()).collect());
|
||||
vec![format!("there is no ink named {} to print (inks: {inks})", few(unknown))]
|
||||
};
|
||||
(list, warnings)
|
||||
notes.push(format!("there is no ink named {} to print (inks: {inks})", few(unknown)));
|
||||
}
|
||||
let process: Vec<&str> =
|
||||
list.iter().filter(|p| !p.spot && options.get(p.name.as_str()).is_some_and(|o| o.convert_to_process)).map(|p| p.name.as_str()).collect();
|
||||
if !process.is_empty() {
|
||||
notes.push(format!("{} print as process inks already: only spot inks convert to process", few(process)));
|
||||
}
|
||||
(list, notes)
|
||||
}
|
||||
|
||||
/// The most names a warning of [`print_inks`] lists.
|
||||
@@ -78,20 +100,30 @@ pub(crate) struct Separator<'a> {
|
||||
pub doc: &'a Document,
|
||||
cms: Arc<Cms>,
|
||||
set: &'a PrintSettings,
|
||||
/// The inks whose own options convert them to process ([`InkSettings::convert_to_process`]).
|
||||
converted: HashSet<&'a str>,
|
||||
/// The plates are written as PostScript, which has no blending modes.
|
||||
postscript: bool,
|
||||
}
|
||||
|
||||
impl<'a> Separator<'a> {
|
||||
pub fn new(doc: &'a Document, set: &'a PrintSettings, postscript: bool) -> Self {
|
||||
Self { doc, cms: separation_cms(doc, set), set, postscript }
|
||||
let converted = ink_options(set).into_iter().filter(|(_, o)| o.convert_to_process).map(|(name, _)| name).collect();
|
||||
Self { doc, cms: separation_cms(doc, set), set, converted, postscript }
|
||||
}
|
||||
|
||||
/// Whether colors linked to swatch `name` print as process inks: every swatch but
|
||||
/// Registration with Convert All Spot Colors to Process, else the inks converted one by one.
|
||||
/// A link to a process swatch separates as its color either way.
|
||||
fn converts(&self, name: &str) -> bool {
|
||||
name != REGISTRATION && (self.set.output.spots_to_process || self.converted.contains(name))
|
||||
}
|
||||
|
||||
/// How much of ink `plate` colour `c` (with swatch link `link`) prints, 0..1.
|
||||
fn ink(&self, plate: &str, c: &Color, link: Link) -> f32 {
|
||||
let color = &self.set.color;
|
||||
// Spot colours as process: only Registration keeps its link.
|
||||
let link = link.filter(|(name, _)| !self.set.output.spots_to_process || *name == REGISTRATION);
|
||||
// Spot colors as process lose their link; Registration always keeps its.
|
||||
let link = link.filter(|(name, _)| !self.converts(name));
|
||||
// Without Preserve Numbers, CMYK colours are separated again from their appearance.
|
||||
let lab;
|
||||
let c = if !color.preserve_numbers && matches!(c, Color::Cmyk { .. }) {
|
||||
@@ -104,15 +136,16 @@ impl<'a> Separator<'a> {
|
||||
}
|
||||
|
||||
/// [`Self::ink`] of a colour that prints process plates `plates` with its spot tint
|
||||
/// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. With
|
||||
/// spots as process, each process plate prints `plates` layered with the spot tint's process
|
||||
/// equivalent, as a separated image's plates layer ([`vectorcraft_doc::separated::Separated::coverage_as`]).
|
||||
/// ([`stop_inks`]): the spot plate prints the tint and the process plates print `plates`. When
|
||||
/// its spot ink prints as process, each process plate prints `plates` layered with the spot
|
||||
/// tint's process equivalent, as a separated image's plates layer
|
||||
/// ([`vectorcraft_doc::separated::Separated::coverage_as`]).
|
||||
fn stop_ink(&self, plate: &str, c: &Color, link: Link, plates: StopPlates) -> f32 {
|
||||
let own = stop_inks(self.doc, &self.cms, c, link, plates, self.set.color.intent);
|
||||
let (Some(_), Some((name, tint))) = (plates, own.spot.as_ref()) else {
|
||||
return self.ink(plate, c, link);
|
||||
};
|
||||
if !self.set.output.spots_to_process {
|
||||
if !self.converts(name) {
|
||||
return own.on_plate(plate);
|
||||
}
|
||||
let Some(i) = cms::PROCESS_PLATES.iter().position(|p| *p == plate) else {
|
||||
@@ -135,17 +168,26 @@ impl<'a> Separator<'a> {
|
||||
|
||||
/// Whether paint `p` puts none of ink `plate` down: a solid color, a gradient whose every stop
|
||||
/// does, or a freeform gradient with color points whose every point does (points carry no
|
||||
/// swatch link). On PostScript plates, to within half a percent (the other inks a black may
|
||||
/// carry and still count as black, [`vectorcraft_doc::overprint::is_black_ink`]).
|
||||
/// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that
|
||||
/// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as
|
||||
/// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a
|
||||
/// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of
|
||||
/// another ink such a black may carry counts as none.
|
||||
fn no_ink(&self, plate: &str, p: &Paint) -> bool {
|
||||
let none = if self.postscript { 0.005 } else { 0.0 };
|
||||
let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot));
|
||||
let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false));
|
||||
match p {
|
||||
Paint::Solid { color, swatch, tint } => self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))) <= none,
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint))))
|
||||
}
|
||||
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
|
||||
Some(f) => f.points.iter().all(|pt| self.ink(plate, &pt.color, None) <= none),
|
||||
Some(f) => f.points.iter().all(|pt| none(&pt.color, true, self.ink(plate, &pt.color, None))),
|
||||
None => {
|
||||
!g.gradient.stops.is_empty()
|
||||
&& g.gradient.stops.iter().all(|s| self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates) <= none)
|
||||
&& g.gradient.stops.iter().all(|s| {
|
||||
let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates);
|
||||
none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink)
|
||||
})
|
||||
}
|
||||
},
|
||||
_ => false,
|
||||
@@ -156,7 +198,9 @@ impl<'a> Separator<'a> {
|
||||
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
|
||||
/// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which
|
||||
/// knock out). A writer without blending modes (PostScript) then keeps the ink below them,
|
||||
/// where it would draw their Darken as a knockout.
|
||||
/// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on
|
||||
/// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting
|
||||
/// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2).
|
||||
fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc<Node>, discard_white: bool) {
|
||||
let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p);
|
||||
let n = Arc::make_mut(a);
|
||||
@@ -207,12 +251,8 @@ impl<'a> Separator<'a> {
|
||||
}
|
||||
}
|
||||
// A DCS file's image prints its own plates: a spot plate on its ink when the job prints
|
||||
// that ink, else as its process equivalent.
|
||||
let spots: BTreeSet<String> = if self.set.output.spots_to_process {
|
||||
BTreeSet::new()
|
||||
} else {
|
||||
plates(self.doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
|
||||
};
|
||||
// that ink as a spot ink, else as its process equivalent.
|
||||
let spots: BTreeSet<String> = plates(self.doc).into_iter().filter(|p| p.spot && !self.converts(&p.name)).map(|p| p.name).collect();
|
||||
let own = |name: &str| spots.contains(name);
|
||||
// A spot plate printing as process prints as the document's swatch of its ink does, when
|
||||
// there is one; else as the process equivalent its file gives.
|
||||
|
||||
@@ -462,15 +462,21 @@ pub struct InkSettings {
|
||||
/// Halftone screen angle (degrees); `None`: the ink's default.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub angle: Option<f64>,
|
||||
/// A spot ink prints as process inks: no plate of its own, its color on the process plates.
|
||||
/// Off by default. [`PrintOutput::spots_to_process`] converts every spot ink whatever this
|
||||
/// says; process inks and Registration ignore it.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub convert_to_process: bool,
|
||||
}
|
||||
|
||||
impl Default for InkSettings {
|
||||
fn default() -> Self {
|
||||
Self { name: String::new(), print: true, frequency: None, angle: None }
|
||||
Self { name: String::new(), print: true, frequency: None, angle: None, convert_to_process: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// An ink of a separation, with its options resolved ([`super::inks`]).
|
||||
/// An ink of a separation, with its options resolved ([`super::print_inks`],
|
||||
/// [`super::document_inks`]).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PrintInk {
|
||||
@@ -479,6 +485,10 @@ pub struct PrintInk {
|
||||
pub print: bool,
|
||||
pub frequency: f64,
|
||||
pub angle: f64,
|
||||
/// A spot ink printing as process inks (its own option or Convert All Spot Colors to
|
||||
/// Process): it has no plate.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub convert_to_process: bool,
|
||||
}
|
||||
|
||||
/// The default halftone screen ruling (lpi).
|
||||
|
||||
@@ -465,9 +465,14 @@ impl Default for SecuritySettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` lies in `lo..=hi` (and is a number).
|
||||
/// `v` lies in `lo..=hi` (and is a number). The error names the range with its unit as one value
|
||||
/// (`72–2400 ppi`), so a catalog can match the message and translate it.
|
||||
pub(crate) fn within(name: &str, v: f64, lo: f64, hi: f64, unit: &str) -> Result<(), PdfError> {
|
||||
if (lo..=hi).contains(&v) { Ok(()) } else { Err(PdfError::BadSetting(format!("{name} must be {lo}–{hi}{unit} (got {v})"))) }
|
||||
if (lo..=hi).contains(&v) {
|
||||
return Ok(());
|
||||
}
|
||||
let range = format!("{lo}–{hi}{unit}");
|
||||
Err(PdfError::BadSetting(format!("{name} must be {range} (got {v})")))
|
||||
}
|
||||
|
||||
impl PdfSettings {
|
||||
|
||||
@@ -423,6 +423,43 @@ fn a_dcs_spot_plate_printing_as_process_takes_the_documents_swatch() {
|
||||
assert_eq!(get(&own, "Yellow"), Some(vec![0, 0]));
|
||||
}
|
||||
|
||||
/// A DCS image's spot plate converted to process on its own prints as the document's swatch of
|
||||
/// its ink, while its other spot plate keeps printing on its ink.
|
||||
#[test]
|
||||
fn a_dcs_image_converts_only_the_spot_ink_chosen() {
|
||||
use vectorcraft_doc::separated::{InkPlate, Separated};
|
||||
let plate = |name: &str, cmyk: [f32; 4], data: [u8; 2]| InkPlate { name: name.into(), cmyk, data: data.to_vec() };
|
||||
let s = Separated::new(
|
||||
2,
|
||||
1,
|
||||
vec![
|
||||
plate("Cyan", [0.0; 4], [0, 0]),
|
||||
plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], [128, 0]),
|
||||
plate("Spot Green", [0.0, 0.0, 1.0, 0.0], [0, 128]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let mut d = image_doc(ImageBlob::separated_tiff(&s, None, &[]).unwrap(), 2, 1);
|
||||
d.swatches.push(Swatch { name: "Spot Orange".into(), paint: Paint::solid(Color::cmyk(0.0, 0.6, 1.0, 0.0)), global: true, spot: true });
|
||||
// The document's Spot Green is cyan, where its file says yellow.
|
||||
d.swatches.push(Swatch { name: "Spot Green".into(), paint: Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)), global: true, spot: true });
|
||||
let settings: PrintSettings =
|
||||
serde_json::from_value(json!({"output": {"mode": "separations", "inks": [{"name": "Spot Green", "convertToProcess": true}]}})).unwrap();
|
||||
let names: Vec<String> = print_inks(&d, &settings).0.into_iter().map(|i| i.name).collect();
|
||||
assert_eq!(names, ["Cyan", "Magenta", "Yellow", "Black", "Spot Orange"]);
|
||||
let job = plan(&d, &PrintOptions { settings, ..Default::default() }).unwrap();
|
||||
let coverage = job.plates.iter().map(|p| {
|
||||
let NodeKind::Image(im) = &p.layers[0].children().unwrap()[0].kind else { panic!("an image") };
|
||||
p.image_blob(im).and_then(|b| b.coverage()).unwrap().2
|
||||
});
|
||||
let all: Vec<(String, Vec<u8>)> = names.into_iter().zip(coverage).collect();
|
||||
let get = |name: &str| all.iter().find(|(n, _)| n == name).map(|(_, c)| c.clone());
|
||||
assert_eq!(get("Cyan"), Some(vec![0, 128]), "the swatch's cyan");
|
||||
assert_eq!(get("Yellow"), Some(vec![0, 0]), "not the file's yellow");
|
||||
assert_eq!(get("Magenta"), Some(vec![0, 0]), "Spot Orange stays on its own plate");
|
||||
assert_eq!(get("Spot Orange"), Some(vec![128, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_output_settings_convert_cmyk_images_and_compression_recompresses_them_in_cmyk() {
|
||||
let ink = [0u8, 102, 255, 0];
|
||||
|
||||
@@ -42,6 +42,51 @@ fn text(pdf: &[u8]) -> String {
|
||||
String::from_utf8_lossy(pdf).into_owned()
|
||||
}
|
||||
|
||||
/// The XMP packet of `pdf`, read as its stream's `/Length` says: the packet's end must be inside
|
||||
/// those bytes and nothing but the end of line may follow them before `endstream`.
|
||||
fn xmp_packet(pdf: &[u8]) -> String {
|
||||
use crate::lab_spot::{find, rfind};
|
||||
let begin = find(pdf, b"<?xpacket begin", 0).expect("an XMP packet");
|
||||
let head = &pdf[..begin];
|
||||
let obj = rfind(head, b" obj").expect("the packet's object");
|
||||
let dict = &head[obj..];
|
||||
let at = find(dict, b"/Length ", 0).expect("its length") + b"/Length ".len();
|
||||
let digits: Vec<u8> = dict[at..].iter().copied().take_while(u8::is_ascii_digit).collect();
|
||||
let length: usize = String::from_utf8(digits).unwrap().parse().unwrap();
|
||||
let mut data = obj + rfind(dict, b"stream").unwrap() + b"stream".len();
|
||||
data += pdf[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count();
|
||||
let stream = &pdf[data..data + length];
|
||||
let close = find(stream, b"<?xpacket end=", 0).expect("the packet ends inside the stream's length");
|
||||
assert!(find(stream, b"?>", close).is_some(), "the packet ends inside the stream's length");
|
||||
let rest = String::from_utf8_lossy(&pdf[data + length..]);
|
||||
assert!(rest.trim_start_matches(['\r', '\n']).starts_with("endstream"), "the stream ends at its length");
|
||||
String::from_utf8(stream.to_vec()).unwrap()
|
||||
}
|
||||
|
||||
/// The value of the XMP element `tag` in `xmp`.
|
||||
fn xmp_value<'a>(xmp: &'a str, tag: &str) -> Option<&'a str> {
|
||||
let open = format!("<{tag}>");
|
||||
let rest = &xmp[xmp.find(&open)? + open.len()..];
|
||||
Some(&rest[..rest.find(&format!("</{tag}>"))?])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdfx4_metadata_has_a_metadata_date_equal_to_the_modification_date() {
|
||||
let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0)]);
|
||||
// Dated by the writer (created), then dated again after writing (modified later).
|
||||
for modified in [None, Some(1_800_000_000)] {
|
||||
let mut o = opts(Standard::PdfX4, |_| {});
|
||||
o.modified = modified;
|
||||
let xmp = xmp_packet(&export(&d, &o).unwrap());
|
||||
let modify = xmp_value(&xmp, "xmp:ModifyDate").expect("xmp:ModifyDate");
|
||||
assert_eq!(xmp_value(&xmp, "xmp:MetadataDate"), Some(modify), "{modified:?}: {xmp}");
|
||||
assert_eq!(xmp.matches("<xmp:MetadataDate>").count(), 1, "{modified:?}");
|
||||
if modified.is_some() {
|
||||
assert!(modify.starts_with("2027-01-15T"), "the later date: {modify}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_standard_writes_its_header_output_intent_boxes_and_identification() {
|
||||
let mut d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::rgb(0.2, 0.4, 0.9)]);
|
||||
|
||||
@@ -637,6 +637,91 @@ fn cmyk_and_a_spot_separate_into_five_plates() {
|
||||
assert_eq!(inks(&p[2]), [0.0, 40.0], "the gold's yellow");
|
||||
}
|
||||
|
||||
/// A CMYK document with spot swatches Gold and Pine, and three 50 pt squares left to right: Gold
|
||||
/// at 50%, Pine at 100% and Registration.
|
||||
fn gold_and_pine() -> Document {
|
||||
let mut d = doc(200.0, 100.0, &[]);
|
||||
d.color_mode = vectorcraft_doc::ColorMode::Cmyk;
|
||||
d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
|
||||
d.swatches.push(Swatch { name: "Pine".into(), paint: Paint::solid(Color::cmyk(0.8, 0.0, 0.3, 0.0)), global: true, spot: true });
|
||||
let layer = d.default_layer().unwrap();
|
||||
let linked = |color: Color, swatch: &str, tint: f32| Paint::Solid { color, swatch: Some(swatch.into()), tint };
|
||||
let squares = [
|
||||
(0.0, linked(Color::cmyk(0.0, 0.1, 0.4, 0.05), "Gold", 0.5)),
|
||||
(60.0, linked(Color::cmyk(0.8, 0.0, 0.3, 0.0), "Pine", 1.0)),
|
||||
(120.0, linked(Color::cmyk(1.0, 1.0, 1.0, 1.0), vectorcraft_color::swatch::REGISTRATION, 1.0)),
|
||||
];
|
||||
for (x, p) in squares {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::basic(p, Paint::None, 0.0)))
|
||||
.unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The ink of each 50 pt square on a plate, left to right, in percent.
|
||||
fn square_inks(page: &Page) -> Vec<f32> {
|
||||
page.1
|
||||
.iter()
|
||||
.filter(|(b, _)| (b.width() - 50.0).abs() < 1.0 && (b.height() - 50.0).abs() < 1.0)
|
||||
.map(|(_, p)| match p.color() {
|
||||
Some(Color::Gray { k }) => (k * 100.0).round(),
|
||||
c => panic!("{c:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_spot_ink_converts_to_process_and_the_others_keep_their_plates() {
|
||||
let d = gold_and_pine();
|
||||
// Gold prints as process even with its plate turned off: converting is not leaving it out.
|
||||
let set = json!({"output": {"mode": "separations", "inks": [{"name": "Gold", "convertToProcess": true, "print": false, "frequency": 100}]}});
|
||||
let pv = preview(&d, &settings(set.clone())).unwrap();
|
||||
assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black", "Pine"]);
|
||||
let all: Vec<(&str, bool)> = pv.document_inks.iter().map(|i| (i.name.as_str(), i.convert_to_process)).collect();
|
||||
assert_eq!(all, [("Cyan", false), ("Magenta", false), ("Yellow", false), ("Black", false), ("Gold", true), ("Pine", false)]);
|
||||
let gold = &pv.document_inks[4];
|
||||
assert_eq!((gold.print, gold.frequency), (false, 100.0), "its plate options are kept");
|
||||
assert!(pv.setting_notes.iter().all(|n| !n.contains("no ink named") && !n.contains("only spot inks")), "{:?}", pv.setting_notes);
|
||||
let p = pages(&job(&d, set).bytes);
|
||||
assert_eq!(p.len(), 5);
|
||||
// (Gold, Pine, Registration) on Cyan, Magenta, Yellow, Black and Pine.
|
||||
assert_eq!(
|
||||
p.iter().map(square_inks).collect::<Vec<_>>(),
|
||||
[[0.0, 0.0, 100.0], [10.0, 0.0, 100.0], [40.0, 0.0, 100.0], [5.0, 0.0, 100.0], [0.0, 100.0, 100.0]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice() {
|
||||
let d = gold_and_pine();
|
||||
let inks = json!([{"name": "Gold", "convertToProcess": false, "angle": 30}, {"name": "Pine", "convertToProcess": true}]);
|
||||
let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "spotsToProcess": true, "inks": inks}}))).unwrap();
|
||||
assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black"]);
|
||||
let spots: Vec<(&str, bool, f64)> = pv.document_inks[4..].iter().map(|i| (i.name.as_str(), i.convert_to_process, i.angle)).collect();
|
||||
assert_eq!(spots, [("Gold", true, 30.0), ("Pine", true, 45.0)]);
|
||||
// The options of the converted inks still name inks of the document.
|
||||
assert!(pv.setting_notes.iter().all(|n| !n.contains("no ink named")), "{:?}", pv.setting_notes);
|
||||
// Without the option, each ink's own choice applies again.
|
||||
let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "inks": inks}}))).unwrap();
|
||||
assert_eq!(pv.inks.iter().map(|i| i.name.as_str()).collect::<Vec<_>>(), ["Cyan", "Magenta", "Yellow", "Black", "Gold"]);
|
||||
// A process ink doesn't convert: it keeps its plate, and a note says so.
|
||||
let pv = preview(&d, &settings(json!({"output": {"mode": "separations", "inks": [{"name": "Cyan", "convertToProcess": true}]}}))).unwrap();
|
||||
assert_eq!(pv.inks.len(), 6);
|
||||
assert!(pv.document_inks.iter().all(|i| !i.convert_to_process));
|
||||
assert_eq!(pv.setting_notes, ["`Cyan` print as process inks already: only spot inks convert to process"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ink_option_without_convert_to_process_keeps_its_spot_plate() {
|
||||
let set = settings(json!({"output": {"inks": [{"name": "Gold", "angle": 30}]}}));
|
||||
assert!(!set.output.inks[0].convert_to_process);
|
||||
let back = serde_json::to_value(&set.output.inks[0]).unwrap();
|
||||
assert_eq!(back, json!({"name": "Gold", "print": true, "angle": 30.0}), "off is not written");
|
||||
let on = InkSettings { convert_to_process: true, ..set.output.inks[0].clone() };
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["convertToProcess"], json!(true));
|
||||
}
|
||||
|
||||
/// A 200 × 100 pt CMYK document filled with cyan, with spot swatch `Ink` (100% K) and the objects
|
||||
/// `art` over the cyan.
|
||||
fn over_cyan(art: Vec<Node>) -> Document {
|
||||
@@ -747,7 +832,7 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p
|
||||
#[test]
|
||||
fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() {
|
||||
// 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript
|
||||
// plate draws it as nothing (it has no blending modes).
|
||||
// plate (it has no blending modes) draws it as nothing, since the color counts as black.
|
||||
let mut square = Node::path(
|
||||
vectorcraft_doc::NodeId(0),
|
||||
shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)),
|
||||
@@ -767,6 +852,79 @@ fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() {
|
||||
assert_eq!((fills(false), fills(true)), (2, 1), "the cyan plate as PDF, as PostScript");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() {
|
||||
// 0.4% cyan in a color that is not black, set to overprint, on a fill, a stroke, a character
|
||||
// fill, a linear gradient's stop and a freeform gradient's point: the cyan plate draws it on
|
||||
// PDF and PostScript plates alike. A magenta with no cyan at all draws as nothing.
|
||||
let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0);
|
||||
let magenta = Color::cmyk(0.0, 0.5, 0.0, 0.0);
|
||||
let square = |x: f64, fill: Paint, stroke: Paint| {
|
||||
let mut n =
|
||||
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0));
|
||||
if let Some(f) = n.appearance.fill_mut() {
|
||||
f.overprint = true;
|
||||
}
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.overprint = true;
|
||||
}
|
||||
n
|
||||
};
|
||||
let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, faint), GradientStop::new(1.0, magenta)]));
|
||||
let mut freeform =
|
||||
GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, magenta), GradientStop::new(1.0, magenta)]));
|
||||
let points = vec![FreeformPoint::new(kurbo::Point::new(105.0, 20.0), magenta), FreeformPoint::new(kurbo::Point::new(115.0, 30.0), faint)];
|
||||
freeform.freeform = Some(Freeform { points, ..Default::default() });
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(faint), overprint_fill: true, ..Default::default() };
|
||||
let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style);
|
||||
let d = over_cyan(vec![
|
||||
square(10.0, Paint::solid(faint), Paint::None),
|
||||
square(40.0, Paint::None, Paint::solid(faint)),
|
||||
square(70.0, Paint::Gradient(Box::new(linear)), Paint::None),
|
||||
square(100.0, Paint::Gradient(Box::new(freeform)), Paint::None),
|
||||
square(130.0, Paint::solid(magenta), Paint::None),
|
||||
Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))),
|
||||
// A black linked to the spot swatch at a 0.4% tint: 0.4% on the spot plate, none on the cyan.
|
||||
square(160.0, Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 0.004 }, Paint::None),
|
||||
]);
|
||||
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript: true, ..Default::default() };
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let mut spot = vec![];
|
||||
p.plates[4].walk(|n| {
|
||||
spot.extend(n.appearance.fill().and_then(|f| f.paint.color()).map(|c| match c {
|
||||
Color::Gray { k } => (k * 1000.0).round(),
|
||||
c => panic!("{c:?}"),
|
||||
}))
|
||||
});
|
||||
assert!(spot.contains(&4.0), "the PostScript spot plate draws the spot tint: {spot:?}");
|
||||
// The fills, strokes and character fills the cyan plate draws, and the gray of the solid fills.
|
||||
let drawn = |postscript: bool| {
|
||||
let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() };
|
||||
let p = plan(&d, &opts).unwrap();
|
||||
let (mut fills, mut strokes, mut chars, mut grays) = (0, 0, 0, vec![]);
|
||||
p.plates[0].walk(|n| {
|
||||
if let Some(f) = n.appearance.fill().filter(|f| !f.paint.is_none()) {
|
||||
fills += 1;
|
||||
if let Some(Color::Gray { k }) = f.paint.color() {
|
||||
grays.push((k * 1000.0).round());
|
||||
}
|
||||
}
|
||||
strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none()));
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count();
|
||||
}
|
||||
});
|
||||
(fills, strokes, chars, grays)
|
||||
};
|
||||
for postscript in [false, true] {
|
||||
let (fills, strokes, chars, grays) = drawn(postscript);
|
||||
let at = if postscript { "PostScript" } else { "PDF" };
|
||||
assert_eq!((strokes, chars), (1, 1), "{at}: the stroke and the character fill");
|
||||
assert_eq!(fills, 4, "{at}: the cyan, the faint fill and both gradients, not the magenta");
|
||||
assert_eq!(grays, [1000.0, 4.0], "{at}: the cyan and the faint fill's 0.4%");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprinting_type_leaves_the_inks_below_on_separations() {
|
||||
let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() };
|
||||
@@ -915,6 +1073,8 @@ fn a_spot_gradient_stop_prints_its_process_plates() {
|
||||
assert_eq!(first(json!({"output": {"mode": "separations"}})), [25.0, 0.0, 40.0, 0.0, 50.0], "Cyan, Magenta, Yellow, Black, Gold");
|
||||
// Spots as process: the plates layered with the gold tint's process inks (0, 10, 40, 5).
|
||||
assert_eq!(first(json!({"output": {"mode": "separations", "spotsToProcess": true}})), [25.0, 10.0, 64.0, 5.0]);
|
||||
// Gold converted on its own: the same.
|
||||
assert_eq!(first(json!({"output": {"mode": "separations", "inks": [{"name": "Gold", "convertToProcess": true}]}})), [25.0, 10.0, 64.0, 5.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -81,8 +81,13 @@ fn form_resource_scopes_keep_scanned_overprint_in_step_with_interpretation() {
|
||||
}
|
||||
|
||||
pub(crate) fn text_pdf(content: &str) -> Vec<u8> {
|
||||
text_pdf_with("/ca 0.25 /CA 0.75", content)
|
||||
}
|
||||
|
||||
/// [`text_pdf`] with graphics state `/G` set by `state` (its entries, such as `/ca 0.5 /CA 0.5`).
|
||||
pub(crate) fn text_pdf_with(state: &str, content: &str) -> Vec<u8> {
|
||||
page(
|
||||
"/Font << /F1 5 0 R >> /ExtGState << /G << /ca 0.25 /CA 0.75 >> >>",
|
||||
&format!("/Font << /F1 5 0 R >> /ExtGState << /G << {state} >> >>"),
|
||||
content.as_bytes(),
|
||||
&[
|
||||
b"<< /Type /Font /Subtype /TrueType /BaseFont /Inter-Regular /Encoding /WinAnsiEncoding /FirstChar 65 /LastChar 67 /Widths [600 600 600] /FontDescriptor 6 0 R >>".to_vec(),
|
||||
|
||||
@@ -38,6 +38,11 @@ fn page(drawn: &[char], sign_width: Option<f64>) -> Vec<u8> {
|
||||
/// graphics state, to set between glyphs or before them, with `objects` it refers to (the first
|
||||
/// is object `first_extra(1) + 4`).
|
||||
fn page_with(ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objects: &[String], sign_width: Option<f64>) -> Vec<u8> {
|
||||
page_in("Identity-H", ops, extra, objects, sign_width)
|
||||
}
|
||||
|
||||
/// [`page_with`] with the Type 0 font's encoding `encoding` (`Identity-V`: vertical writing).
|
||||
fn page_in(encoding: &str, ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objects: &[String], sign_width: Option<f64>) -> Vec<u8> {
|
||||
FontDb::global().add_font(matra_font().expect("the test font builds"));
|
||||
let program = matra_font().unwrap();
|
||||
let hex: String = program.iter().map(|b| format!("{b:02X}")).collect::<String>() + ">";
|
||||
@@ -66,7 +71,7 @@ fn page_with(ops: impl Fn(&dyn Fn(char) -> String) -> String, extra: &str, objec
|
||||
];
|
||||
let refs: Vec<&str> = objs.iter().chain(objects).map(String::as_str).collect();
|
||||
let resources = format!(
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /Identity-H /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >> {extra}",
|
||||
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /MatratestSans-Regular /Encoding /{encoding} /DescendantFonts [{} 0 R] /ToUnicode {} 0 R >> >> {extra}",
|
||||
n + 2,
|
||||
n + 3
|
||||
);
|
||||
@@ -218,3 +223,22 @@ fn outlined_glyphs_under_a_varying_soft_mask_are_masked_one_by_one() {
|
||||
assert_eq!(outlines(&report.document), 3, "a path each");
|
||||
assert_eq!(masked_outlines(&report.document), 3, "each path has its own mask");
|
||||
}
|
||||
|
||||
/// A vertical line (upright glyphs) with one glyph filled and stroked: its glyphs aren't kept as
|
||||
/// outlines, so it can't come in as the outlines of that glyph alone, losing the glyph filled
|
||||
/// only. Every glyph comes in filled (#8015).
|
||||
#[test]
|
||||
fn a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled() {
|
||||
let bytes = page_in("Identity-V", |id| format!("1 0 0 rg 0 0 1 RG 2 w {} Tj 2 Tr {} Tj 0 Tr", id(KA), id(SIGN_I)), "", &[], None);
|
||||
let report = open(&bytes);
|
||||
let mut runs = vec![];
|
||||
report.document.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
runs.extend(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), !r.style.stroke.is_none())));
|
||||
}
|
||||
});
|
||||
let filled: String = runs.iter().filter(|r| r.1).map(|r| r.0.as_str()).collect();
|
||||
assert_eq!(filled, format!("{KA}{SIGN_I}"), "every glyph filled: {runs:?}");
|
||||
let stroked: String = runs.iter().filter(|r| r.2).map(|r| r.0.as_str()).collect();
|
||||
assert_eq!(stroked, SIGN_I.to_string(), "{runs:?}");
|
||||
}
|
||||
@@ -758,3 +758,19 @@ fn perf_text_heavy_open() {
|
||||
println!("4000 lines: {n} text objects in {took:?} (as outlines: {:?})", start.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertical type filled, then stroked (fill and stroke rendering draws a whole operator's glyphs
|
||||
/// filled before it strokes them): one column, each glyph filled and stroked (#8015).
|
||||
#[test]
|
||||
fn a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type() {
|
||||
for mode in ["2", "6"] {
|
||||
let content = format!("0 0 1 RG 1 0 0 rg 2 w BT {mode} Tr /F6 24 Tf 150 180 Td {} Tj 0 Tr ET", gids("§±×"));
|
||||
let t = texts(&open_as(&page(&content, ""), TextAs::Text));
|
||||
assert_eq!(t.len(), 1, "{content}: {t:#?}");
|
||||
assert_eq!(t[0].plain_text(), "§±×");
|
||||
for r in &t[0].runs {
|
||||
assert!(!r.style.fill.is_none() && !r.style.stroke.is_none(), "{content}: {:?}", t[0].runs);
|
||||
assert!((r.style.stroke_width - 2.0).abs() < 1e-6, "{content}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,3 +122,227 @@ fn imported_stroked_type_keeps_the_files_cap_join_and_miter_limit() {
|
||||
assert_eq!(joins, [Some(LineJoin::Round), Some(LineJoin::Miter)], "{content}: {runs:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill and stroke rendering (mode 2, or 6 with a clip) draws a text-showing operator's glyphs
|
||||
/// filled, then the same glyphs stroked: the type comes in once, filled and stroked, whether the
|
||||
/// operator shows one glyph or a word, or a TJ array of strings with kerning between them, in an
|
||||
/// outline font, with or without replacement text (`ActualText`). Stroke rendering (modes 1 and 5) stays stroke only. A Type 3 glyph is filled in
|
||||
/// every one of those modes, once (#8015).
|
||||
#[test]
|
||||
fn a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
|
||||
// `/T3`: a Type 3 font whose glyphs take the text's paint (`d1`), `W A V E` mapped by ToUnicode.
|
||||
let t3 = first_extra(1);
|
||||
let glyph = crate::tests_import_fidelity::stream("", "600 0 0 0 600 700 d1 0 0 m 600 0 l 300 700 l h f");
|
||||
let to_unicode = crate::tests_import_fidelity::stream(
|
||||
"",
|
||||
"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /T3-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 4 beginbfchar\n<41> <0041>\n<45> <0045>\n<56> <0056>\n<57> <0057>\nendbfchar endcmap CMapName currentdict /CMap defineresource pop end end",
|
||||
);
|
||||
let font = format!(
|
||||
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 600 700] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /g {} 0 R >> /Encoding << /Type /Encoding /Differences [65 /g 69 /g 86 /g 87 /g] >> /FirstChar 65 /LastChar 87 /Widths [600 0 0 0 600 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 600 600] /ToUnicode {} 0 R /Resources << >> >>",
|
||||
t3 + 1,
|
||||
t3 + 2
|
||||
);
|
||||
let page = |content: &str| {
|
||||
let resources = format!("/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> /T3 {t3} 0 R >>");
|
||||
pdf_with(&[PdfPage { resources, ..PdfPage::new(300.0, 200.0, content) }], &[&font, &glyph, &to_unicode], None)
|
||||
};
|
||||
let objects = |content: &str| {
|
||||
let d = import(&page(content)).unwrap();
|
||||
let mut types = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
types.push((**t).clone());
|
||||
}
|
||||
});
|
||||
types
|
||||
};
|
||||
let cream = Paint::solid(Color::rgb8(0xff, 0xff, 0xcc));
|
||||
let black = Paint::solid(Color::BLACK);
|
||||
let shows =
|
||||
["(WAVE) Tj", "[(WA) -50 (VE)] TJ", "(WA) Tj (VE) Tj", "(W) Tj (A) Tj (V) Tj (E) Tj", "/Span << /ActualText (WAVE) >> BDC (WAVE) Tj EMC"];
|
||||
for font in ["F1", "T3"] {
|
||||
for show in shows {
|
||||
for mode in ["0", "1", "2", "4", "5", "6"] {
|
||||
let content = format!("0 0 0 RG 1 1 0.8 rg 3 w 1 J 1 j BT {mode} Tr /{font} 60 Tf 40 110 Td {show} 0 Tr ET");
|
||||
let types = objects(&content);
|
||||
assert_eq!(types.len(), 1, "{content}: one type object: {types:#?}");
|
||||
let t = &types[0];
|
||||
assert_eq!(t.plain_text(), "WAVE", "{content}");
|
||||
// A Type 3 glyph paints itself: the reader fills it whatever the mode.
|
||||
let (fill, stroke) = match mode {
|
||||
_ if font == "T3" => (true, false),
|
||||
"0" | "4" => (true, false),
|
||||
"1" | "5" => (false, true),
|
||||
_ => (true, true),
|
||||
};
|
||||
for r in &t.runs {
|
||||
let s = &r.style;
|
||||
assert_eq!(s.fill, if fill { cream.clone() } else { Paint::None }, "{content}: fill: {:?}", t.runs);
|
||||
if stroke {
|
||||
assert_eq!(s.stroke, black, "{content}: stroke: {:?}", t.runs);
|
||||
assert!((s.stroke_width - 3.0).abs() < 1e-6, "{content}: width {}", s.stroke_width);
|
||||
assert_eq!((s.stroke_cap, s.stroke_join), (LineCap::Round, LineJoin::Round), "{content}");
|
||||
} else {
|
||||
assert!(s.stroke.is_none(), "{content}: no stroke: {:?}", t.runs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A word filled, then stroked with another join part way through (one operator each):
|
||||
// each part keeps its own join, all of it filled.
|
||||
let content = "0 0 0 RG 1 1 0.8 rg 3 w BT 2 Tr /F1 60 Tf 40 110 Td 1 j (WA) Tj 0 j (VE) Tj 0 Tr ET";
|
||||
let types = objects(content);
|
||||
assert_eq!(types.len(), 1, "{content}: {types:#?}");
|
||||
let joins: Vec<_> = types[0].runs.iter().map(|r| (r.text.as_str(), r.style.fill == cream, r.style.stroke_join)).collect();
|
||||
assert_eq!(joins, [("WA", true, LineJoin::Round), ("VE", true, LineJoin::Miter)], "{content}");
|
||||
// Filled type, then stroked type of its own elsewhere: a stroke over no filled glyph.
|
||||
let content = "0 0 0 RG 1 1 0.8 rg 3 w BT 0 Tr /F1 60 Tf 40 110 Td (WAVE) Tj 1 Tr 0 -70 Td (WAVE) Tj 0 Tr ET";
|
||||
let types = objects(content);
|
||||
assert_eq!(types.len(), 2, "{content}: {types:#?}");
|
||||
let looks: Vec<_> = types.iter().flat_map(|t| &t.runs).map(|r| (r.style.fill == cream, !r.style.stroke.is_none())).collect();
|
||||
assert_eq!(looks, [(true, false), (false, true)], "{content}");
|
||||
}
|
||||
|
||||
/// Helvetica PDF page drawing `content`, imported: each run of type as its text, size, and
|
||||
/// whether it is filled and stroked, in text order.
|
||||
fn word_runs(content: &str) -> Vec<(String, f64, bool, bool)> {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>";
|
||||
let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None);
|
||||
let d = import(&bytes).unwrap();
|
||||
let mut runs = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
runs.extend(t.runs.iter().map(|r| (r.text.clone(), r.style.size, !r.style.fill.is_none(), !r.style.stroke.is_none())));
|
||||
}
|
||||
});
|
||||
runs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
|
||||
runs
|
||||
}
|
||||
|
||||
/// A stroke goes only over a glyph filled with the very same placement: a word filled, then its
|
||||
/// first glyph stroked at another size from the same origin, is two pieces of type, the word
|
||||
/// unstroked and the glyph at its own size (#8015).
|
||||
#[test]
|
||||
fn a_stroke_at_another_size_does_not_go_over_the_filled_glyph() {
|
||||
for mode in ["1", "2"] {
|
||||
let content = format!("0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT {mode} Tr /F1 30 Tf 40 110 Td (W) Tj 0 Tr ET");
|
||||
let filled = mode == "2";
|
||||
assert_eq!(word_runs(&content), [("W".to_string(), 30.0, filled, true), ("WAVE".to_string(), 60.0, true, false)], "{content}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke over one glyph of a filled word strokes that glyph alone, not the rest of the word
|
||||
/// (#8015).
|
||||
#[test]
|
||||
fn a_stroke_over_one_glyph_of_a_filled_word_strokes_only_that_glyph() {
|
||||
// W alone stroked at the same size from the same origin: W is stroked, AVE not.
|
||||
let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT 1 Tr /F1 60 Tf 40 110 Td (W) Tj 0 Tr ET";
|
||||
assert_eq!(word_runs(content), [("AVE".to_string(), 60.0, true, false), ("W".to_string(), 60.0, true, true)], "{content}");
|
||||
// Filled and stroked there instead: that W is drawn again, over the word, as type of its own.
|
||||
let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 40 110 Td (WAVE) Tj ET BT 2 Tr /F1 60 Tf 40 110 Td (W) Tj 0 Tr ET";
|
||||
assert_eq!(word_runs(content), [("W".to_string(), 60.0, true, true), ("WAVE".to_string(), 60.0, true, false)], "{content}");
|
||||
}
|
||||
|
||||
/// A glyph filled at one opacity and stroked at another (`ca` and `CA` differ) stays two pieces
|
||||
/// of type, each at its own opacity, also when it is shown on its own, so the stroke is drawn
|
||||
/// right after its fill (#8015). Two such operators are four pieces in the order they are drawn,
|
||||
/// the second glyph's fill over the first one's stroke.
|
||||
#[test]
|
||||
fn a_glyph_stroked_at_another_opacity_than_its_fill_stays_its_own_type() {
|
||||
let (fill, stroke) = ((64.0 / 255.0, true, false), (191.0 / 255.0, false, true));
|
||||
for (show, want) in [("(A) Tj", vec![fill, stroke]), ("(A) Tj (B) Tj", vec![fill, stroke, fill, stroke])] {
|
||||
let content = format!("/G gs 1 0 0 rg 0 0 1 RG 2 w BT /F1 20 Tf 2 Tr 1 0 0 1 10 20 Tm {show} 0 Tr ET");
|
||||
let d = import(&crate::tests::reader_compat::text_pdf(&content)).unwrap();
|
||||
let mut texts = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let st = t.first_style();
|
||||
texts.push((n.opacity, !st.fill.is_none(), !st.stroke.is_none()));
|
||||
}
|
||||
});
|
||||
assert_eq!(texts, want, "{content}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Type filled and stroked at the same opacity below 1 stays a filled object and a stroked one:
|
||||
/// the file composites the fill and the stroke apiece (darker where they overlap), while an
|
||||
/// object's opacity applies to its fill and stroke together. Opaque, it is one object (#8015).
|
||||
#[test]
|
||||
fn translucent_fill_and_stroke_text_stays_two_objects() {
|
||||
let half = |fill, stroke| (128.0 / 255.0, fill, stroke);
|
||||
for show in ["(A) Tj", "(AB) Tj"] {
|
||||
let content = format!("/G gs 1 0 0 rg 0 0 1 RG 2 w BT /F1 20 Tf 2 Tr 1 0 0 1 10 20 Tm {show} 0 Tr ET");
|
||||
for (state, want) in [("/ca 0.5 /CA 0.5", vec![half(true, false), half(false, true)]), ("/ca 1 /CA 1", vec![(1.0, true, true)])] {
|
||||
let d = import(&crate::tests::reader_compat::text_pdf_with(state, &content)).unwrap();
|
||||
let mut texts = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let st = t.first_style();
|
||||
texts.push((n.opacity, !st.fill.is_none(), !st.stroke.is_none()));
|
||||
}
|
||||
});
|
||||
assert_eq!(texts, want, "{state}: {content}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke goes only over a glyph filled with the same text: "AB" filled, its "A" stroked, then
|
||||
/// an "X" stroked where the "B" stands is type of its own, and the "B" stays unstroked (#8015).
|
||||
#[test]
|
||||
fn a_stroke_of_another_glyph_where_one_was_filled_stays_its_own_type() {
|
||||
let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 60 Tf 1 0 0 1 40 110 Tm (AB) Tj 1 Tr 1 0 0 1 40 110 Tm (A) Tj (X) Tj 0 Tr ET";
|
||||
let want = [("A".to_string(), 60.0, true, true), ("B".to_string(), 60.0, true, false), ("X".to_string(), 60.0, false, true)];
|
||||
assert_eq!(word_runs(content), want, "{content}");
|
||||
}
|
||||
|
||||
/// Helvetica PDF page drawing `content` (fill cream, stroke black, 3 points wide), imported: each
|
||||
/// type object's runs in drawing order, as their text and whether they are filled and stroked.
|
||||
fn type_runs(content: &str) -> Vec<Vec<(String, bool, bool)>> {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>";
|
||||
let content = format!("0 0 0 RG 1 1 0.8 rg 3 w {content}");
|
||||
let bytes = pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, &content) }], None);
|
||||
let d = import(&bytes).unwrap();
|
||||
let mut types = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
types.push(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), !r.style.stroke.is_none())).collect());
|
||||
}
|
||||
});
|
||||
types
|
||||
}
|
||||
|
||||
/// A glyph filled only (mode 0) right after one filled and stroked (mode 2) is filled only: it
|
||||
/// joins the same type object, but not the stroked run, whether the glyphs before were filled
|
||||
/// only, filled and stroked, or both, and a glyph filled and stroked after it is stroked again
|
||||
/// (#8300).
|
||||
#[test]
|
||||
fn a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked() {
|
||||
let run = |text: &str, stroked: bool| (text.to_string(), true, stroked);
|
||||
let cases = [
|
||||
("2 Tr (B) Tj 0 Tr (C) Tj", vec![run("B", true), run("C", false)]),
|
||||
("0 Tr (A) Tj 2 Tr (B) Tj 0 Tr (C) Tj", vec![run("A", false), run("B", true), run("C", false)]),
|
||||
("2 Tr (B) Tj 0 Tr (C) Tj 2 Tr (D) Tj", vec![run("B", true), run("C", false), run("D", true)]),
|
||||
("2 Tr (AB) Tj 0 Tr (CD) Tj", vec![run("AB", true), run("CD", false)]),
|
||||
("0 Tr (A) Tj 2 Tr (BC) Tj", vec![run("A", false), run("BC", true)]),
|
||||
];
|
||||
for (show, want) in cases {
|
||||
let content = format!("BT /F1 48 Tf 20 80 Td {show} 0 Tr ET");
|
||||
assert_eq!(type_runs(&content), [want], "{content}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill and stroke rendering glyph by glyph, and a word filled whole then stroked whole at the
|
||||
/// same place, still come in as one run filled and stroked (#8300).
|
||||
#[test]
|
||||
fn glyphs_filled_and_stroked_one_by_one_stay_one_run() {
|
||||
for content in [
|
||||
"BT /F1 48 Tf 20 80 Td 2 Tr (A) Tj (B) Tj (C) Tj 0 Tr ET",
|
||||
"BT /F1 48 Tf 1 0 0 1 20 80 Tm 0 Tr (ABC) Tj 1 Tr 1 0 0 1 20 80 Tm (ABC) Tj 0 Tr ET",
|
||||
] {
|
||||
assert_eq!(type_runs(content), [vec![("ABC".to_string(), true, true)]], "{content}");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Raster export: render a document region with [`RasterExportOptions`] (resolution, background,
|
||||
//! anti-aliasing) and encode it as PNG ([`png`]: resolution in `pHYs`, Adam7 interlacing), JPEG
|
||||
//! ([`jpeg`]: RGB, CMYK or grey, progressive, resolution and colour profile), lossless WebP, or
|
||||
//! ([`jpeg`]: RGB, CMYK or grey, progressive, resolution and colour profile), lossless or lossy WebP, or
|
||||
//! a palette image ([`quantize`]) as PNG-8 or [`gif`], [`tiff`] (RGB, CMYK or grey, LZW, either byte
|
||||
//! order, the profile), [`bmp`] (1–32 bits, RLE) or [`tga`]; [`web`] adds what Save for Web optimises
|
||||
//! further (web snap, colour table edits, lossy GIF, comments); [`psd`] writes layered bitmaps.
|
||||
@@ -49,8 +49,10 @@ pub struct RasterExportOptions {
|
||||
pub anti_alias: AntiAlias,
|
||||
/// PNG, PNG-8: Adam7 interlacing; GIF: interlaced rows.
|
||||
pub interlaced: bool,
|
||||
/// JPEG quality 0–100.
|
||||
/// JPEG quality 0–100, and lossy WebP's.
|
||||
pub quality: u8,
|
||||
/// WebP: lossless (`true`), or lossy at [`Self::quality`].
|
||||
pub webp_lossless: bool,
|
||||
/// JPEG colour model, coding and profile.
|
||||
pub jpeg: jpeg::JpegOptions,
|
||||
/// PNG-8 and GIF: the colour reduction (also BMP's at 1, 4 and 8 bits).
|
||||
@@ -76,6 +78,7 @@ impl Default for RasterExportOptions {
|
||||
anti_alias: AntiAlias::Art,
|
||||
interlaced: false,
|
||||
quality: 90,
|
||||
webp_lossless: true,
|
||||
jpeg: jpeg::JpegOptions::default(),
|
||||
palette: quantize::PaletteOptions::default(),
|
||||
tiff: tiff::TiffOptions::default(),
|
||||
@@ -125,7 +128,7 @@ impl RasterExportOptions {
|
||||
};
|
||||
jpeg::encode(&px, img.width, img.height, self.quality, Some(self.ppi), &self.jpeg)
|
||||
}
|
||||
RasterFormat::WebP => webp(img),
|
||||
RasterFormat::WebP => webp(img, (!self.webp_lossless).then_some(self.quality)),
|
||||
RasterFormat::Png8 | RasterFormat::Gif => {
|
||||
let ix = quantize::quantize(&img.to_straight(), img.width, img.height, &self.palette);
|
||||
match format {
|
||||
@@ -184,8 +187,9 @@ pub fn on_white(p: &[u8; 4]) -> [u8; 3] {
|
||||
[0, 1, 2].map(|i| ((u32::from(p[i]) * a + 255 * (255 - a) + 127) / 255) as u8)
|
||||
}
|
||||
|
||||
/// Lossless WebP.
|
||||
pub(crate) fn webp(img: &Rendered) -> Result<Vec<u8>, String> {
|
||||
/// WebP: lossless (`VP8L`) when `lossy_quality` is `None`, else lossy (`VP8 `, with an `ALPH`
|
||||
/// chunk when some pixels are not opaque) at that quality 0–100.
|
||||
pub(crate) fn webp(img: &Rendered, lossy_quality: Option<u8>) -> Result<Vec<u8>, String> {
|
||||
let src = craft_image_codecs::Image::from_raw(
|
||||
img.width,
|
||||
img.height,
|
||||
@@ -194,8 +198,40 @@ pub(crate) fn webp(img: &Rendered) -> Result<Vec<u8>, String> {
|
||||
img.to_straight(),
|
||||
)
|
||||
.map_err(|e| format!("WebP encoding failed: {e}"))?;
|
||||
let opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..craft_image_codecs::EncodeOptions::default() };
|
||||
craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))
|
||||
let opts = craft_image_codecs::EncodeOptions {
|
||||
webp_lossless: lossy_quality.is_none(),
|
||||
webp_quality: lossy_quality.unwrap_or(100).min(100),
|
||||
..craft_image_codecs::EncodeOptions::default()
|
||||
};
|
||||
let file = craft_image_codecs::encode(&src, craft_image_codecs::Format::WebP, &opts).map_err(|e| format!("WebP encoding failed: {e}"))?;
|
||||
if lossy_quality.is_some() && vp8_partition_at_limit(&file) {
|
||||
return Err("WebP encoding failed: the image is too large for lossy WebP: lower the resolution or choose Lossless".into());
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// The largest first-partition size a VP8 key frame's 19-bit size field holds (RFC 6386 §9.1).
|
||||
const VP8_FIRST_PARTITION_LIMIT: u32 = (1 << 19) - 1;
|
||||
|
||||
/// Does the `VP8 ` chunk of RIFF WebP `file` give its first partition the size limit? The encoder
|
||||
/// writes the limit for a larger partition too, and a decoder then reads the token partition from
|
||||
/// the wrong offset, so a frame at the limit is not written.
|
||||
fn vp8_partition_at_limit(file: &[u8]) -> bool {
|
||||
let mut at = 12usize;
|
||||
while let Some(head) = file.get(at..).and_then(|rest| rest.get(..8)) {
|
||||
let len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]);
|
||||
if &head[..4] == b"VP8 " {
|
||||
return file.get(at + 8..).and_then(|rest| rest.get(..3)).is_some_and(|tag| {
|
||||
let tag = u32::from(tag[0]) | (u32::from(tag[1]) << 8) | (u32::from(tag[2]) << 16);
|
||||
tag >> 5 >= VP8_FIRST_PARTITION_LIMIT
|
||||
});
|
||||
}
|
||||
let Some(next) = usize::try_from(u64::from(len) + u64::from(len % 2) + 8).ok().and_then(|n| at.checked_add(n)) else {
|
||||
break;
|
||||
};
|
||||
at = next;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Bounds of the art an export draws: visible objects off template layers (guides left out),
|
||||
|
||||
@@ -202,6 +202,84 @@ fn backgrounds_are_opaque_or_transparent() {
|
||||
assert_eq!(webp.get_pixel(0, 0).0, [0, 0, 0, 255]);
|
||||
}
|
||||
|
||||
/// The chunk types of RIFF WebP file `file`, in order.
|
||||
fn webp_chunks(file: &[u8]) -> Vec<[u8; 4]> {
|
||||
assert_eq!((&file[..4], &file[8..12]), (&b"RIFF"[..], &b"WEBP"[..]));
|
||||
let mut chunks = Vec::new();
|
||||
let mut at = 12;
|
||||
while at + 8 <= file.len() {
|
||||
let len = u32::from_le_bytes([file[at + 4], file[at + 5], file[at + 6], file[at + 7]]) as usize;
|
||||
chunks.push([file[at], file[at + 1], file[at + 2], file[at + 3]]);
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
chunks
|
||||
}
|
||||
|
||||
/// Lossy WebP is a `VP8 ` picture; transparent pixels stay transparent through an `ALPH` chunk
|
||||
/// in a `VP8X` file, and opaque art stays opaque.
|
||||
#[test]
|
||||
fn lossy_webp_keeps_transparent_pixels_transparent() {
|
||||
let d = circle_doc();
|
||||
let lossless = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap();
|
||||
assert_eq!(webp_chunks(&lossless), [*b"VP8L"], "lossless by default");
|
||||
let o = RasterExportOptions { webp_lossless: false, quality: 75, ..Default::default() };
|
||||
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8X", *b"ALPH", *b"VP8 "]);
|
||||
let img = export(&d, RasterFormat::WebP, &o);
|
||||
assert_eq!(img.dimensions(), (40, 30));
|
||||
assert_eq!(img.get_pixel(0, 0)[3], 0, "a corner outside the circle");
|
||||
let middle = img.get_pixel(20, 15);
|
||||
assert!(middle[3] == 255 && middle[0] < 24, "{middle:?}");
|
||||
// Opaque art on a background is a plain `VP8 ` file.
|
||||
let opaque = RasterExportOptions { background: Some([255; 3]), ..o };
|
||||
let file = Renderer::new().export_region(&d, d.artboards[0].rect, RasterFormat::WebP, &opaque).unwrap();
|
||||
assert_eq!(webp_chunks(&file), [*b"VP8 "]);
|
||||
}
|
||||
|
||||
/// A lossy frame's tag (RFC 6386 §9.1) holds its first partition's size in 19 bits. A frame whose
|
||||
/// size field is at that limit may hold a larger partition, so it is refused; frames below it
|
||||
/// decode with another decoder at every quality, a 1 × 1 image and transparent pixels included.
|
||||
#[test]
|
||||
fn lossy_webp_refuses_a_first_partition_at_the_size_limit() {
|
||||
let circle = circle_doc();
|
||||
let dot = Document::new(1.0, 1.0);
|
||||
for (d, background) in [(&circle, None), (&circle, Some([255; 3])), (&dot, Some([40, 80, 120]))] {
|
||||
for quality in [0, 50, 100] {
|
||||
let o = RasterExportOptions { webp_lossless: false, quality, background, ..Default::default() };
|
||||
let mut file = Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::WebP, &o).unwrap();
|
||||
let decoded = image::load_from_memory_with_format(&file, image::ImageFormat::WebP).unwrap();
|
||||
let rect = d.artboards[0].rect;
|
||||
assert_eq!((decoded.width(), decoded.height()), (rect.width() as u32, rect.height() as u32), "quality {quality}");
|
||||
assert!(!vp8_partition_at_limit(&file), "quality {quality}");
|
||||
let vp8 = chunk_offset(&file, b"VP8 ") + 8;
|
||||
let tag = u32::from(file[vp8]) | (u32::from(file[vp8 + 1]) << 8) | (u32::from(file[vp8 + 2]) << 16);
|
||||
let len = u32::from_le_bytes(file[vp8 - 4..vp8].try_into().unwrap());
|
||||
assert_eq!((tag & 1, &file[vp8 + 3..vp8 + 6]), (0, &[0x9d, 0x01, 0x2a][..]), "a key frame with its start code");
|
||||
assert!((tag >> 5) + 10 <= len, "the first partition fits in the chunk");
|
||||
// The size field at its limit.
|
||||
let at_limit = (tag & 0x1f) | (VP8_FIRST_PARTITION_LIMIT << 5);
|
||||
file[vp8..vp8 + 3].copy_from_slice(&at_limit.to_le_bytes()[..3]);
|
||||
assert!(vp8_partition_at_limit(&file), "quality {quality}");
|
||||
}
|
||||
}
|
||||
let lossless = Renderer::new().export_region(&circle, circle.artboards[0].rect, RasterFormat::WebP, &RasterExportOptions::default()).unwrap();
|
||||
assert!(!vp8_partition_at_limit(&lossless));
|
||||
// Cut short or with a chunk length past the end, the scan stops without a frame.
|
||||
for bad in [&b"RIFF\0\0\0\0WEBP"[..], b"RIFF\0\0\0\0WEBPVP8 ", b"RIFF\0\0\0\0WEBPXXXX\xff\xff\xff\xffVP8 \x04\0\0\0\xff\xff\xff\0", b""] {
|
||||
assert!(!vp8_partition_at_limit(bad), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The offset of the first chunk of type `ty` in RIFF WebP `file`.
|
||||
fn chunk_offset(file: &[u8], ty: &[u8; 4]) -> usize {
|
||||
let mut at = 12;
|
||||
while &file[at..at + 4] != ty {
|
||||
let len = u32::from_le_bytes(file[at + 4..at + 8].try_into().unwrap()) as usize;
|
||||
at += 8 + len + len % 2;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// #787: translucent art over opaque art (or a background) stays exactly opaque, its anti-aliased
|
||||
/// edges too, so the file is written as RGB.
|
||||
#[test]
|
||||
|
||||
@@ -419,7 +419,7 @@ impl Rendered {
|
||||
}
|
||||
/// Encode as lossless WebP.
|
||||
pub fn to_webp(&self) -> Result<Vec<u8>, String> {
|
||||
encode::webp(self)
|
||||
encode::webp(self, None)
|
||||
}
|
||||
/// Straight-alpha RGBA at (x, y).
|
||||
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
|
||||
|
||||
@@ -454,18 +454,23 @@ fn check_spaced_harakat(db: &FontDb, family: &str) {
|
||||
}
|
||||
|
||||
/// Right to left, with harakat coloured apart, Optical kerning keeps the Tsume of each letter's
|
||||
/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it.
|
||||
/// cluster as it does in "HOH": the glyphs move as far with Optical kerning as without it. The test
|
||||
/// font leaves blank space beside both letters' ink, so its Tsume must move something; an installed
|
||||
/// face may not (#7821: Arial's initial beh and its fatha fill its cell), and there the Tsume takes
|
||||
/// nothing, with or without Optical kerning.
|
||||
#[test]
|
||||
fn optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(crate::test_fonts::lam_alef_font(b"rlig").unwrap()), 1);
|
||||
check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig"));
|
||||
check_optical_tsume(&db, crate::test_fonts::lam_alef_family(b"rlig"), true);
|
||||
if let Some(face) = arabic_face("optical_kerning_keeps_the_tsume_of_a_letter_with_coloured_harakat") {
|
||||
check_optical_tsume(FontDb::global(), &face.family);
|
||||
check_optical_tsume(FontDb::global(), &face.family, false);
|
||||
}
|
||||
}
|
||||
|
||||
fn check_optical_tsume(db: &FontDb, family: &str) {
|
||||
/// `strict`: every letter's cluster must leave blank space beside its ink, so its Tsume must move
|
||||
/// or narrow something.
|
||||
fn check_optical_tsume(db: &FontDb, family: &str, strict: bool) {
|
||||
const WORD: &str = "بَبَ"; // ب 0, fatha 2, ب 4, fatha 6
|
||||
let set = |optical: bool, letter: Option<usize>| {
|
||||
let mut t = text_with_harakat(WORD, family, Some(red()));
|
||||
@@ -479,11 +484,27 @@ fn check_optical_tsume(db: &FontDb, family: &str) {
|
||||
// Tsume of the line's first cluster only narrows its advance and moves no glyph.
|
||||
let xs = |t: &TextObject| layout(db, t).glyphs.iter().flat_map(|g| [g.xf.as_coeffs()[4], g.advance]).collect::<Vec<_>>();
|
||||
assert!(xs(&set(true, None)).iter().zip(xs(&set(false, None))).any(|(a, b)| (a - b).abs() > 1e-6), "{family}: Optical moves the pair");
|
||||
// The blank space Tsume shares out: between the letter's cluster's cell (from its glyphs'
|
||||
// shared origin, as long as their advances) and its glyphs' ink, on each side, without Tsume.
|
||||
let plain = layout(db, &set(false, None));
|
||||
let blank = |letter: usize| {
|
||||
let cluster: Vec<_> = plain.glyphs.iter().filter(|g| g.byte == letter).collect();
|
||||
let start = cluster.iter().map(|g| g.origin.x).fold(f64::INFINITY, f64::min);
|
||||
let end = start + cluster.iter().map(|g| g.advance).sum::<f64>();
|
||||
let ink = cluster.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| g.outline.bounding_box());
|
||||
let (lo, hi) = ink.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), b| (lo.min(b.x0), hi.max(b.x1)));
|
||||
(lo - start).clamp(0.0, end - start) + (end - hi).clamp(0.0, end - start)
|
||||
};
|
||||
// Each letter in turn: the first one's cluster ends the pair, the second one's starts it.
|
||||
for letter in [0, 4] {
|
||||
let moved = |optical: bool| xs(&set(optical, Some(letter))).iter().zip(xs(&set(optical, None))).map(|(a, b)| a - b).collect::<Vec<_>>();
|
||||
let (without, with_optical) = (moved(false), moved(true));
|
||||
assert!(without.iter().any(|m| m.abs() > 1e-3), "{family} {letter}: Tsume moves or narrows the glyphs: {without:?}");
|
||||
let blank = blank(letter);
|
||||
if strict || blank > 1e-6 {
|
||||
assert!(without.iter().any(|m| m.abs() > 1e-6), "{family} {letter}: Tsume moves or narrows the glyphs ({blank} blank): {without:?}");
|
||||
} else {
|
||||
assert!(without.iter().all(|m| m.abs() < 1e-6), "{family} {letter}: no blank space ({blank}), Tsume takes nothing: {without:?}");
|
||||
}
|
||||
assert!(
|
||||
without.len() == with_optical.len() && without.iter().zip(&with_optical).all(|(a, b)| (a - b).abs() < 1e-6),
|
||||
"{family} {letter}: {without:?} {with_optical:?}"
|
||||
|
||||
@@ -75,6 +75,7 @@ group = "Selection"
|
||||
shown_when = [
|
||||
"The Group Selection tool: each click selects the next enclosing group.",
|
||||
"Direct Selection with Alt held (Alt makes it Group Selection for the next click).",
|
||||
"Over a panel where a click or a drop adds something, such as the strip under the Gradient panel's ramp, where a click adds a stop, or the Layers panel's list while rows are Alt-dragged, where the drop adds copies (where the system has no copy cursor the app can show).",
|
||||
]
|
||||
hotspot = "The arrow's tip."
|
||||
look = "ArrowHollow with a plus badge."
|
||||
|
||||
@@ -607,7 +607,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> V
|
||||
let edge = cut_edge(img);
|
||||
let mut changed = false;
|
||||
let mut stack: Vec<(usize, usize)> = Vec::new();
|
||||
for i in 0..w * h {
|
||||
for (i, blend) in blended.iter_mut().enumerate() {
|
||||
let mine = q.labels[i];
|
||||
if mine == TRANSPARENT || !edge.get(i).copied().unwrap_or(false) {
|
||||
continue;
|
||||
@@ -630,7 +630,7 @@ pub(crate) fn settle_cut_edges(q: &mut Quantized, img: &Raster, gray: bool) -> V
|
||||
}
|
||||
}
|
||||
});
|
||||
blended[i] = !near.is_empty();
|
||||
*blend = !near.is_empty();
|
||||
if keep || near.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -236,6 +236,7 @@ impl VectorcraftApp {
|
||||
let ime_target = crate::ime::target(&mut self.session, ime_view);
|
||||
let ime_before = crate::ime::stamp(&mut self.session, ime_view);
|
||||
let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors);
|
||||
let spot_base = panels::color_guide::before_command(self);
|
||||
let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());
|
||||
let r = panels::actions::after_recorded_command(self, r);
|
||||
if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) {
|
||||
@@ -267,6 +268,8 @@ impl VectorcraftApp {
|
||||
{
|
||||
self.ui.status = w.to_string();
|
||||
}
|
||||
// A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link.
|
||||
panels::color_guide::after_command(self, id, ¶ms, v, spot_base);
|
||||
if id == "file.new" {
|
||||
self.ui.status.clear();
|
||||
// New Document's Pixel preview mode (Overprint Preview is the engine's).
|
||||
|
||||
+174
-25
@@ -82,10 +82,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.add_space(2.0);
|
||||
// With the macOS menu bar the menus are at the top of the screen instead.
|
||||
let menus_end = if app.services.native_menu.is_some() { ui.cursor().min.x } else { menus::menu_bar(app, ui) };
|
||||
// The right-side group fills the space after the menus from the right; when it runs
|
||||
// short, Discord goes first (it is also under Help), then Explore tutorials (also
|
||||
// Window › Learn), then the search icon (the palette stays under its shortcut), then
|
||||
// the workspace switcher narrows.
|
||||
// The right-side group fills the space after the menus from the right, in the order
|
||||
// [`fit_right_group`] gives.
|
||||
let full = ui.max_rect();
|
||||
let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() };
|
||||
let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom()));
|
||||
@@ -97,21 +95,22 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let text = ui.painter().layout_no_wrap(label.text().to_string(), egui::FontId::proportional(12.0), t.warning);
|
||||
text.size().x + 2.0 * ui.spacing().button_padding.x + 8.0 + ui.spacing().item_spacing.x
|
||||
});
|
||||
let room = (right.width() - safe_w).max(0.0);
|
||||
let switcher = safe.is_none() || room >= 64.0 + 8.0;
|
||||
// Built-in workspace names translate; the user's own stay as typed.
|
||||
let ws_name =
|
||||
if crate::workspaces::is_builtin(&app.ui.workspace) { tl!(&app.ui.workspace).to_string() } else { app.ui.workspace.clone() };
|
||||
let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text);
|
||||
let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0);
|
||||
let gap = ui.spacing().item_spacing.x;
|
||||
// The search icon, as in PhotoCraft: shown while a minimal switcher fits beside it.
|
||||
let icon = 28.0;
|
||||
let search = switcher && room >= 64.0 + 8.0 + gap + icon;
|
||||
let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0);
|
||||
// Explore tutorials, beside the search icon, opens the Learn panel.
|
||||
let learn = search && room >= ws_w + 8.0 + 2.0 * (gap + icon);
|
||||
let discord = learn && room >= ws_w + 8.0 + 2.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false);
|
||||
let shortcut = menus::shortcut_of("help.commandPalette").map(menus::shown_shortcut);
|
||||
let field = SearchField::new(ui, &t, shortcut);
|
||||
let fit = fit_right_group(&RightWidths {
|
||||
room: (right.width() - safe_w).max(0.0),
|
||||
safe_mode: safe.is_some(),
|
||||
switcher: (ws.size().x + 36.0).clamp(112.0, 190.0),
|
||||
field: field.width,
|
||||
icon: BAR_ICON,
|
||||
gap: ui.spacing().item_spacing.x,
|
||||
community: crate::community::discord_width(ui, false),
|
||||
});
|
||||
let (switcher, ws_w, learn, discord) = (fit.switcher, fit.switcher_w, fit.learn, fit.community);
|
||||
let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
let ui = &mut rui;
|
||||
// Workspace switcher: shows the current workspace, opens Window → Workspace.
|
||||
@@ -131,19 +130,33 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
// Search → command palette (its shortcut opens it too).
|
||||
if search {
|
||||
let tip = match menus::shortcut_of("help.commandPalette") {
|
||||
Some(sc) => format!("{} ({})", tl!("Search commands, tools, panels and effects"), menus::shown_shortcut(sc)),
|
||||
None => tl!("Search commands, tools, panels and effects").to_string(),
|
||||
};
|
||||
if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() {
|
||||
app.ui.palette_open = !app.ui.palette_open;
|
||||
app.ui.palette_query.clear();
|
||||
}
|
||||
let with_shortcut = |text: &str| match &field.shortcut {
|
||||
Some(sc) => format!("{text} ({sc})"),
|
||||
None => text.to_string(),
|
||||
};
|
||||
let tip = with_shortcut(tl!("Search commands, tools, panels and effects"));
|
||||
let name = with_shortcut(tl!("Search commands"));
|
||||
// The field and the icon toggle the palette as its shortcut does, and like the shortcut
|
||||
// they do nothing while a dialog is open, so they are drawn disabled then.
|
||||
let enabled = app.ui.dialog.is_none();
|
||||
let open = app.ui.palette_open;
|
||||
let clicked = ui
|
||||
.add_enabled_ui(enabled, |ui| match fit.search {
|
||||
Search::Field => field.show(ui, &t, &name, &tip, open).clicked(),
|
||||
Search::Icon => {
|
||||
let (_, resp) = ui.allocate_exact_size(vec2(BAR_ICON, BAR_ICON), Sense::click());
|
||||
widgets::paint_icon_button_named(ui, resp, "search", &name, &tip, open).clicked()
|
||||
}
|
||||
Search::Hidden => false,
|
||||
})
|
||||
.inner;
|
||||
if clicked && enabled {
|
||||
app.ui.palette_open = !app.ui.palette_open;
|
||||
app.ui.palette_query.clear();
|
||||
}
|
||||
if learn {
|
||||
let shown = crate::panels::learn::visible(&app.ui);
|
||||
if widgets::icon_button(ui, "graduation-cap", tl!("Explore tutorials"), shown, icon).clicked()
|
||||
if widgets::icon_button(ui, "graduation-cap", tl!("Explore tutorials"), shown, BAR_ICON).clicked()
|
||||
&& let Err(e) = app.run("window.learn", json!({}))
|
||||
{
|
||||
app.ui.status = e;
|
||||
@@ -168,6 +181,142 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of the app bar's square icon buttons (the search icon, Explore tutorials).
|
||||
const BAR_ICON: f32 = 28.0;
|
||||
/// The narrowest the workspace switcher gets.
|
||||
const MIN_SWITCHER: f32 = 64.0;
|
||||
|
||||
/// How the app bar shows the search that opens the command palette.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Search {
|
||||
/// A field with the magnifier, "Search commands" and the palette's shortcut.
|
||||
Field,
|
||||
/// The magnifier alone.
|
||||
Icon,
|
||||
/// Not in the bar; the palette stays under its shortcut and Help › Search Commands….
|
||||
Hidden,
|
||||
}
|
||||
|
||||
/// The widths [`fit_right_group`] fits into `room`, in points.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RightWidths {
|
||||
/// The room after the menus, less the Safe Mode label's.
|
||||
room: f32,
|
||||
/// Whether the bar shows the Safe Mode label.
|
||||
safe_mode: bool,
|
||||
/// The workspace switcher's full width.
|
||||
switcher: f32,
|
||||
/// The search field's width.
|
||||
field: f32,
|
||||
/// The side of a square icon button.
|
||||
icon: f32,
|
||||
/// The space between two controls.
|
||||
gap: f32,
|
||||
/// The community button's width.
|
||||
community: f32,
|
||||
}
|
||||
|
||||
/// What the right-hand group of the app bar shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct RightGroup {
|
||||
/// Whether the workspace switcher shows.
|
||||
switcher: bool,
|
||||
/// The workspace switcher's width.
|
||||
switcher_w: f32,
|
||||
/// How the search shows.
|
||||
search: Search,
|
||||
/// Whether Explore tutorials shows.
|
||||
learn: bool,
|
||||
/// Whether the community button shows.
|
||||
community: bool,
|
||||
}
|
||||
|
||||
/// The right-hand group for the room it has. As the room runs short, the community button goes first
|
||||
/// (it is also under Help), then Explore tutorials (also Window › Learn), then the search field becomes the
|
||||
/// search icon, then the workspace switcher narrows to [`MIN_SWITCHER`], then the icon goes. In Safe
|
||||
/// Mode the label's width is taken first, and the switcher (also under Window › Workspace) goes when
|
||||
/// a minimal one does not fit.
|
||||
fn fit_right_group(w: &RightWidths) -> RightGroup {
|
||||
let room = w.room;
|
||||
let switcher = !w.safe_mode || room >= MIN_SWITCHER + 8.0;
|
||||
let icon = switcher && room >= MIN_SWITCHER + 8.0 + w.gap + w.icon;
|
||||
let field = icon && room >= w.switcher + 8.0 + w.gap + w.field;
|
||||
let search = if field {
|
||||
Search::Field
|
||||
} else if icon {
|
||||
Search::Icon
|
||||
} else {
|
||||
Search::Hidden
|
||||
};
|
||||
let search_w = match search {
|
||||
Search::Field => w.gap + w.field,
|
||||
Search::Icon => w.gap + w.icon,
|
||||
Search::Hidden => 0.0,
|
||||
};
|
||||
let switcher_w = w.switcher.min(room - 8.0 - search_w).max(MIN_SWITCHER);
|
||||
let learn_end = switcher_w + 8.0 + search_w + w.gap + w.icon;
|
||||
let learn = field && room >= learn_end;
|
||||
let community = learn && room >= learn_end + 10.0 + w.gap + w.community;
|
||||
RightGroup { switcher, switcher_w, search, learn, community }
|
||||
}
|
||||
|
||||
/// The app bar's search field: a button drawn as a field. The command palette's popup holds the
|
||||
/// only text field.
|
||||
struct SearchField {
|
||||
hint: Arc<egui::Galley>,
|
||||
/// The palette's shortcut as the menus show it; none when the user cleared it.
|
||||
shortcut: Option<String>,
|
||||
key: Option<Arc<egui::Galley>>,
|
||||
width: f32,
|
||||
}
|
||||
|
||||
impl SearchField {
|
||||
/// Space from the field's left edge to the hint text (the magnifier sits in it).
|
||||
const TEXT_LEFT: f32 = 26.0;
|
||||
/// The widest the field gets.
|
||||
const MAX_WIDTH: f32 = 220.0;
|
||||
|
||||
fn new(ui: &Ui, t: &Tokens, shortcut: Option<String>) -> SearchField {
|
||||
let hint = ui.painter().layout_no_wrap(tl!("Search commands").to_string(), egui::FontId::proportional(12.0), t.text_dim);
|
||||
let text_w = Self::TEXT_LEFT + hint.size().x + 8.0;
|
||||
// A shortcut that leaves no room for the hint in the widest field is left to the tooltip.
|
||||
let key = shortcut
|
||||
.as_ref()
|
||||
.map(|s| ui.painter().layout_no_wrap(s.clone(), egui::FontId::proportional(11.0), t.text_dim))
|
||||
.filter(|k| text_w + 12.0 + k.size().x <= Self::MAX_WIDTH);
|
||||
let key_w = key.as_ref().map_or(0.0, |k| 12.0 + k.size().x);
|
||||
let width = (text_w + key_w + 24.0).clamp(120.0, Self::MAX_WIDTH);
|
||||
SearchField { hint, shortcut, key, width }
|
||||
}
|
||||
|
||||
/// Draws the field. A click, or Enter or Space with the keyboard on it, clicks it. Screen
|
||||
/// readers get a button called `name`, and hovering it shows `tip`.
|
||||
fn show(self, ui: &mut Ui, t: &Tokens, name: &str, tip: &str, open: bool) -> egui::Response {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(self.width, WIDGET_H), Sense::click());
|
||||
let fill = if open {
|
||||
t.tool_active
|
||||
} else if resp.hovered() {
|
||||
t.hover
|
||||
} else {
|
||||
t.input
|
||||
};
|
||||
let border = if resp.has_focus() { t.accent } else { t.input_border };
|
||||
ui.painter().rect(r, CornerRadius::same(4), fill, Stroke::new(1.0, border), egui::StrokeKind::Inside);
|
||||
icons::paint(ui, "search", egui::Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0)), t.icon);
|
||||
let mut text_right = r.right() - 8.0;
|
||||
if let Some(key) = self.key {
|
||||
let at = egui::pos2(text_right - key.size().x, r.center().y - key.size().y / 2.0);
|
||||
text_right = at.x - 12.0;
|
||||
ui.painter().with_clip_rect(r).galley(at, key, t.text_dim);
|
||||
}
|
||||
let clip = egui::Rect::from_min_max(r.min, egui::pos2(text_right.max(r.left()), r.bottom()));
|
||||
let at = egui::pos2(r.left() + Self::TEXT_LEFT, r.center().y - self.hint.size().y / 2.0);
|
||||
ui.painter().with_clip_rect(clip).galley(at, self.hint, t.text_dim);
|
||||
resp.widget_info(|| widgets::icon_button_info(ui.is_enabled(), open, name));
|
||||
resp.on_hover_text(tip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window shows the system's title bar instead of the app drawing its own
|
||||
/// ([`VectorcraftApp::desktop_frame`]): Windows with Preferences › User Interface › System Title
|
||||
/// Bar, and Linux whenever the desktop draws the frame, with or without the preference. The
|
||||
|
||||
@@ -159,6 +159,412 @@ fn hints_name_keys_as_the_menus_do() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The widths of the app bar's right-hand group used by the fitting tests.
|
||||
fn right_widths(room: f32, safe_mode: bool) -> super::RightWidths {
|
||||
super::RightWidths { room, safe_mode, switcher: 150.0, field: 170.0, icon: 28.0, gap: 8.0, community: 80.0 }
|
||||
}
|
||||
|
||||
/// What the group shows, in words, with the switcher's width as full, narrower or minimal.
|
||||
fn right_stage(g: &super::RightGroup) -> String {
|
||||
let switcher = match g.switcher_w {
|
||||
_ if !g.switcher => "no switcher",
|
||||
w if w >= 150.0 => "full switcher",
|
||||
w if w > super::MIN_SWITCHER => "narrower switcher",
|
||||
_ => "minimal switcher",
|
||||
};
|
||||
format!("community {}, learn {}, {:?}, {switcher}", g.community, g.learn, g.search)
|
||||
}
|
||||
|
||||
/// As the app bar's room runs short, the community button goes first, then Explore tutorials, then the search
|
||||
/// field becomes the icon, then the workspace switcher narrows to its minimum, then the icon goes.
|
||||
/// Whatever shows fits in the room, down to the minimal switcher alone.
|
||||
#[test]
|
||||
fn the_app_bar_gives_up_its_right_hand_controls_in_order() {
|
||||
let mut stages: Vec<String> = Vec::new();
|
||||
for room in (0..=700).rev().map(|r| r as f32) {
|
||||
let w = right_widths(room, false);
|
||||
let g = super::fit_right_group(&w);
|
||||
let stage = right_stage(&g);
|
||||
if stages.last() != Some(&stage) {
|
||||
stages.push(stage);
|
||||
}
|
||||
let search = match g.search {
|
||||
super::Search::Field => w.gap + w.field,
|
||||
super::Search::Icon => w.gap + w.icon,
|
||||
super::Search::Hidden => 0.0,
|
||||
};
|
||||
let learn = if g.learn { w.gap + w.icon } else { 0.0 };
|
||||
let community = if g.community { 10.0 + w.gap + w.community } else { 0.0 };
|
||||
let used = g.switcher_w + 8.0 + search + learn + community;
|
||||
assert!(used <= room || g.switcher_w == super::MIN_SWITCHER && g.search == super::Search::Hidden, "{room}: {g:?} needs {used}");
|
||||
}
|
||||
assert_eq!(
|
||||
stages,
|
||||
[
|
||||
"community true, learn true, Field, full switcher",
|
||||
"community false, learn true, Field, full switcher",
|
||||
"community false, learn false, Field, full switcher",
|
||||
"community false, learn false, Icon, full switcher",
|
||||
"community false, learn false, Icon, narrower switcher",
|
||||
"community false, learn false, Icon, minimal switcher",
|
||||
// Once the icon has gone, the switcher takes the room it leaves.
|
||||
"community false, learn false, Hidden, narrower switcher",
|
||||
"community false, learn false, Hidden, minimal switcher",
|
||||
]
|
||||
);
|
||||
// In Safe Mode the label's width is taken first (not counted in `room`), and the switcher goes
|
||||
// when a minimal one does not fit.
|
||||
let safe = |room| right_stage(&super::fit_right_group(&right_widths(room, true)));
|
||||
assert_eq!(safe(700.0), "community true, learn true, Field, full switcher");
|
||||
assert_eq!(safe(72.0), "community false, learn false, Hidden, minimal switcher");
|
||||
assert_eq!(safe(71.0), "community false, learn false, Hidden, no switcher");
|
||||
}
|
||||
|
||||
/// What screen readers call the app bar's search field, and the icon it becomes, before the shortcut.
|
||||
const SEARCH_NAME: &str = "Search commands";
|
||||
|
||||
/// A native menu bar that draws nothing.
|
||||
struct NoMenus;
|
||||
impl crate::native_menu::Backend for NoMenus {
|
||||
fn sync(&mut self, _: &crate::native_menu::MenuBar) {}
|
||||
fn drain(&mut self) -> Vec<crate::native_menu::Event> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// The app bar drawn alone, `width` points wide.
|
||||
struct AppBar {
|
||||
app: crate::VectorcraftApp,
|
||||
ctx: egui::Context,
|
||||
width: f32,
|
||||
/// Handle the app's keys before the bar and show the command palette after it, as the app's
|
||||
/// frame does. Off, Tab moves the keyboard focus through the bar's controls, as with a screen
|
||||
/// reader.
|
||||
keys: bool,
|
||||
}
|
||||
|
||||
/// The app bar's search control, as a screen reader and the painter see it.
|
||||
#[derive(Debug)]
|
||||
struct SearchSeen {
|
||||
name: String,
|
||||
rect: egui::Rect,
|
||||
texts: Vec<String>,
|
||||
}
|
||||
|
||||
impl AppBar {
|
||||
fn new(width: f32) -> AppBar {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
crate::shortcut_editor::sync(&app.ui);
|
||||
AppBar { app, ctx, width, keys: false }
|
||||
}
|
||||
|
||||
/// One frame; the accessibility nodes and the texts painted, with where each is.
|
||||
fn frame(&mut self, events: Vec<egui::Event>) -> (Vec<egui::accesskit::Node>, Vec<(String, egui::Rect)>) {
|
||||
fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))),
|
||||
egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.width, 600.0));
|
||||
let (app, keys) = (&mut self.app, self.keys);
|
||||
let mut out = self.ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
if keys {
|
||||
crate::shortcuts::handle(app, ui.ctx());
|
||||
}
|
||||
super::app_bar(app, ui);
|
||||
if keys {
|
||||
crate::palette::show(app, ui.ctx());
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let mut texts = vec![];
|
||||
out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts));
|
||||
(out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default(), texts)
|
||||
}
|
||||
|
||||
/// The search control after two frames, if the bar shows it.
|
||||
fn search(&mut self) -> Option<SearchSeen> {
|
||||
self.frame(vec![]);
|
||||
let (nodes, texts) = self.frame(vec![]);
|
||||
let node = nodes.iter().find(|n| n.label().is_some_and(|l| l.starts_with(SEARCH_NAME)))?;
|
||||
let b = node.bounds()?;
|
||||
let rect = egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32));
|
||||
// Without the icon set loaded, a test frame draws an icon as a warning sign; leave it out.
|
||||
let mut texts: Vec<(String, egui::Rect)> =
|
||||
texts.into_iter().filter(|(t, r)| rect.expand(0.5).contains_rect(*r) && !t.starts_with('\u{26a0}')).collect();
|
||||
texts.sort_by(|a, b| a.1.left().total_cmp(&b.1.left()));
|
||||
let texts = texts.into_iter().map(|(t, _)| t).collect();
|
||||
Some(SearchSeen { name: node.label().unwrap_or_default().to_string(), rect, texts })
|
||||
}
|
||||
|
||||
/// Where the in-window menus end: the right edge of the Help menu's title, if the bar shows it.
|
||||
fn menus_end(&mut self) -> Option<f32> {
|
||||
self.frame(vec![]);
|
||||
let nodes = self.frame(vec![]).0;
|
||||
nodes.iter().filter(|n| n.label() == Some("Help")).filter_map(|n| n.bounds()).map(|b| b.x1 as f32).reduce(f32::max)
|
||||
}
|
||||
|
||||
fn has(&mut self, name: &str) -> bool {
|
||||
self.frame(vec![]);
|
||||
self.frame(vec![]).0.iter().any(|n| n.label() == Some(name))
|
||||
}
|
||||
|
||||
fn click(&mut self, at: egui::Pos2) {
|
||||
let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
self.frame(vec![egui::Event::PointerMoved(at), press(true)]);
|
||||
self.frame(vec![press(false)]);
|
||||
}
|
||||
|
||||
/// Whether the widget at `rect` has the keyboard focus.
|
||||
fn focused_at(&self, rect: egui::Rect) -> bool {
|
||||
self.ctx.memory(|m| m.focused()).and_then(|id| self.ctx.read_response(id)).is_some_and(|r| r.rect == rect)
|
||||
}
|
||||
|
||||
/// A press and release of `key`; Space also types a space, as a keyboard does.
|
||||
fn key(&mut self, key: egui::Key) {
|
||||
let event = |pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
|
||||
let mut press = vec![event(true)];
|
||||
if key == egui::Key::Space {
|
||||
press.push(egui::Event::Text(" ".into()));
|
||||
}
|
||||
self.frame(press);
|
||||
self.frame(vec![event(false)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A wide app bar shows a search field with the palette's shortcut in it, and screen readers get a
|
||||
/// button named [`SEARCH_NAME`] with the shortcut.
|
||||
#[test]
|
||||
fn a_wide_app_bar_shows_a_search_field_with_the_palette_shortcut() {
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
let shortcut = crate::menus::shown_shortcut("Cmd+Shift+/");
|
||||
let seen = bar.search().expect("the search field shows");
|
||||
assert_eq!(seen.name, format!("{SEARCH_NAME} ({shortcut})"));
|
||||
assert!(seen.rect.width() >= 120.0 && seen.rect.width() <= 220.0, "a field, not the 28-point icon: {seen:?}");
|
||||
assert_eq!(seen.texts, [SEARCH_NAME.to_string(), shortcut], "{seen:?}");
|
||||
assert!(bar.has("Explore tutorials"));
|
||||
}
|
||||
|
||||
/// The field shows the palette's shortcut as the user set it, and no shortcut once it is cleared.
|
||||
#[test]
|
||||
fn the_search_field_follows_the_palettes_shortcut() {
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
crate::keymap::set_override(&mut bar.app.ui.shortcut_overrides, "help.commandPalette", "Alt+F9");
|
||||
crate::shortcut_editor::sync(&bar.app.ui);
|
||||
let rebound = crate::menus::shown_shortcut("Alt+F9");
|
||||
let seen = bar.search().expect("the search field shows");
|
||||
assert_eq!(seen.name, format!("{SEARCH_NAME} ({rebound})"));
|
||||
assert_eq!(seen.texts, [SEARCH_NAME.to_string(), rebound], "{seen:?}");
|
||||
crate::keymap::set_override(&mut bar.app.ui.shortcut_overrides, "help.commandPalette", "");
|
||||
crate::shortcut_editor::sync(&bar.app.ui);
|
||||
let seen = bar.search().expect("the search field shows");
|
||||
assert_eq!(seen.name, SEARCH_NAME);
|
||||
assert_eq!(seen.texts, [SEARCH_NAME], "{seen:?}");
|
||||
bar.app.ui.shortcut_overrides.clear();
|
||||
crate::shortcut_editor::sync(&bar.app.ui);
|
||||
}
|
||||
|
||||
/// A shortcut too long to sit beside "Search commands" in the widest field is left to the tooltip
|
||||
/// and the screen-reader name, and "Search commands" stays readable.
|
||||
#[test]
|
||||
fn a_long_shortcut_leaves_the_search_hint_readable() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let long = format!("Ctrl+Alt+Shift+{}", "PageDown".repeat(4));
|
||||
let mut fields = vec![];
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
fields = [Some("Ctrl+Shift+/".to_string()), Some(long.clone()), None]
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
let f = super::SearchField::new(ui, &t, s);
|
||||
(f.width, f.hint.size().x, f.key.as_ref().map(|k| k.size().x), f.shortcut.clone())
|
||||
})
|
||||
.collect();
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
let [(short_w, hint, short_key, _), (long_w, _, long_key, long_shortcut), (none_w, _, none_key, _)] = &fields[..] else {
|
||||
panic!("three fields: {fields:?}");
|
||||
};
|
||||
let short_key = short_key.expect("a short shortcut is shown");
|
||||
assert!(*short_w <= 220.0 && 26.0 + hint + 12.0 + short_key + 8.0 <= *short_w, "the hint and the shortcut fit side by side: {fields:?}");
|
||||
assert_eq!((*long_key, long_shortcut.as_deref()), (None, Some(long.as_str())), "a long one is left to the tooltip and the name");
|
||||
assert!(*long_w <= 220.0 && 26.0 + hint + 8.0 <= *long_w, "{fields:?}");
|
||||
assert!(none_key.is_none() && *none_w >= 120.0, "{fields:?}");
|
||||
}
|
||||
|
||||
/// A click on the field, or on the icon it becomes in a narrow bar, opens the command palette with an
|
||||
/// empty query, and a second click closes it, as the palette's shortcut does. While a dialog is open
|
||||
/// neither does anything, as the shortcut does.
|
||||
#[test]
|
||||
fn a_click_on_the_search_field_opens_the_palette() {
|
||||
for icon in [false, true] {
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
if icon {
|
||||
let narrow = (300..1400).rev().step_by(10).find(|w| {
|
||||
bar.width = *w as f32;
|
||||
bar.search().is_some_and(|s| s.rect.width() == 28.0)
|
||||
});
|
||||
assert!(narrow.is_some(), "a narrow bar shows the icon");
|
||||
}
|
||||
let at = bar.search().expect("the search control shows").rect.center();
|
||||
bar.app.ui.palette_query = "old".into();
|
||||
bar.click(at);
|
||||
assert!(bar.app.ui.palette_open, "icon: {icon}");
|
||||
assert_eq!(bar.app.ui.palette_query, "", "icon: {icon}");
|
||||
bar.app.ui.palette_query = "typed".into();
|
||||
bar.click(at);
|
||||
assert!(!bar.app.ui.palette_open, "a second click closes it (icon: {icon})");
|
||||
assert_eq!(bar.app.ui.palette_query, "", "icon: {icon}");
|
||||
bar.app.ui.dialog = Some(crate::state::Dialog::new("about", json!({})));
|
||||
bar.click(at);
|
||||
assert!(!bar.app.ui.palette_open, "not over a dialog (icon: {icon})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon a narrow bar shows has the field's screen-reader name, and while a dialog is open screen
|
||||
/// readers find the field and the icon disabled.
|
||||
#[test]
|
||||
fn the_search_icon_has_the_fields_name_and_both_are_disabled_under_a_dialog() {
|
||||
let shortcut = crate::menus::shown_shortcut("Cmd+Shift+/");
|
||||
for icon in [false, true] {
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
if icon {
|
||||
let narrow = (300..1400).rev().step_by(10).find(|w| {
|
||||
bar.width = *w as f32;
|
||||
bar.search().is_some_and(|s| s.rect.width() == 28.0)
|
||||
});
|
||||
assert!(narrow.is_some(), "a narrow bar shows the icon");
|
||||
}
|
||||
let disabled = |bar: &mut AppBar| {
|
||||
bar.frame(vec![]);
|
||||
let nodes = bar.frame(vec![]).0;
|
||||
let node = nodes.iter().find(|n| n.label().is_some_and(|l| l.starts_with(SEARCH_NAME))).expect("the search control shows");
|
||||
(node.label().unwrap_or_default().to_string(), node.is_disabled())
|
||||
};
|
||||
assert_eq!(disabled(&mut bar), (format!("{SEARCH_NAME} ({shortcut})"), false), "icon: {icon}");
|
||||
bar.app.ui.dialog = Some(crate::state::Dialog::new("about", json!({})));
|
||||
assert_eq!(disabled(&mut bar), (format!("{SEARCH_NAME} ({shortcut})"), true), "icon: {icon}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyboard focus reaches the field, Enter or Space opens the palette and does nothing else, and
|
||||
/// Tab then moves the focus on. This holds with the app's keys handled, the palette drawn after the
|
||||
/// bar, a document open, and an object selected with the Selection tool, whose Enter otherwise
|
||||
/// opens Move. In the app, Tab with no field focused shows and hides the panels instead of moving
|
||||
/// the focus, so the focus reaches the bar the way a screen reader moves it.
|
||||
#[test]
|
||||
fn the_keyboard_opens_the_palette_from_the_search_field() {
|
||||
let cases =
|
||||
[(egui::Key::Enter, 0), (egui::Key::Space, 0), (egui::Key::Enter, 1), (egui::Key::Space, 1), (egui::Key::Enter, 2), (egui::Key::Space, 2)];
|
||||
for (key, setup) in cases {
|
||||
let document = setup > 0;
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
let field = bar.search().expect("the search field shows").rect;
|
||||
assert!(field.width() >= 120.0, "a field, not the icon: {field:?}");
|
||||
let mut reached = false;
|
||||
for _ in 0..40 {
|
||||
bar.key(egui::Key::Tab);
|
||||
if bar.focused_at(field) {
|
||||
reached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(reached, "Tab reaches the search field");
|
||||
bar.keys = true;
|
||||
if document {
|
||||
bar.app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
}
|
||||
if setup == 2 {
|
||||
let id = bar.app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap()["id"].clone();
|
||||
bar.app.select_tool("selection");
|
||||
bar.app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
}
|
||||
// The app's keys leave the focus on the field.
|
||||
bar.frame(vec![]);
|
||||
assert!(bar.focused_at(field), "{key:?} (setup {setup})");
|
||||
assert!(!bar.app.ui.palette_open);
|
||||
let status = bar.app.ui.status.clone();
|
||||
bar.key(key);
|
||||
// The key opens the palette and goes no further: it does not pick the first result, type a
|
||||
// space into the palette's field or open Move.
|
||||
assert!(bar.app.ui.palette_open, "{key:?} opens the palette (setup {setup})");
|
||||
assert!(bar.app.ui.dialog.is_none(), "{key:?} opened no dialog (setup {setup})");
|
||||
assert_eq!(bar.app.ui.palette_query, "", "{key:?} (setup {setup})");
|
||||
assert!(bar.app.ui.recent_commands.is_empty() && bar.app.ui.status == status, "{key:?} ran nothing (setup {setup})");
|
||||
}
|
||||
// Tab moves the focus off the field with the app's keys handled.
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
let field = bar.search().expect("the search field shows").rect;
|
||||
for _ in 0..40 {
|
||||
if bar.focused_at(field) {
|
||||
break;
|
||||
}
|
||||
bar.key(egui::Key::Tab);
|
||||
}
|
||||
assert!(bar.focused_at(field), "Tab reaches the search field at {field:?}");
|
||||
bar.keys = true;
|
||||
let panels = (bar.app.ui.dock, bar.app.ui.toolbar);
|
||||
bar.key(egui::Key::Tab);
|
||||
assert!(!bar.focused_at(field), "Tab leaves the field");
|
||||
assert_eq!((bar.app.ui.dock, bar.app.ui.toolbar), panels, "Tab on the field does not hide the panels");
|
||||
}
|
||||
|
||||
/// As the window narrows, the search field becomes the icon after Explore tutorials has gone and
|
||||
/// before the icon goes, never overlapping the menus: with a long workspace name, with the menus in
|
||||
/// the system's menu bar, and with the window's own caption buttons.
|
||||
#[test]
|
||||
fn a_narrowing_app_bar_turns_the_search_field_into_the_icon() {
|
||||
for case in ["default", "long workspace name", "native menus", "caption buttons"] {
|
||||
let mut bar = AppBar::new(1400.0);
|
||||
match case {
|
||||
"long workspace name" => bar.app.ui.workspace = "A workspace with a very long name indeed".into(),
|
||||
"native menus" => bar.app.services.native_menu = Some(crate::native_menu::NativeMenu::new(Box::new(NoMenus))),
|
||||
"caption buttons" => bar.app.custom_titlebar = true,
|
||||
_ => {}
|
||||
}
|
||||
assert_eq!(bar.menus_end().is_some(), case != "native menus", "{case}: the in-window menus show");
|
||||
// 0: gone, 1: icon, 2: field.
|
||||
let mut last = 2;
|
||||
let mut seen_icon = false;
|
||||
for width in (300..=1400).rev().step_by(10) {
|
||||
bar.width = width as f32;
|
||||
let learn = bar.has("Explore tutorials");
|
||||
let search = bar.search();
|
||||
let now = match &search {
|
||||
Some(s) if s.rect.width() >= 120.0 => 2,
|
||||
Some(s) => {
|
||||
assert_eq!(s.rect.width(), 28.0, "{case} at {width}");
|
||||
assert!(s.texts.is_empty(), "the icon has no text: {case} at {width}");
|
||||
1
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
assert!(width < 1400 || now == 2, "{case}: a wide bar shows the field");
|
||||
assert!(now <= last, "{case} at {width}: the search came back as the bar narrowed");
|
||||
assert!(!learn || now == 2, "{case} at {width}: Explore tutorials outlasted the field");
|
||||
if let Some(s) = &search {
|
||||
assert!(s.rect.right() <= width as f32, "{case} at {width}: {s:?}");
|
||||
if let Some(menus_end) = bar.menus_end() {
|
||||
assert!(s.rect.left() >= menus_end, "{case} at {width}: the search overlaps the menus ending at {menus_end}: {s:?}");
|
||||
}
|
||||
}
|
||||
seen_icon |= now == 1;
|
||||
last = now;
|
||||
}
|
||||
assert!(seen_icon, "{case}: the field becomes the icon before it goes");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StatusText {
|
||||
text: String,
|
||||
|
||||
@@ -789,6 +789,27 @@ pub fn os_cursors(build: bool, wayland: bool) -> bool {
|
||||
build && !wayland
|
||||
}
|
||||
|
||||
/// The cursor a panel shows where a click or a drop adds something, such as a stop under the
|
||||
/// Gradient panel's ramp or a copy of rows Alt-dragged in the Layers panel (#8217): the white arrow
|
||||
/// with a plus that Group Selection shows for a click that adds the next group. Windows has no system copy cursor (winit shows the plain arrow for
|
||||
/// `CursorIcon::Copy`), so where the window shows glyphs as OS cursors ([`os_cursors`]) the panel
|
||||
/// hands it this glyph; elsewhere (macOS, Wayland, the web, `VECTORCRAFT_SYSTEM_CURSORS`) the
|
||||
/// system's copy cursor shows (#8241). Set every frame it shows: the canvas and egui reset it.
|
||||
pub(crate) fn set_add_cursor(app: &mut crate::VectorcraftApp, ctx: &egui::Context) {
|
||||
ctx.set_cursor_icon(egui::CursorIcon::Copy);
|
||||
if add_cursor_is_a_glyph(app) {
|
||||
// As the canvas sizes its glyphs (User Interface › Scale Cursor Proportional to UI).
|
||||
let ui_scale = if app.session.prefs.scale_cursor_with_ui { 1.0 } else { ctx.zoom_factor() };
|
||||
ctx.set_cursor_image(app.canvas.cursors.get(Cursor::GroupSelection, ctx.pixels_per_point() / ui_scale));
|
||||
}
|
||||
}
|
||||
|
||||
/// Does [`set_add_cursor`] hand the OS its glyph (rather than ask for the system copy cursor)?
|
||||
/// Where the window shows glyphs as OS cursors, unless `VECTORCRAFT_SYSTEM_CURSORS` opts out.
|
||||
pub(crate) fn add_cursor_is_a_glyph(app: &crate::VectorcraftApp) -> bool {
|
||||
std::env::var_os("VECTORCRAFT_SYSTEM_CURSORS").is_none() && os_cursors(OS_CURSORS, app.services.wayland)
|
||||
}
|
||||
|
||||
/// Does the window hide the pointer only while it is the key window? macOS does: winit hides it with
|
||||
/// a cursor rect holding a transparent cursor, and macOS applies the rect only in the key window.
|
||||
/// Over a window behind another app or under a sheet, the system pointer shows (#2020).
|
||||
|
||||
@@ -179,6 +179,9 @@ use crate::{VectorcraftApp, widgets};
|
||||
|
||||
type DialogResult = Result<Value, String>;
|
||||
|
||||
/// A dialog's Reset ([`DialogSpec::reset`]).
|
||||
type ResetFn = fn(&VectorcraftApp, &mut Dialog) -> Result<(), String>;
|
||||
|
||||
/// The shared dialog frame's inner margin, and the least room it leaves at the window's edges.
|
||||
const MARGIN: i8 = 22;
|
||||
const EDGE_GAP: f32 = 8.0;
|
||||
@@ -219,8 +222,8 @@ pub(crate) struct DialogSpec {
|
||||
pub alternate: Option<(&'static str, &'static str)>,
|
||||
/// Puts the fields back to their defaults. While Alt (Option on macOS) is held, the Cancel
|
||||
/// button of a dialog with an `ok` reads Reset; Reset (or `ui.dialogReset`) runs this and the
|
||||
/// dialog stays open.
|
||||
pub reset: Option<fn(&VectorcraftApp, &mut Dialog)>,
|
||||
/// dialog stays open. An error leaves the dialog as it was.
|
||||
pub reset: Option<ResetFn>,
|
||||
pub min_width: f32,
|
||||
pub max_width: Option<f32>,
|
||||
/// The body runs a live preview interaction that Cancel rolls back.
|
||||
@@ -728,12 +731,12 @@ pub(crate) fn can_reset(app: &VectorcraftApp) -> bool {
|
||||
}
|
||||
|
||||
/// Reset (`ui.dialogReset`, or Cancel while Alt or Option is held): the open dialog's fields go
|
||||
/// back to their defaults and it stays open → the dialog; an error when no dialog is open or the
|
||||
/// open one has no Reset.
|
||||
/// back to their defaults and it stays open → the dialog; an error when no dialog is open, the
|
||||
/// open one has no Reset, or its Reset fails (the dialog is then left as it was).
|
||||
pub(crate) fn reset(app: &mut VectorcraftApp) -> DialogResult {
|
||||
let Some(mut d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) };
|
||||
let Some(reset) = spec(&d.kind).reset else { return Err("the open dialog has no Reset".into()) };
|
||||
reset(app, &mut d);
|
||||
reset(app, &mut d)?;
|
||||
let out = serde_json::to_value(&d).unwrap_or_default();
|
||||
app.ui.dialog = Some(d);
|
||||
Ok(out)
|
||||
|
||||
@@ -201,10 +201,35 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
|
||||
(crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS),
|
||||
(crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS),
|
||||
(crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES),
|
||||
("object.rasterize", "antiAlias") => Some(RASTERIZE_ANTI_ALIAS),
|
||||
("object.rasterize", "background") => Some(RASTERIZE_BACKGROUNDS),
|
||||
("object.mesh.create", "appearance") => Some(MESH_APPEARANCES),
|
||||
("object.repeat.options", "gridType") => Some(REPEAT_GRID_TYPES),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Object › Rasterize › Anti-aliasing: the modes `vectorcraft_render::AntiAlias` names, with its
|
||||
/// labels, as the Rasterize effect's dialog lists them (`effect.rs`, `own_choices`).
|
||||
const RASTERIZE_ANTI_ALIAS: form::Choices = &[("None", "none"), ("Art Optimized", "art"), ("Type Optimized", "type")];
|
||||
|
||||
/// Object › Rasterize › Background, as Document Raster Effects Settings and the Rasterize effect
|
||||
/// list it. A color the command was given another way (black, a hex color) shows as it is.
|
||||
const RASTERIZE_BACKGROUNDS: form::Choices = &[("White", "white"), ("Transparent", "transparent")];
|
||||
|
||||
/// Object › Create Gradient Mesh › Appearance: the values `object.mesh.create` takes.
|
||||
const MESH_APPEARANCES: form::Choices = &[("Flat", "flat"), ("To Center", "center"), ("To Edge", "edge")];
|
||||
|
||||
/// Repeat Options › Grid Type of a grid repeat: the tile types, labeled as the Pattern Options
|
||||
/// panel labels them (`panels/pattern_options.rs`, `TILE_LABELS`).
|
||||
const REPEAT_GRID_TYPES: form::Choices = &[
|
||||
("Grid", "grid"),
|
||||
("Brick by Row", "brickByRow"),
|
||||
("Brick by Column", "brickByColumn"),
|
||||
("Hex by Column", "hexByColumn"),
|
||||
("Hex by Row", "hexByRow"),
|
||||
];
|
||||
|
||||
/// Object › Rasterize › Color Model: the values `object.rasterize` takes, the document's own
|
||||
/// colour model first (#5660).
|
||||
fn rasterize_color_models(command: &str, key: &str, cmyk: bool) -> Option<form::Choices> {
|
||||
@@ -688,4 +713,147 @@ mod tests {
|
||||
h.event(egui::Event::PointerButton { pos: ok, button, pressed: false, modifiers });
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// The dialog that is open in `app`, drawn by a kittest harness (the first frame installs the
|
||||
/// fonts).
|
||||
fn dialog_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> {
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
crate::dialogs::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
/// Opens the dropdown labeled `label` and picks `choice` in it: the field must be a dropdown,
|
||||
/// not a text field.
|
||||
fn pick(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, label: &str, choice: &str) {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
assert!(h.query_by_role_and_label(Role::TextInput, label).is_none(), "{label} is not a text field");
|
||||
h.get_by_role_and_label(Role::ComboBox, label).click();
|
||||
h.run_steps(3);
|
||||
h.get_by_label(choice).click();
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// The choices this dialog lists for Rasterize, Create Gradient Mesh and Repeat Options are the
|
||||
/// values their commands take (#8020, #7991): each one runs, and every language with complete
|
||||
/// menus has a row for each label.
|
||||
#[test]
|
||||
fn choice_fields_list_the_values_their_commands_take() {
|
||||
use vectorcraft_doc::pattern::TileType;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
let listed = |command: &str, key: &str| choices(command, key).unwrap_or_else(|| panic!("{command} {key}: a choice"));
|
||||
let aa: Vec<(&str, &str)> = AntiAlias::ALL.iter().map(|a| (a.label(), a.id())).collect();
|
||||
assert_eq!(listed("object.rasterize", "antiAlias"), aa.as_slice());
|
||||
for (_, value) in listed("object.rasterize", "background") {
|
||||
assert!(vectorcraft_doc::Background::parse(value).is_some(), "{value}");
|
||||
}
|
||||
for (label, value) in listed("object.repeat.options", "gridType") {
|
||||
let tile = TileType::parse(value, None).unwrap_or_else(|| panic!("{value}"));
|
||||
assert_eq!((tile.id(), tile.label()), (*value, *label));
|
||||
}
|
||||
let run = |command: &str, key: &str, value: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
if command == "object.repeat.options" {
|
||||
s.execute("object.repeat.grid", &json!({"ids": [id], "rows": 2, "cols": 2})).unwrap();
|
||||
}
|
||||
s.execute(command, &json!({ key: value })).unwrap_or_else(|e| panic!("{command} {key} {value}: {e}"));
|
||||
};
|
||||
let fields = [
|
||||
("object.rasterize", "antiAlias"),
|
||||
("object.rasterize", "background"),
|
||||
("object.mesh.create", "appearance"),
|
||||
("object.repeat.options", "gridType"),
|
||||
];
|
||||
for (command, key) in fields {
|
||||
for (label, value) in listed(command, key) {
|
||||
run(command, key, value);
|
||||
for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) {
|
||||
assert!(crate::i18n::has(lang, label), "{}: {label}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Object › Rasterize… shows Anti Alias and Background as dropdowns of the values
|
||||
/// `object.rasterize` takes. OK rasterizes with the picked ones as one undo step, and a value
|
||||
/// the dialog doesn't list (black) shows as it is and is sent unchanged.
|
||||
#[test]
|
||||
fn rasterize_anti_alias_and_background_are_dropdowns() {
|
||||
let corner = |app: &VectorcraftApp| {
|
||||
let st = app.session.active().unwrap();
|
||||
let key = st.selection.objects.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(i)) => Some(i.key.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let decoded = craft_image_codecs::decode(&st.doc.images[&key.expect("the ellipse became an image")].bytes).unwrap();
|
||||
image::RgbaImage::from_raw(decoded.width(), decoded.height(), decoded.to_rgba8()).unwrap().get_pixel(0, 0).0
|
||||
};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
let steps = app.session.active().unwrap().history.undo.len();
|
||||
crate::menus::invoke(&mut app, "object.rasterize", json!({}));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.str("antiAlias"), d.str("background")), ("art".into(), "transparent".into()));
|
||||
let mut h = dialog_harness(app);
|
||||
pick(&mut h, "Anti Alias:", "Type Optimized");
|
||||
pick(&mut h, "Background:", "White");
|
||||
let d = h.state().ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.str("antiAlias"), d.str("background")), ("type".into(), "white".into()));
|
||||
let app = h.state_mut();
|
||||
crate::dialogs::confirm(app).unwrap();
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step");
|
||||
assert_eq!(corner(app), [255, 255, 255, 255], "a white background");
|
||||
// A background the dialog doesn't list stays as it is.
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
crate::menus::invoke(app, "object.rasterize", json!({}));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("background".into(), json!("black"));
|
||||
frame(app);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("background"), "black", "drawing the dropdown keeps it");
|
||||
crate::dialogs::confirm(app).unwrap();
|
||||
assert_eq!(corner(app), [0, 0, 0, 255], "a black background");
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh… shows Appearance, and Repeat Options for a grid repeat its Grid Type,
|
||||
/// as dropdowns of the values their commands take; OK applies the picked one.
|
||||
#[test]
|
||||
fn mesh_appearance_and_repeat_grid_type_are_dropdowns() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let entries = crate::menus::menu_entries(&app);
|
||||
let item = entries.iter().find(|e| e.path == ["Object"] && e.label == "Create Gradient Mesh…").expect("listed");
|
||||
let (cmd, p) = crate::menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
crate::menus::invoke(&mut app, &cmd, p);
|
||||
let mut h = dialog_harness(app);
|
||||
pick(&mut h, "Appearance:", "To Center");
|
||||
let app = h.state_mut();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("appearance"), "center");
|
||||
crate::dialogs::confirm(app).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(st.selection.objects.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Mesh(_)))), "a mesh");
|
||||
|
||||
let mut h = dialog_harness(grid_options_app());
|
||||
pick(&mut h, "Grid Type:", "Brick by Row");
|
||||
let app = h.state_mut();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("gridType"), "brickByRow");
|
||||
crate::dialogs::confirm(app).unwrap();
|
||||
let fields = crate::panels::pattern_options::repeat_fields(app).unwrap();
|
||||
assert_eq!(fields["gridType"], json!("brickByRow"));
|
||||
}
|
||||
}
|
||||
@@ -189,9 +189,9 @@ pub fn open(app: &mut VectorcraftApp) {
|
||||
}
|
||||
|
||||
/// The options format `id` starts with in Format Settings: the raster options dialogs' defaults
|
||||
/// (without quality and image maps: the rows choose quality, a map is another file), the SVG
|
||||
/// Options' first-use ones (without artboards and images: a linked image is another file), or the
|
||||
/// default PDF preset.
|
||||
/// (without image maps, a map being another file, and without quality but WebP's: JPEG rows choose
|
||||
/// their quality), the SVG Options' first-use ones (without artboards and images: a linked image is
|
||||
/// another file), or the default PDF preset.
|
||||
fn defaults(app: &VectorcraftApp, id: &str) -> Map<String, Value> {
|
||||
let mut o = match (id, fileio::format(id)) {
|
||||
("svg", _) => svg_options::first_use(),
|
||||
@@ -199,9 +199,12 @@ fn defaults(app: &VectorcraftApp, id: &str) -> Map<String, Value> {
|
||||
(_, Some(f)) => png_options::defaults(app, f),
|
||||
_ => Map::new(),
|
||||
};
|
||||
for k in ["quality", "imageMap", "useArtboards", "images"] {
|
||||
for k in ["imageMap", "useArtboards", "images"] {
|
||||
o.remove(k);
|
||||
}
|
||||
if id != "webp" {
|
||||
o.remove("quality");
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
|
||||
@@ -136,10 +136,11 @@ fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)>
|
||||
|
||||
/// Reset (Cancel with Alt or Option held): every option goes back to the Flare tool's default
|
||||
/// (`FLARE_OPTIONS`, with Rays and Rings on). The dialog keeps a click's `x` and `y`, so OK still draws there.
|
||||
fn reset(_: &VectorcraftApp, d: &mut Dialog) {
|
||||
fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
if let Value::Object(defaults) = vectorcraft_tools::create("flare").options() {
|
||||
d.fields.extend(defaults);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// OK: set the tool's options; opened by a click, draw a flare there with them.
|
||||
|
||||
@@ -40,9 +40,10 @@ pub fn open(app: &mut VectorcraftApp) -> Value {
|
||||
}
|
||||
|
||||
/// Reset: the center and 0.
|
||||
fn reset(_: &VectorcraftApp, d: &mut Dialog) {
|
||||
fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
d.fields.insert("pivot".into(), json!(CENTER));
|
||||
d.fields.insert("rotate".into(), json!(0.0));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
@@ -61,8 +62,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.add_space(8.0);
|
||||
let r = widgets::flat_button(ui, tl!("Reset"), 64.0);
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Reset")));
|
||||
if r.clicked() {
|
||||
reset(app, d);
|
||||
if r.clicked()
|
||||
&& let Err(e) = reset(app, d)
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced),
|
||||
//! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image
|
||||
//! map), WebP Options, and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
|
||||
//! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither,
|
||||
//! transparency and matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options
|
||||
//! ([`super::psd_options`]). Fields
|
||||
//! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the
|
||||
@@ -39,6 +39,10 @@ const MATTES: [&str; 3] = ["none", "white", "black"];
|
||||
const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"];
|
||||
/// JPEG quality on the dialog's 0–10 scale: the band each step falls in.
|
||||
const QUALITY_BANDS: [&str; 11] = ["Low", "Low", "Low", "Medium", "Medium", "Medium", "High", "High", "Maximum", "Maximum", "Maximum"];
|
||||
/// WebP compression labels: `lossless` true, then false.
|
||||
const WEBP_COMPRESSION_LABELS: [&str; 2] = ["Lossless", "Lossy"];
|
||||
/// The lossy WebP quality a new export starts with (0–100).
|
||||
const WEBP_QUALITY: u8 = 90;
|
||||
|
||||
/// The dialog kind of a raster format (`pngOptions`, `jpgOptions`, `webpOptions`, `gifOptions`,
|
||||
/// `png8Options`).
|
||||
@@ -81,6 +85,9 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map<String, Value> {
|
||||
"png" => {
|
||||
o.insert("interlaced".into(), json!(false));
|
||||
}
|
||||
"webp" => {
|
||||
o.extend([("lossless".into(), json!(true)), ("quality".into(), json!(WEBP_QUALITY))]);
|
||||
}
|
||||
"jpg" => {
|
||||
let model = if cmyk { ColorModel::Cmyk } else { ColorModel::Rgb };
|
||||
let defaults = jpeg::JpegOptions::default();
|
||||
@@ -207,11 +214,7 @@ pub(super) fn option_rows(ui: &mut egui::Ui, d: &mut Dialog, id: &str, screens:
|
||||
}
|
||||
"jpg" => jpeg_rows(ui, d, &label, screens),
|
||||
"gif" | "png8" => palette_rows(ui, d, &label),
|
||||
"webp" => {
|
||||
ui.label("");
|
||||
label(ui, tl!("Lossless (lossy WebP isn't available yet)"));
|
||||
ui.end_row();
|
||||
}
|
||||
"webp" => webp_rows(ui, d, &label),
|
||||
"psd" => psd_options::rows(ui, d, &label),
|
||||
id => tiff_bmp_tga::rows(ui, d, id, &label),
|
||||
}
|
||||
@@ -252,6 +255,26 @@ fn quality_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui,
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
/// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses
|
||||
/// (dimmed while Lossless is chosen, keeping its value).
|
||||
fn webp_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Compression:"));
|
||||
let lossless = d.fields.get("lossless").and_then(Value::as_bool).unwrap_or(true);
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-webp", WEBP_COMPRESSION_LABELS[usize::from(!lossless)], &WEBP_COMPRESSION_LABELS, 150.0) {
|
||||
d.fields.insert("lossless".into(), json!(i == 0));
|
||||
}
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Quality:"));
|
||||
let mut q = d.f64("quality", f64::from(WEBP_QUALITY)).round().clamp(0.0, 100.0) as u8;
|
||||
ui.add_enabled_ui(!lossless, |ui| {
|
||||
if widgets::slider(ui, egui::Slider::new(&mut q, 0..=100)).changed() {
|
||||
d.fields.insert("quality".into(), json!(q));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
/// The JPEG method, and its scans when progressive.
|
||||
fn method_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Method:"));
|
||||
|
||||
@@ -746,13 +746,19 @@ fn general(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let on = scaling == PrintScaling::Custom || tiles;
|
||||
let linked = get(d, SCALE_LINKED).as_bool() == Some(true);
|
||||
ui.label(tl!("W:"));
|
||||
if let Some(w) = percent(ui, d, "scale.width", on).filter(|_| linked) {
|
||||
let w = percent(ui, d, "scale.width", on);
|
||||
if let Some(w) = w.filter(|_| linked) {
|
||||
set(d, "scale.height", json!(w));
|
||||
}
|
||||
ui.label(tl!("H:"));
|
||||
if let Some(h) = percent(ui, d, "scale.height", on).filter(|_| linked) {
|
||||
let h = percent(ui, d, "scale.height", on);
|
||||
if let Some(h) = h.filter(|_| linked) {
|
||||
set(d, "scale.width", json!(h));
|
||||
}
|
||||
// A typed W or H is what the next `ui.dialog.set` changes from.
|
||||
if w.is_some() || h.is_some() {
|
||||
see_scale(&mut d.fields);
|
||||
}
|
||||
ui.add_enabled_ui(on, |ui| scale_link(ui, d, linked));
|
||||
});
|
||||
row(ui, tl!("Overlap:"), |ui| length(ui, d, "overlap", unit, tiles));
|
||||
@@ -779,11 +785,13 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) {
|
||||
flag(ui, d, "output.spotsToProcess", tl!("Convert All Spot Colors to Process"), separations);
|
||||
flag(ui, d, "output.overprintBlack", tl!("Overprint Black"), separations);
|
||||
heading(ui, tl!("Document Ink Options"));
|
||||
let inks = pv.as_ref().ok().and_then(|v| v["inks"].as_array()).map(Vec::as_slice).unwrap_or_default();
|
||||
// Every ink of the document, the spot inks printing as process (no plate) included.
|
||||
let inks = pv.as_ref().ok().and_then(|v| v["documentInks"].as_array()).map(Vec::as_slice).unwrap_or_default();
|
||||
if !separations || inks.is_empty() {
|
||||
note(ui, tl!("Separations list the document's inks here: one page per ink that prints."));
|
||||
return;
|
||||
}
|
||||
let all_spots = get(d, "output.spotsToProcess").as_bool() == Some(true);
|
||||
let t = Tokens::get(ui.ctx());
|
||||
egui::Grid::new("print-inks").num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| {
|
||||
for h in [tl!("Print"), tl!("Ink"), tl!("Frequency"), tl!("Angle")] {
|
||||
@@ -792,17 +800,31 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) {
|
||||
ui.end_row();
|
||||
for ink in inks {
|
||||
let name = ink["name"].as_str().unwrap_or_default();
|
||||
// A spot ink printing as process has no plate: its plate options wait, dimmed, for it
|
||||
// to print as a spot ink again.
|
||||
let process = ink["convertToProcess"] == true;
|
||||
let on = ink["print"].as_bool().unwrap_or(true);
|
||||
if widgets::check_box(ui, name, on, true) {
|
||||
if widgets::check_box(ui, name, on, !process) {
|
||||
set_ink(d, name, "print", json!(!on));
|
||||
}
|
||||
let spot = if ink["spot"] == true { format!(" ({})", tl!("spot")) } else { String::new() };
|
||||
ui.label(egui::RichText::new(format!("{name}{spot}")).color(t.text));
|
||||
ui.horizontal(|ui| {
|
||||
if ink["spot"] == true {
|
||||
if ink_kind_button(ui, name, process, !all_spots) {
|
||||
set_ink(d, name, "convertToProcess", json!(!process));
|
||||
}
|
||||
} else {
|
||||
ui.add_space(INK_KIND);
|
||||
}
|
||||
let spot = if ink["spot"] == true { format!(" ({})", tl!("spot")) } else { String::new() };
|
||||
ui.label(egui::RichText::new(format!("{name}{spot}")).color(t.text));
|
||||
});
|
||||
for (k, suffix) in [("frequency", " lpi"), ("angle", "°")] {
|
||||
let v = ink[k].as_f64().unwrap_or(0.0);
|
||||
let heading = if k == "frequency" { tl!("Frequency") } else { tl!("Angle") };
|
||||
let field_name = format!("{heading} {name}");
|
||||
if let Some(x) = widgets::plain_field_named(ui, ("print-ink", name, k), Some(&field_name), v, suffix, 2, 72.0) {
|
||||
let typed =
|
||||
ui.add_enabled_ui(!process, |ui| widgets::plain_field_named(ui, ("print-ink", name, k), Some(&field_name), v, suffix, 2, 72.0));
|
||||
if let Some(x) = typed.inner {
|
||||
set_ink(d, name, k, json!(x));
|
||||
}
|
||||
}
|
||||
@@ -812,6 +834,42 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog, pv: &Result<Value, String>) {
|
||||
note(ui, tl!("Frequencies and angles are the output device's to apply."));
|
||||
}
|
||||
|
||||
/// The size of the spot or process icon before a spot ink's name.
|
||||
const INK_KIND: f32 = 18.0;
|
||||
|
||||
/// The icon before spot ink `name`'s name: a spot icon while it prints as a spot ink, the four
|
||||
/// process inks while it prints as process (`process`). A click switches it; dimmed (`enabled`
|
||||
/// off) while Convert All Spot Colors to Process converts every spot ink. Whether it was clicked.
|
||||
fn ink_kind_button(ui: &mut egui::Ui, name: &str, process: bool, enabled: bool) -> bool {
|
||||
let label = if process {
|
||||
crate::i18n::fmt(tl!("Keep {name} as spot"), &[("name", name)])
|
||||
} else {
|
||||
crate::i18n::fmt(tl!("Convert {name} to process"), &[("name", name)])
|
||||
};
|
||||
let sense = if enabled { egui::Sense::click() } else { egui::Sense::hover() };
|
||||
let (rect, resp) = ui.allocate_exact_size(egui::Vec2::splat(INK_KIND), sense);
|
||||
let t = Tokens::get(ui.ctx());
|
||||
if enabled && resp.hovered() {
|
||||
ui.painter().rect_filled(rect, 3.0, t.hover);
|
||||
}
|
||||
let icon = rect.shrink(4.0);
|
||||
if process {
|
||||
let q = icon.size() / 2.0;
|
||||
for (i, c) in crate::panels::swatches::CMYK_INKS.into_iter().enumerate() {
|
||||
let c = if enabled { c } else { c.gamma_multiply(0.4) };
|
||||
let at = icon.min + egui::vec2((i % 2) as f32 * q.x, (i / 2) as f32 * q.y);
|
||||
ui.painter().rect_filled(egui::Rect::from_min_size(at, q), 0.0, c);
|
||||
}
|
||||
} else {
|
||||
let color = if enabled { t.icon } else { t.text_disabled };
|
||||
ui.painter().circle_stroke(icon.center(), icon.width() / 2.0, egui::Stroke::new(1.0, color));
|
||||
ui.painter().circle_filled(icon.center(), icon.width() / 5.0, color);
|
||||
}
|
||||
resp.widget_info(|| widgets::icon_button_info(enabled, false, &label));
|
||||
let resp = resp.on_hover_text(label);
|
||||
enabled && resp.clicked()
|
||||
}
|
||||
|
||||
/// Set option `key` of ink `name` in `output.inks` (the ink gets its own entry the first time).
|
||||
fn set_ink(d: &mut Dialog, name: &str, key: &str, value: Value) {
|
||||
let mut inks = get(d, "output.inks").as_array().cloned().unwrap_or_default();
|
||||
|
||||
@@ -9,7 +9,10 @@
|
||||
//! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`,
|
||||
//! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed),
|
||||
//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a
|
||||
//! preset) and `__hasSlices`. Save… remembers
|
||||
//! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K),
|
||||
//! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`,
|
||||
//! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and
|
||||
//! takes the settings it finds, and `__optimized` holds its result. Save… remembers
|
||||
//! the settings and writes the files (`file.saveForWeb`); Done only remembers them; Preview in
|
||||
//! Browser opens the HTML page (`file.saveForWeb.browser`). While Alt (Option on macOS) is held,
|
||||
//! Cancel reads Reset, which puts the remembered settings back and leaves the dialog open
|
||||
@@ -71,6 +74,11 @@ const MATTES: [&str; 3] = ["none", "white", "black"];
|
||||
const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"];
|
||||
/// JPEG quality steps: (label, quality).
|
||||
const QUALITIES: [(&str, u8); 5] = [("Low", 10), ("Medium", 30), ("High", 60), ("Very High", 80), ("Maximum", 100)];
|
||||
/// Optimize to File Size's Start With (`__optimizeStart`) and Use (`__optimizeUse`) choices.
|
||||
const START_WITH: [(&str, &str); 2] = [("current", "Current Settings"), ("auto", "Auto Select GIF/JPEG")];
|
||||
const SIZE_USE: [(&str, &str); 3] = [("allSlices", "Total of All Slices"), ("eachSlice", "Each Slice"), ("currentSlice", "Current Slice")];
|
||||
/// The fields of Optimize to File Size's rows.
|
||||
const OPTIMIZE_FIELDS: [&str; 3] = ["__optimizeK", "__optimizeStart", "__optimizeUse"];
|
||||
|
||||
/// Open on the document's active artboard, keeping the other remembered settings.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
@@ -101,11 +109,12 @@ fn remembered(app: &VectorcraftApp) -> WebSettings {
|
||||
/// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the
|
||||
/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay,
|
||||
/// nothing is remembered or written, and the dialog stays open.
|
||||
fn reset(app: &VectorcraftApp, d: &mut Dialog) {
|
||||
fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
for key in ["preset", "discard", "__presetName", "__color"] {
|
||||
d.fields.remove(key);
|
||||
}
|
||||
d.fields.extend(settings_fields(&remembered(app)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings as dialog fields.
|
||||
@@ -411,13 +420,11 @@ fn texture(ctx: &egui::Context, name: &str, px: &[u8], [w, h]: [u32; 2]) -> egui
|
||||
ctx.load_texture(name, img, opts)
|
||||
}
|
||||
|
||||
/// The rendering for `s` and the optimised image for each of `panes`, from the cache when nothing
|
||||
/// they depend on changed.
|
||||
fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: &[WebSettings]) -> (Result<Shot, String>, Vec<Result<Shot, String>>) {
|
||||
let Some(st) = app.session.active() else { return (Err("no document".into()), vec![]) };
|
||||
let doc = &st.doc;
|
||||
let mut cache: Cache = ctx.data(|m| m.get_temp(cache_id())).unwrap_or_default();
|
||||
let render_key = format!(
|
||||
/// What the rendering for `s` depends on: the active document, its revision and the settings that
|
||||
/// change the image's pixels.
|
||||
fn render_key(app: &VectorcraftApp, s: &WebSettings) -> Option<String> {
|
||||
let st = app.session.active()?;
|
||||
Some(format!(
|
||||
"{}:{}:{:?}:{:?}:{:?}:{}:{}:{:?}:{:?}",
|
||||
st.uid,
|
||||
st.revision,
|
||||
@@ -428,7 +435,15 @@ fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: &
|
||||
s.clip_to_artboard,
|
||||
s.artboard,
|
||||
(!s.clip_to_artboard).then_some(s.slices)
|
||||
);
|
||||
))
|
||||
}
|
||||
|
||||
/// The rendering for `s` and the optimised image for each of `panes`, from the cache when nothing
|
||||
/// they depend on changed.
|
||||
fn previews(app: &VectorcraftApp, ctx: &egui::Context, s: &WebSettings, panes: &[WebSettings]) -> (Result<Shot, String>, Vec<Result<Shot, String>>) {
|
||||
let (Some(st), Some(render_key)) = (app.session.active(), render_key(app, s)) else { return (Err("no document".into()), vec![]) };
|
||||
let doc = &st.doc;
|
||||
let mut cache: Cache = ctx.data(|m| m.get_temp(cache_id())).unwrap_or_default();
|
||||
if cache.render_key != render_key || cache.render.is_none() {
|
||||
let r = webexport::render(doc, s).map(Arc::new);
|
||||
cache.original = r.as_ref().ok().map(|r| Shot {
|
||||
@@ -507,6 +522,14 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if let Err(e) = apply_preset(app, d) {
|
||||
app.status(e);
|
||||
}
|
||||
if d.fields.remove("__optimizeOpen").is_some_and(|v| v == json!(true)) {
|
||||
open_optimize_rows(app, ui, d);
|
||||
}
|
||||
if d.fields.remove("__optimizeGo").is_some_and(|v| v == json!(true))
|
||||
&& let Err(e) = optimize_to_size(app, d)
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
let settings = settings_of(app, d);
|
||||
let mut browser = false;
|
||||
ui.horizontal_top(|ui| {
|
||||
@@ -520,6 +543,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
side(app, ui, d, settings.as_ref().ok());
|
||||
});
|
||||
});
|
||||
optimize_on_enter(ui.ctx(), d);
|
||||
if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) {
|
||||
app.status(e);
|
||||
}
|
||||
@@ -703,6 +727,7 @@ fn pairs<T: Copy>(all: &[T], key: fn(T) -> &'static str, label: fn(T) -> &'stati
|
||||
|
||||
fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) {
|
||||
presets_row(app, ui, d, s);
|
||||
optimize_rows(ui, d, s, &art_key(app));
|
||||
widgets::divider(ui);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| {
|
||||
@@ -804,6 +829,157 @@ fn presets_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: O
|
||||
}
|
||||
}
|
||||
|
||||
/// The optimized file size of the settings `s` on the active document as it is now: from the preview
|
||||
/// cache when the cache holds that document at its current revision, else made through [`previews`],
|
||||
/// which keeps the image for the preview drawn later in the same frame.
|
||||
fn previewed_bytes(app: &VectorcraftApp, ui: &egui::Ui, s: &WebSettings) -> Option<usize> {
|
||||
let key = s.to_json().to_string();
|
||||
let cache: Option<Cache> = ui.ctx().data(|m| m.get_temp(cache_id()));
|
||||
let cached = cache
|
||||
.filter(|c| Some(&c.render_key) == render_key(app, s).as_ref())
|
||||
.and_then(|c| c.shots.into_iter().find(|(k, _)| *k == key))
|
||||
.and_then(|(_, shot)| shot.ok())
|
||||
.and_then(|shot| shot.bytes);
|
||||
cached.or_else(|| previews(app, ui.ctx(), s, std::slice::from_ref(s)).1.into_iter().next()?.ok()?.bytes)
|
||||
}
|
||||
|
||||
/// Optimize to File Size…: the button opens rows ([`open_optimize_rows`]) for the desired size in
|
||||
/// K, Start With and, with slices, Use; OK or Enter runs [`optimize_to_size`] and Cancel
|
||||
/// closes the rows. A line gives the size it found and whether that is within the desired size
|
||||
/// ([`optimized_result`]).
|
||||
fn optimize_rows(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>, art: &str) {
|
||||
if d.fields.contains_key("__optimizeK") {
|
||||
widgets::label_row(ui, tl!("Desired File Size:"), LABEL_W, |ui| {
|
||||
let k = d.f64("__optimizeK", 32.0);
|
||||
if let Some(v) = widgets::range_field(ui, "sfw-optimize-k", k, 0.001..=webexport::MAX_DESIRED_K, "K", 3, 100.0) {
|
||||
d.fields.insert("__optimizeK".into(), json!(v));
|
||||
}
|
||||
});
|
||||
form::choice(ui, d, "__optimizeStart", tl!("Start With:"), (LABEL_W, FIELD_W), &START_WITH);
|
||||
if d.bool("__hasSlices") {
|
||||
form::choice(ui, d, "__optimizeUse", tl!("Use:"), (LABEL_W, FIELD_W), &SIZE_USE);
|
||||
}
|
||||
widgets::label_row(ui, "", LABEL_W, |ui| {
|
||||
if widgets::flat_button(ui, tl!("OK"), 64.0).clicked() {
|
||||
d.fields.insert("__optimizeGo".into(), json!(true));
|
||||
}
|
||||
if widgets::flat_button(ui, tl!("Cancel"), 64.0).clicked() {
|
||||
for k in OPTIMIZE_FIELDS {
|
||||
d.fields.remove(k);
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
widgets::label_row(ui, "", LABEL_W, |ui| {
|
||||
if widgets::flat_button(ui, tl!("Optimize to File Size…"), FIELD_W).clicked() {
|
||||
d.fields.insert("__optimizeOpen".into(), json!(true));
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(r) = optimized_result(d, s, art) {
|
||||
let size = size_label(r["bytes"].as_u64().unwrap_or(0) as usize);
|
||||
let target = size_label(r["targetBytes"].as_u64().unwrap_or(0) as usize);
|
||||
let text = if r["achieved"] == json!(true) {
|
||||
crate::i18n::fmt(tl!("{size}, within {target}"), &[("size", &size), ("target", &target)])
|
||||
} else {
|
||||
crate::i18n::fmt(tl!("No setting tried fits in {target}; the smallest is {size}"), &[("size", &size), ("target", &target)])
|
||||
};
|
||||
widgets::label_row(ui, "", LABEL_W, |ui| {
|
||||
widgets::dim_label(ui, &text);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// An Enter while the Optimize to File Size rows ([`optimize_rows`]) are open is their OK: it does
|
||||
/// not save. Run after every control of the dialog has drawn, it runs the search unless a control
|
||||
/// took the press (an open dropdown), a field refused the value typed in it, or Ctrl, Cmd or Alt was
|
||||
/// held, which the size field does not commit.
|
||||
pub(super) fn optimize_on_enter(ctx: &egui::Context, d: &mut Dialog) {
|
||||
if !d.fields.contains_key("__optimizeK") || !crate::shortcuts::pressed_anew(ctx, egui::Key::Enter) {
|
||||
return;
|
||||
}
|
||||
let held = ctx.input(|i| {
|
||||
i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, modifiers, .. } if modifiers.ctrl || modifiers.command || modifiers.alt))
|
||||
});
|
||||
let refused = ctx.data(|m| m.get_temp::<bool>(widgets::dialog_reject_commit_flag())).unwrap_or(false);
|
||||
widgets::reject_dialog_commit(ctx);
|
||||
if !held && !refused {
|
||||
d.fields.insert("__optimizeGo".into(), json!(true));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// The last Optimize to File Size result (`__optimized`) while it still holds: the settings are the
|
||||
/// ones it found and the art (`art`, from [`art_key`]) is the art it measured.
|
||||
pub(super) fn optimized_result<'a>(d: &'a Dialog, s: Option<&WebSettings>, art: &str) -> Option<&'a Value> {
|
||||
d.fields.get("__optimized").filter(|r| r["art"] == json!(art) && s.is_some_and(|s| r["settings"] == s.to_json()))
|
||||
}
|
||||
|
||||
/// The active document, its revision and its selected objects and slices, which an Optimize to File
|
||||
/// Size result was measured on. The selection decides the slices Save writes with `slices: selected`
|
||||
/// and the slice Current Slice measures, and a selection made on the canvas or with the Slice
|
||||
/// Selection tool leaves the revision as it is.
|
||||
pub(super) fn art_key(app: &VectorcraftApp) -> String {
|
||||
app.session.active().map_or_else(String::new, |st| format!("{}:{}:{:?}:{:?}", st.uid, st.revision, st.selection.objects, st.selection.slices))
|
||||
}
|
||||
|
||||
/// `bytes` in K, rounded up to the Desired File Size field's 0.001 K so the size it asks for holds
|
||||
/// them. The product is taken in `u128`, which holds any `usize` times 1000 on every target.
|
||||
pub(super) fn size_k(bytes: usize) -> f64 {
|
||||
(bytes as u128 * 1000).div_ceil(1024).max(1) as f64 / 1000.0
|
||||
}
|
||||
|
||||
/// Optimize to File Size… (`__optimizeOpen`): opens the rows with Current Settings and Total of All
|
||||
/// Slices, the desired size starting at the size the current settings give what that Use measures:
|
||||
/// the image slices' files together when there are slices, else the preview's file (32 K when it
|
||||
/// cannot be measured).
|
||||
fn open_optimize_rows(app: &mut VectorcraftApp, ui: &egui::Ui, d: &mut Dialog) {
|
||||
let bytes = if d.bool("__hasSlices") {
|
||||
let mut p = params(d);
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.insert("desiredK".into(), json!(webexport::MAX_DESIRED_K));
|
||||
o.insert("use".into(), json!("allSlices"));
|
||||
}
|
||||
let r = app.run("webExport.optimizeToFileSize", p).ok();
|
||||
r.filter(|r| r["achieved"] == json!(true)).and_then(|r| r["bytes"].as_u64()).map(|b| b as usize)
|
||||
} else {
|
||||
settings_of(app, d).ok().and_then(|s| previewed_bytes(app, ui, &s))
|
||||
};
|
||||
let k = bytes.map_or(32.0, size_k);
|
||||
d.fields.insert("__optimizeK".into(), json!(k));
|
||||
d.fields.insert("__optimizeStart".into(), json!("current"));
|
||||
d.fields.insert("__optimizeUse".into(), json!("allSlices"));
|
||||
}
|
||||
|
||||
/// Optimize to File Size's OK: `webExport.optimizeToFileSize` with the dialog's settings and the
|
||||
/// rows' values; the settings it finds replace the dialog's, the rows close and `__optimized`
|
||||
/// keeps the result. An error leaves the settings and the rows as they are.
|
||||
pub(super) fn optimize_to_size(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<Value, String> {
|
||||
let mut p = params(d);
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.insert("desiredK".into(), d.fields.get("__optimizeK").cloned().unwrap_or(Value::Null));
|
||||
let start = d.str("__optimizeStart");
|
||||
if !start.is_empty() {
|
||||
o.insert("startWith".into(), json!(start));
|
||||
}
|
||||
let scope = d.str("__optimizeUse");
|
||||
if d.bool("__hasSlices") && !scope.is_empty() {
|
||||
o.insert("use".into(), json!(scope));
|
||||
}
|
||||
}
|
||||
let r = app.run("webExport.optimizeToFileSize", p)?;
|
||||
if let Some(found) = r["settings"].as_object() {
|
||||
d.fields.extend(found.clone());
|
||||
}
|
||||
for k in OPTIMIZE_FIELDS {
|
||||
d.fields.remove(k);
|
||||
}
|
||||
let result =
|
||||
json!({ "settings": r["settings"], "bytes": r["bytes"], "targetBytes": r["targetBytes"], "achieved": r["achieved"], "art": art_key(app) });
|
||||
d.fields.insert("__optimized".into(), result);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Two checkboxes side by side.
|
||||
fn check_pair(ui: &mut egui::Ui, d: &mut Dialog, (a, a_label): (&str, &str), (b, b_label): (&str, &str)) {
|
||||
widgets::label_row(ui, "", LABEL_W, |ui| {
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! `document.pdfSettings`. Save Preset… names the settings as a preset (`pdf.preset.save`).
|
||||
//! Opened from Export As with Use Artboards off (`__artBounds`), the dialog has no Artboards
|
||||
//! section, and OK writes one page of the visible art's bounds through [`io::export`]; opened
|
||||
//! from Export Selection (`__selection` too), the page is the selection's crop.
|
||||
//! from Export Selection (`__selection` too), the page is the selection's crop. While Alt (Option
|
||||
//! on macOS) is held, Cancel reads Reset, which puts the options back to the chosen preset's
|
||||
//! settings and leaves the dialog open (`ui.dialogReset`).
|
||||
//!
|
||||
//! The same dialog edits a preset (kind `pdfPreset`, from Edit → PDF Presets): a `name` and
|
||||
//! `description` instead of the preset and artboards, and OK saves the preset.
|
||||
@@ -30,8 +32,15 @@ use crate::{VectorcraftApp, io, widgets};
|
||||
|
||||
pub(super) const KIND: &str = "savePdf";
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Save PDF").into(), body, confirm, ok: Some("Save PDF"), inputs: |_| &["path"], ..DialogSpec::FORM };
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
heading: |_| tl!("Save PDF").into(),
|
||||
body,
|
||||
confirm,
|
||||
ok: Some("Save PDF"),
|
||||
inputs: |_| &["path"],
|
||||
reset: Some(reset),
|
||||
..DialogSpec::FORM
|
||||
};
|
||||
|
||||
/// The dialog kind of the preset editor (New / Edit in Edit → PDF Presets).
|
||||
pub(super) const PRESET_KIND: &str = "pdfPreset";
|
||||
@@ -502,13 +511,33 @@ fn preset_rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
fn apply_preset(app: &mut VectorcraftApp, d: &mut Dialog, name: &str) {
|
||||
match settings_fields(app, &json!({ "preset": name })) {
|
||||
Ok(settings) => {
|
||||
d.fields.extend(settings);
|
||||
replace_settings(d, settings);
|
||||
d.fields.insert("preset".into(), json!(name));
|
||||
}
|
||||
Err(e) => app.status(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The UI-only fields that stand for options: the Security section's password checkboxes.
|
||||
const OPTION_FLAGS: [&str; 2] = ["__requireOpenPassword", "__restrictPermissions"];
|
||||
|
||||
/// Replace every option with `settings` (from [`settings_fields`]), the password checkboxes
|
||||
/// included. The preset, the artboard choice, the path and the other UI-only fields (the section,
|
||||
/// the Save Preset name) stay.
|
||||
fn replace_settings(d: &mut Dialog, settings: Map<String, Value>) {
|
||||
d.fields.retain(|k, _| matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str())));
|
||||
d.fields.extend(settings);
|
||||
}
|
||||
|
||||
/// Reset (Cancel with Alt or Option held): the options go back to the chosen preset's settings, as
|
||||
/// choosing that preset sets them, and the dialog stays open. A preset that can no longer be found
|
||||
/// (a saved one deleted while the dialog is open) is an error, and the dialog is left as it is.
|
||||
fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> {
|
||||
let settings = settings_fields(app, &json!({ "preset": d.str("preset") }))?;
|
||||
replace_settings(d, settings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// General: the options, then the artboards (Save PDF) or the description (preset editor).
|
||||
fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) {
|
||||
heading(ui, tl!("Options"));
|
||||
|
||||
@@ -346,6 +346,74 @@ fn presets_reset_the_settings_and_fields_fall_back_to_defaults() {
|
||||
assert!(app.run("ui.savePdfDialog", json!({"compatibility": "1.0"})).is_err(), "bad options are refused");
|
||||
}
|
||||
|
||||
/// Reset (`ui.dialogReset`, or Cancel with Alt or Option held) puts every option back to the
|
||||
/// chosen preset's settings, passwords and their checkboxes included, and keeps the preset, the
|
||||
/// path, the artboard range, the section and the dialog. After another preset is chosen, Reset
|
||||
/// goes back to that one, and choosing it also clears the password checkboxes.
|
||||
#[test]
|
||||
fn reset_puts_the_chosen_presets_settings_back_and_keeps_the_path_and_artboards() {
|
||||
let (mut app, written, _) = app();
|
||||
app.run("pdf.preset.save", json!({"name": "Mine", "compatibility": "1.5", "marks": {"trim": true}})).unwrap();
|
||||
app.run("ui.savePdfDialog", json!({"path": "/tmp/reset.pdf", "preset": "Mine"})).unwrap();
|
||||
set_field(&mut app, "__allArtboards", json!(false));
|
||||
set_field(&mut app, "range", json!("2"));
|
||||
set_field(&mut app, "__section", json!("Security"));
|
||||
set_field(&mut app, "compatibility", json!("1.7"));
|
||||
set_field(&mut app, "marks.trim", json!(false));
|
||||
set_field(&mut app, "compression.color.ppi", json!(72));
|
||||
set_field(&mut app, OPEN_PASSWORD, json!("secret"));
|
||||
set_field(&mut app, "__restrictPermissions", json!(true));
|
||||
let r = app.run("ui.dialogReset", json!({})).unwrap();
|
||||
assert_eq!(r["kind"], KIND);
|
||||
let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open");
|
||||
assert_eq!(get(d, "compatibility"), "1.5");
|
||||
assert_eq!(get(d, "marks.trim"), true);
|
||||
assert_eq!(get(d, "compression.color.ppi"), 300.0, "a nested option goes back too");
|
||||
assert_eq!(get(d, OPEN_PASSWORD).as_str().unwrap_or_default(), "", "the password is cleared");
|
||||
assert!(!d.fields.contains_key("__restrictPermissions"), "the checkbox is cleared");
|
||||
assert_eq!(
|
||||
(d.str("preset"), d.str("path"), d.str("range"), d.str("__section")),
|
||||
("Mine".to_string(), "/tmp/reset.pdf".to_string(), "2".to_string(), "Security".to_string())
|
||||
);
|
||||
assert!(!d.bool("__allArtboards"));
|
||||
|
||||
let mut d = d.clone();
|
||||
d.fields.insert("__requireOpenPassword".into(), json!(true));
|
||||
apply_preset(&mut app, &mut d, pdf::DEFAULT_PRESET);
|
||||
assert!(!d.fields.contains_key("__requireOpenPassword"), "choosing a preset clears the checkbox");
|
||||
app.ui.dialog = Some(d);
|
||||
set_field(&mut app, "compatibility", json!("1.4"));
|
||||
app.run("ui.dialogReset", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().expect("the dialog stays open");
|
||||
assert_eq!(d.str("preset"), pdf::DEFAULT_PRESET);
|
||||
assert_eq!(get(d, "compatibility"), "1.7");
|
||||
assert_eq!(get(d, "marks.trim"), false);
|
||||
// OK writes the reset options to the kept path and range.
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let w = written.borrow();
|
||||
assert_eq!((w.len(), w[0].0.as_str()), (1, "/tmp/reset.pdf"));
|
||||
assert!(w[0].1.starts_with(b"%PDF-1.7"));
|
||||
assert_eq!(vectorcraft_pdf::import(&w[0].1).unwrap().artboards.len(), 1, "range 2");
|
||||
}
|
||||
|
||||
/// Reset with a saved preset deleted while the dialog is open is an error naming the preset, and
|
||||
/// it leaves the options and the password as they are rather than switching to another preset's.
|
||||
#[test]
|
||||
fn reset_with_a_deleted_preset_is_an_error_and_keeps_the_options() {
|
||||
let (mut app, _, _) = app();
|
||||
app.run("pdf.preset.save", json!({"name": "Gone", "compatibility": "1.5"})).unwrap();
|
||||
app.run("ui.savePdfDialog", json!({"preset": "Gone"})).unwrap();
|
||||
set_field(&mut app, "compatibility", json!("1.6"));
|
||||
set_field(&mut app, OPEN_PASSWORD, json!("secret"));
|
||||
app.run("pdf.preset.delete", json!({"name": "Gone"})).unwrap();
|
||||
let e = app.run("ui.dialogReset", json!({})).unwrap_err();
|
||||
assert!(e.contains("unknown PDF preset `Gone`"), "{e}");
|
||||
let d = app.ui.dialog.as_ref().expect("the dialog stays open");
|
||||
assert_eq!(d.str("preset"), "Gone");
|
||||
assert_eq!(get(d, "compatibility"), "1.6");
|
||||
assert_eq!(get(d, OPEN_PASSWORD), "secret");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_and_bleeds_reach_the_pdf() {
|
||||
let (mut app, written, _) = app();
|
||||
|
||||
@@ -402,7 +402,15 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
let mut rows: Option<egui::Rect> = None;
|
||||
egui::Grid::new("shape-size-dlg").num_columns(3).spacing([10.0, 8.0]).show(ui, |ui| {
|
||||
for (key, label) in [("width", "Width:"), ("height", "Height:")] {
|
||||
let row = form::row_label(ui, label);
|
||||
let row = if key == "height" && d.kind == "ellipse" {
|
||||
let (row, pressed) = height_label_button(ui, label);
|
||||
if pressed {
|
||||
copy_width_to_height(d);
|
||||
}
|
||||
row
|
||||
} else {
|
||||
form::row_label(ui, label)
|
||||
};
|
||||
if ui.label_inputs_by(row.id, |ui| form::length(ui, d, key, unit, form::FIELD_W)) {
|
||||
follow_link(d, key);
|
||||
}
|
||||
@@ -424,6 +432,8 @@ fn linked_size_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
let resp = ui.interact(rect, ui.scope_id().with("shape-size-link"), egui::Sense::click());
|
||||
let icon = if on { "link" } else { "link-2-off" };
|
||||
if widgets::paint_icon_button(ui, resp, icon, "Constrain Width and Height Proportions", on).clicked() {
|
||||
// Enter on the focused button turns the link on or off; it does not also press OK.
|
||||
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
d.fields.insert(LINK.into(), json!(!on));
|
||||
sync_link(ui.ctx(), d);
|
||||
}
|
||||
@@ -469,6 +479,61 @@ fn follow_link(d: &mut Dialog, typed: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ellipse dialog's Height label: a button drawn as the other rows' labels are. Whether it was
|
||||
/// pressed: a click, or Enter or Space while it has the keyboard focus; that Enter does not also
|
||||
/// press OK. A click whose press took the focus from a field that then refused its text (Width
|
||||
/// left empty or not a distance) does not count, as such a click on OK does not. Screen readers
|
||||
/// read it as the button "Height:" (which also names the Height field) with the description "Copy
|
||||
/// Width to Height".
|
||||
fn height_label_button(ui: &mut egui::Ui, label: &str) -> (egui::Response, bool) {
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
let text = egui::RichText::new(tl!(label)).color(t.text_dim);
|
||||
let resp = ui.add(egui::Button::new(text).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
let resp = resp.on_hover_text(tl!("Copy Width to Height"));
|
||||
let press = resp.id.with("press-pass");
|
||||
if resp.contains_pointer() && ui.input(|i| i.pointer.any_pressed()) {
|
||||
let pass = ui.ctx().cumulative_pass_nr();
|
||||
ui.data_mut(|m| m.insert_temp(press, pass));
|
||||
}
|
||||
if !resp.clicked() {
|
||||
// A press let go without a click (dragged off the button) leaves no press behind.
|
||||
if ui.input(|i| i.pointer.any_released()) {
|
||||
ui.data_mut(|m| m.remove::<u64>(press));
|
||||
}
|
||||
return (resp, false);
|
||||
}
|
||||
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
|
||||
let (pressed_at, refused_at, refused_now) = ui.data_mut(|m| {
|
||||
let pressed_at = m.get_temp::<u64>(press);
|
||||
m.remove::<u64>(press);
|
||||
(pressed_at, m.get_temp::<u64>(widgets::dialog_reject_pass()), m.get_temp::<bool>(widgets::dialog_reject_commit_flag()))
|
||||
});
|
||||
let refused = refused_now == Some(true) || matches!((refused_at, pressed_at), (Some(r), Some(p)) if r >= p);
|
||||
(resp, !refused)
|
||||
}
|
||||
|
||||
/// Height takes the Width the dialog holds (help page "Draw ellipses",
|
||||
/// <https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140>).
|
||||
/// A Width that is missing, empty, not a distance or not finite leaves Height as it is. With the
|
||||
/// link on, the link keeps the circle from then on (proportions 1 : 1), or keeps no proportions
|
||||
/// when Width is 0; the link stays on.
|
||||
fn copy_width_to_height(d: &mut Dialog) {
|
||||
let width = match d.fields.get("width") {
|
||||
Some(Value::Number(n)) => n.as_f64(),
|
||||
Some(Value::String(s)) => Unit::Points.parse(s),
|
||||
_ => None,
|
||||
};
|
||||
let Some(width) = width.filter(|w| w.is_finite()) else { return };
|
||||
d.fields.insert("height".into(), json!(width));
|
||||
if d.bool(LINK) {
|
||||
if width != 0.0 {
|
||||
d.fields.insert(RATIO.into(), json!(1.0));
|
||||
} else {
|
||||
d.fields.remove(RATIO);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ellipse dialog's Anchors: the nearest whole number from 2 to 1000 (4, a live ellipse, when
|
||||
/// left empty or not a number).
|
||||
fn ellipse_anchors(d: &Dialog) -> u64 {
|
||||
@@ -1063,6 +1128,237 @@ mod tests {
|
||||
assert_eq!(ellipse_anchors(h.state().ui.dialog.as_ref().unwrap()), 4);
|
||||
}
|
||||
|
||||
/// A harness drawing `app`'s dialog, with the app's fonts installed on its first frame.
|
||||
fn dialog_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> {
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
/// The dialog's Width and Height in points.
|
||||
fn dialog_size(h: &egui_kittest::Harness<'_, VectorcraftApp>) -> (f64, f64) {
|
||||
let d = h.state().ui.dialog.as_ref().expect("the dialog is open");
|
||||
(d.f64("width", -1.0), d.f64("height", -1.0))
|
||||
}
|
||||
|
||||
/// Replaces the text of the field named `name` with `text` and leaves it with Tab.
|
||||
fn retype(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str, text: &str) {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() };
|
||||
h.get_by_role_and_label(Role::TextInput, name).focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(all, egui::Key::A);
|
||||
h.get_by_role_and_label(Role::TextInput, name).type_text(text);
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// In the Ellipse dialog, a click on the word Height copies Width into Height, also a Width
|
||||
/// typed and not yet committed; the fields keep their names. Cancel discards it; OK draws the
|
||||
/// circle as one undo step.
|
||||
#[test]
|
||||
fn clicking_height_in_the_ellipse_dialog_copies_width_into_height() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0}));
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("width".into(), json!(80.0));
|
||||
d.fields.insert("height".into(), json!(30.0));
|
||||
let mut h = dialog_harness(app);
|
||||
h.check_accessibility();
|
||||
let button = h.get_by_role_and_label(Role::Button, "Height:");
|
||||
assert_eq!(button.accesskit_node().description().as_deref(), Some("Copy Width to Height"));
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(dialog_size(&h), (80.0, 80.0));
|
||||
let d = h.state().ui.dialog.as_ref().unwrap();
|
||||
assert!(!d.bool(LINK) && !d.fields.contains_key(RATIO), "the link stays off");
|
||||
// The value fields keep their names.
|
||||
h.get_by_role_and_label(Role::TextInput, "Width:");
|
||||
h.get_by_role_and_label(Role::TextInput, "Height:");
|
||||
|
||||
// A Width typed and not committed with Enter or Tab is the one copied.
|
||||
let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() };
|
||||
h.get_by_role_and_label(Role::TextInput, "Width:").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(all, egui::Key::A);
|
||||
h.get_by_role_and_label(Role::TextInput, "Width:").type_text("50 pt");
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog_size(&h), (50.0, 50.0));
|
||||
|
||||
// A Width the field refuses when the click takes its focus (not a distance, or empty)
|
||||
// is not copied: Height keeps its value.
|
||||
h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("height".into(), json!(30.0));
|
||||
h.run_steps(2);
|
||||
for typed in ["wide", ""] {
|
||||
h.get_by_role_and_label(Role::TextInput, "Width:").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(all, egui::Key::A);
|
||||
if typed.is_empty() {
|
||||
h.key_press(egui::Key::Backspace);
|
||||
} else {
|
||||
h.get_by_role_and_label(Role::TextInput, "Width:").type_text(typed);
|
||||
}
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog_size(&h), (50.0, 30.0), "{typed:?}");
|
||||
}
|
||||
// The field shows its value again, and the next click copies it.
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog_size(&h), (50.0, 50.0));
|
||||
|
||||
// A Height typed and not committed does not outlast the copy: a distance is replaced by
|
||||
// Width, and a Height the field refuses keeps the copy from happening, as it keeps OK from
|
||||
// confirming.
|
||||
for (typed, after) in [("70 pt", (50.0, 50.0)), ("tall", (50.0, 30.0))] {
|
||||
h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("height".into(), json!(30.0));
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::TextInput, "Height:").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(all, egui::Key::A);
|
||||
h.get_by_role_and_label(Role::TextInput, "Height:").type_text(typed);
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(dialog_size(&h), after, "{typed:?}");
|
||||
}
|
||||
|
||||
// Cancel: nothing is drawn.
|
||||
let undo = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.state().session.active().unwrap().history.undo.len();
|
||||
let before = undo(&h);
|
||||
crate::dialogs::cancel(h.state_mut());
|
||||
h.run_steps(2);
|
||||
assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
|
||||
assert_eq!(undo(&h), before);
|
||||
|
||||
// OK: one circle, one undo step.
|
||||
super::super::open_tool_dialog(h.state_mut(), "ellipse", json!({"x": 10.0, "y": 10.0}));
|
||||
h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("width".into(), json!(64.0));
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").click();
|
||||
h.run_steps(2);
|
||||
super::super::confirm(h.state_mut()).unwrap();
|
||||
assert!(h.state().ui.dialog.is_none());
|
||||
assert_eq!(undo(&h), before + 1);
|
||||
let doc = &h.state().session.doc().unwrap().doc;
|
||||
let b = doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap();
|
||||
assert!((b.width() - 64.0).abs() < 1e-6 && (b.height() - 64.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// The Height button works from the keyboard: Space and Enter copy Width into Height, and
|
||||
/// that Enter does not press OK. With the link on, the link stays on and keeps the circle when
|
||||
/// Width is typed next; a Width of 0 is copied and leaves the link no proportions to keep.
|
||||
#[test]
|
||||
fn the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 10.0}));
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("width".into(), json!(80.0));
|
||||
d.fields.insert("height".into(), json!(20.0));
|
||||
d.fields.insert(LINK.into(), json!(true));
|
||||
let mut h = dialog_harness(app);
|
||||
assert_eq!(h.state().ui.dialog.as_ref().unwrap().f64(RATIO, 0.0), 0.25);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Space);
|
||||
h.run_steps(2);
|
||||
assert_eq!(dialog_size(&h), (80.0, 80.0));
|
||||
let d = h.state().ui.dialog.as_ref().unwrap();
|
||||
assert!(d.bool(LINK), "the link stays on");
|
||||
assert_eq!(d.f64(RATIO, 0.0), 1.0);
|
||||
// The link now keeps the circle.
|
||||
retype(&mut h, "Width:", "40 pt");
|
||||
assert_eq!(dialog_size(&h), (40.0, 40.0));
|
||||
|
||||
// Enter on the button copies, and the dialog stays open.
|
||||
h.state_mut().ui.dialog.as_mut().unwrap().fields.insert("width".into(), json!(0.0));
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::Button, "Height:").focus();
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialog.is_some(), "Enter on the Height button does not press OK");
|
||||
assert_eq!(dialog_size(&h), (0.0, 0.0));
|
||||
let d = h.state().ui.dialog.as_ref().unwrap();
|
||||
assert!(d.bool(LINK) && !d.fields.contains_key(RATIO), "no proportions to keep at 0");
|
||||
assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Enter on the focused link button turns the link on and leaves the dialog open, as Space does.
|
||||
#[test]
|
||||
fn enter_on_the_link_button_turns_the_link_on_without_pressing_ok() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
const LINK_NAME: &str = "Constrain Width and Height Proportions";
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, "rectangle", json!({"x": 10.0, "y": 10.0}));
|
||||
let mut h = dialog_harness(app);
|
||||
assert!(!h.state().ui.dialog.as_ref().unwrap().bool(LINK));
|
||||
h.get_by_role_and_label(Role::Button, LINK_NAME).focus();
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
let d = h.state().ui.dialog.as_ref().expect("Enter on the link button does not press OK");
|
||||
assert!(d.bool(LINK));
|
||||
assert!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Rectangle and Rounded Rectangle keep plain Width and Height labels.
|
||||
#[test]
|
||||
fn only_the_ellipse_dialog_has_the_height_button() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for kind in ["rectangle", "roundedRectangle"] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
super::super::open_tool_dialog(&mut app, kind, json!({"x": 10.0, "y": 10.0}));
|
||||
let h = dialog_harness(app);
|
||||
h.get_by_role_and_label(Role::TextInput, "Height:");
|
||||
assert!(h.query_by_role_and_label(Role::Button, "Height:").is_none(), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Width that is missing, empty, not a distance or not finite leaves Height as it is; a
|
||||
/// Width with a unit is copied in points, and 0 is copied.
|
||||
#[test]
|
||||
fn copying_width_takes_only_a_width_that_reads() {
|
||||
for width in [None, Some(json!("")), Some(json!("wide")), Some(json!("inf")), Some(json!(null)), Some(json!(true))] {
|
||||
let mut d = Dialog::new("ellipse", json!({"height": 30.0}));
|
||||
if let Some(w) = width.clone() {
|
||||
d.fields.insert("width".into(), w);
|
||||
}
|
||||
copy_width_to_height(&mut d);
|
||||
assert_eq!(d.fields.get("height"), Some(&json!(30.0)), "{width:?}");
|
||||
}
|
||||
for (width, want) in [(json!("1 in"), 72.0), (json!(0), 0.0), (json!(12.5), 12.5)] {
|
||||
let mut d = Dialog::new("ellipse", json!({"width": width.clone(), "height": 30.0}));
|
||||
copy_width_to_height(&mut d);
|
||||
assert_eq!(d.f64("height", -1.0), want, "{width}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_anchors_take_the_nearest_whole_number_from_2_to_1000() {
|
||||
let d = |v: Value| Dialog::new("ellipse", json!({ "anchors": v }));
|
||||
|
||||
@@ -2524,6 +2524,31 @@ fn flare_options_alt_turns_cancel_into_reset() {
|
||||
);
|
||||
}
|
||||
|
||||
/// While Alt is held, Save PDF's Cancel button reads Reset; Reset puts the chosen preset's settings
|
||||
/// back and leaves the dialog open with its path, letting Alt go shows Cancel again, and Cancel
|
||||
/// closes the dialog.
|
||||
#[test]
|
||||
fn save_pdf_alt_turns_cancel_into_reset() {
|
||||
let mut app = app();
|
||||
app.run("ui.savePdfDialog", json!({"path": "/tmp/alt.pdf"})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("compatibility".into(), json!("1.4"));
|
||||
let mut f = Frames::new();
|
||||
f.button(&mut app, "Cancel");
|
||||
f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::ALT)]);
|
||||
let reset = f.button(&mut app, "Reset");
|
||||
let texts = f.texts(&mut app);
|
||||
assert!(!texts.iter().any(|(t, _)| t == "Cancel"), "Reset takes Cancel's place: {texts:?}");
|
||||
f.press(&mut app, reset, true);
|
||||
f.press(&mut app, reset, false);
|
||||
let d = app.ui.dialog.as_ref().expect("Reset leaves the dialog open");
|
||||
assert_eq!((d.str("compatibility"), d.str("path")), ("1.7".to_string(), "/tmp/alt.pdf".to_string()));
|
||||
f.run(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
|
||||
let cancel = f.button(&mut app, "Cancel");
|
||||
f.press(&mut app, cancel, true);
|
||||
f.press(&mut app, cancel, false);
|
||||
assert!(app.ui.dialog.is_none(), "Cancel closes the dialog");
|
||||
}
|
||||
|
||||
/// While Alt is held, Save for Web's Cancel button reads Reset; Reset puts the remembered settings
|
||||
/// back without remembering anything and leaves the dialog open, and letting Alt go shows Cancel again.
|
||||
#[test]
|
||||
|
||||
@@ -422,6 +422,54 @@ fn a_scale_set_through_the_dialog_keeps_the_percentage_it_changes() {
|
||||
assert_eq!(saved["scale"], json!({"width": 250.0, "height": 250.0, "linked": true}));
|
||||
}
|
||||
|
||||
/// An accessibility action on the node `target_node`.
|
||||
fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId) -> egui::Event {
|
||||
use egui::accesskit::{ActionRequest, TreeId};
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None })
|
||||
}
|
||||
|
||||
/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out.
|
||||
fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) {
|
||||
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
screen.run(app, vec![]);
|
||||
let out = screen.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)));
|
||||
screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]);
|
||||
screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]);
|
||||
screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_set_after_a_typed_percentage_follows_the_link() {
|
||||
let (mut app, _) = app();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
let mut screen = Screen::new();
|
||||
set(&mut app, "scaling", json!("custom"));
|
||||
dialog(&mut app).fields["scale"]["width"] = json!(40);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (40.0, 40.0, true));
|
||||
// W typed with the link on sets H as well.
|
||||
type_w(&mut screen, &mut app, "40", "60");
|
||||
assert_eq!(scale(&mut app), (60.0, 60.0, true));
|
||||
// A new H set before the next frame: W follows it, and Done saves both.
|
||||
dialog(&mut app).fields["scale"]["height"] = json!(50);
|
||||
set(&mut app, "discard", json!(true));
|
||||
super::confirm(&mut app).unwrap();
|
||||
let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap();
|
||||
assert_eq!(saved["scale"], json!({"width": 50.0, "height": 50.0, "linked": true}));
|
||||
// W typed with the link off changes W alone; turning the link on then sets H to W.
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
let (link, _, _) = screen.link(&mut app);
|
||||
screen.run(&mut app, vec![request(egui::accesskit::Action::Click, link)]);
|
||||
assert_eq!(scale(&mut app), (50.0, 50.0, false));
|
||||
type_w(&mut screen, &mut app, "50", "70");
|
||||
assert_eq!(scale(&mut app), (70.0, 50.0, false));
|
||||
screen.run(&mut app, vec![request(egui::accesskit::Action::Click, link)]);
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (70.0, 70.0, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dimmed_scale_link_ignores_the_keyboard() {
|
||||
use egui::accesskit::{Action, ActionRequest, TreeId};
|
||||
@@ -440,3 +488,43 @@ fn the_dimmed_scale_link_ignores_the_keyboard() {
|
||||
screen.run(&mut app, vec![]);
|
||||
assert_eq!(scale(&mut app), (100.0, 100.0, true));
|
||||
}
|
||||
|
||||
/// The node screen readers call `label` with role `role`, and whether it is dimmed.
|
||||
fn node(screen: &mut Screen, app: &mut VectorcraftApp, label: &str, role: egui::accesskit::Role) -> Option<(egui::accesskit::NodeId, bool)> {
|
||||
screen.run(app, vec![]);
|
||||
let out = screen.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
nodes.iter().find(|(_, n)| n.label() == Some(label) && n.role() == role).map(|(id, n)| (*id, n.is_disabled()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_inks_icon_converts_it_to_process_and_back() {
|
||||
use egui::accesskit::{Action, ActionRequest, Role, TreeId};
|
||||
let (mut app, _) = app();
|
||||
app.run("swatch.new", json!({"name": "Gold", "color": {"model": "cmyk", "c": 0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
set(&mut app, "__section", json!("Output"));
|
||||
set(&mut app, "output", json!({"mode": "separations"}));
|
||||
let mut screen = Screen::new();
|
||||
let click = |target_node| {
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node, target_tree: TreeId::ROOT, data: None })
|
||||
};
|
||||
// Only the spot ink has the icon.
|
||||
assert!(node(&mut screen, &mut app, "Convert Cyan to process", Role::Button).is_none());
|
||||
let (convert, dimmed) = node(&mut screen, &mut app, "Convert Gold to process", Role::Button).expect("Gold's icon");
|
||||
assert!(!dimmed);
|
||||
assert_eq!(node(&mut screen, &mut app, "Gold", Role::CheckBox).map(|n| n.1), Some(false));
|
||||
screen.run(&mut app, vec![click(convert)]);
|
||||
assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": true}]));
|
||||
// Converted, it has no plate: its Print box is dimmed, and the icon turns it back.
|
||||
assert_eq!(node(&mut screen, &mut app, "Gold", Role::CheckBox).map(|n| n.1), Some(true));
|
||||
let (keep, _) = node(&mut screen, &mut app, "Keep Gold as spot", Role::Button).expect("the process icon");
|
||||
screen.run(&mut app, vec![click(keep)]);
|
||||
assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}]));
|
||||
// Convert All Spot Colors to Process converts it and dims the icon, keeping its own choice.
|
||||
dialog(&mut app).fields["output"]["spotsToProcess"] = json!(true);
|
||||
let (keep, dimmed) = node(&mut screen, &mut app, "Keep Gold as spot", Role::Button).expect("the process icon");
|
||||
assert!(dimmed);
|
||||
screen.run(&mut app, vec![click(keep)]);
|
||||
assert_eq!(dialog(&mut app).fields["output"]["inks"], json!([{"name": "Gold", "print": true, "convertToProcess": false}]));
|
||||
}
|
||||
@@ -101,13 +101,48 @@ fn text_export_options_write_the_stories() {
|
||||
assert_eq!((path.as_str(), bytes.as_slice()), ("/out/Untitled-1.txt", &b"Hello\r\nthere\r\n"[..]));
|
||||
}
|
||||
|
||||
/// WebP Options: Lossless by default, with the Quality slider disabled; Lossy enables it, and OK
|
||||
/// writes a lossy file at that quality, without a note.
|
||||
#[test]
|
||||
fn webp_options_say_the_file_is_lossless() {
|
||||
let (mut app, _) = app(1);
|
||||
fn webp_options_choose_lossless_or_lossy_at_a_quality() {
|
||||
use crate::widgets::accessibility_tests::tree;
|
||||
use egui::accesskit::Role;
|
||||
let quality_disabled = |app: &mut VectorcraftApp| {
|
||||
let t = tree(|ui| show(app, ui.ctx()));
|
||||
t.iter().find(|n| n.role() == Role::Slider).expect("the Quality slider").is_disabled()
|
||||
};
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "webp"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("webpOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((&d.fields["lossless"], &d.fields["quality"]), (&json!(true), &json!(90)));
|
||||
assert!(quality_disabled(&mut app), "Quality applies to Lossy");
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default");
|
||||
|
||||
app.run("file.exportAs", json!({"format": "webp"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
set(&mut app, "lossless", json!(false));
|
||||
set(&mut app, "quality", json!(40));
|
||||
assert!(!quality_disabled(&mut app), "Lossy enables Quality");
|
||||
frame(&mut app);
|
||||
// The dialog's options, as `document.export` takes them.
|
||||
let mut options = app.ui.dialog.as_ref().unwrap().fields.clone();
|
||||
options.retain(|k, _| !k.starts_with("__") && k != "path");
|
||||
let r = confirm(&mut app).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{r}");
|
||||
let file = written.borrow().last().unwrap().1.clone();
|
||||
assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy");
|
||||
// The file is the one `document.export` writes with those options at quality 40.
|
||||
let at = |app: &mut VectorcraftApp, q: u8| {
|
||||
let mut p = options.clone();
|
||||
p.insert("quality".into(), json!(q));
|
||||
vectorcraft_format::base64_decode(app.run("document.export", serde_json::Value::Object(p)).unwrap()["dataBase64"].as_str().unwrap()).unwrap()
|
||||
};
|
||||
assert_eq!(file, at(&mut app, 40));
|
||||
assert_ne!(file, at(&mut app, 90));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -726,3 +726,192 @@ fn colour_table_buttons_edit_the_lists() {
|
||||
save_for_web::set_table(&mut d, "sort", json!("hue"));
|
||||
assert_eq!(d.fields["colorTable"], json!({"locked": [], "webShift": ["#123456"], "sort": "hue"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_takes_the_settings_that_fit() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-optimize");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "format", json!("jpg"));
|
||||
set(&mut app, "quality", json!(100));
|
||||
frame(&mut app);
|
||||
let full = app.session.execute("document.exportForWeb.preview", &json!({"format": "jpg", "quality": 100})).unwrap()["bytes"].as_u64().unwrap();
|
||||
let field = |app: &VectorcraftApp, k: &str| app.ui.dialog.as_ref().unwrap().fields.get(k).cloned();
|
||||
// A size of 0 is refused: the settings and the rows stay.
|
||||
set(&mut app, "__optimizeK", json!(0));
|
||||
set(&mut app, "__optimizeStart", json!("current"));
|
||||
set(&mut app, "__optimizeGo", json!(true));
|
||||
frame(&mut app);
|
||||
assert_eq!(field(&app, "quality"), Some(json!(100)));
|
||||
assert_eq!(field(&app, "__optimizeK"), Some(json!(0)));
|
||||
assert_eq!((field(&app, "__optimized"), field(&app, "__optimizeGo")), (None, None));
|
||||
// OK takes the settings found and closes the rows.
|
||||
set(&mut app, "__optimizeK", json!(full as f64 * 0.8 / 1024.0));
|
||||
set(&mut app, "__optimizeGo", json!(true));
|
||||
frame(&mut app);
|
||||
let found = field(&app, "__optimized").unwrap();
|
||||
assert_eq!(found["achieved"], json!(true), "{found}");
|
||||
let quality = field(&app, "quality").unwrap().as_u64().unwrap();
|
||||
assert!(quality < 100, "{found}");
|
||||
assert_eq!(field(&app, "__optimizeK"), None);
|
||||
// The result holds for the settings found on the art it measured.
|
||||
let settings = app.session.web_settings(&found["settings"]).unwrap();
|
||||
let shown = |app: &VectorcraftApp| {
|
||||
save_for_web::optimized_result(app.ui.dialog.as_ref().unwrap(), Some(&settings), &save_for_web::art_key(app)).is_some()
|
||||
};
|
||||
assert!(shown(&app));
|
||||
// The result line draws, and Save writes the size found.
|
||||
frame(&mut app);
|
||||
let r = confirm(&mut app).unwrap();
|
||||
let written = std::fs::read(r["path"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(written.len() as u64, found["bytes"].as_u64().unwrap());
|
||||
assert!(written.len() as u64 <= found["targetBytes"].as_u64().unwrap());
|
||||
assert_eq!(app.session.last_web_settings().quality as u64, quality);
|
||||
// A change to the art drops the result.
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), found.clone());
|
||||
assert!(shown(&app));
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
assert!(!shown(&app));
|
||||
// So does a change to the selection, which decides the slices Save writes with `slices: selected`,
|
||||
// also one that leaves the revision as it is (a click on the canvas).
|
||||
let mut current = found.clone();
|
||||
current["art"] = json!(save_for_web::art_key(&app));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), current);
|
||||
assert!(shown(&app));
|
||||
let st = app.session.active_mut().unwrap();
|
||||
assert!(!st.selection.objects.is_empty());
|
||||
st.selection.objects.clear();
|
||||
assert!(!shown(&app));
|
||||
// And a change to the selected slices alone (the Slice Selection tool).
|
||||
let mut current = found.clone();
|
||||
current["art"] = json!(save_for_web::art_key(&app));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("__optimized".into(), current);
|
||||
assert!(shown(&app));
|
||||
let st = app.session.active_mut().unwrap();
|
||||
let any = st.doc.layers[0].id;
|
||||
st.selection.slices.push(any);
|
||||
assert!(!shown(&app));
|
||||
}
|
||||
|
||||
/// Enter while the Optimize to File Size rows are open runs the search and writes nothing; once the
|
||||
/// search has closed the rows, Enter saves with the settings it found.
|
||||
#[test]
|
||||
fn enter_in_the_optimize_rows_runs_the_search_and_saves_nothing() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-optimize-enter");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "format", json!("jpg"));
|
||||
set(&mut app, "quality", json!(100));
|
||||
frame(&mut app);
|
||||
let full = app.session.execute("document.exportForWeb.preview", &json!({"format": "jpg", "quality": 100})).unwrap()["bytes"].as_u64().unwrap();
|
||||
set(&mut app, "__optimizeK", json!(full as f64 * 0.8 / 1024.0));
|
||||
set(&mut app, "__optimizeStart", json!("current"));
|
||||
let files = |dir: &std::path::Path| std::fs::read_dir(dir).map_or(0, |r| r.count());
|
||||
let enter_with = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| {
|
||||
let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput { events: vec![key], ..Default::default() }, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
};
|
||||
let enter = |app: &mut VectorcraftApp| enter_with(app, egui::Modifiers::NONE);
|
||||
// Ctrl+Enter, which the size field does not commit, neither searches nor saves.
|
||||
enter_with(&mut app, egui::Modifiers::CTRL);
|
||||
frame(&mut app);
|
||||
assert_eq!(kind(&app), Some(save_for_web::KIND), "Ctrl+Enter in the rows does not save");
|
||||
assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("__optimizeK"), "the rows stay open");
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("__optimized"));
|
||||
assert_eq!(files(&dir), 0);
|
||||
enter(&mut app);
|
||||
assert_eq!(kind(&app), Some(save_for_web::KIND), "Enter in the rows does not save");
|
||||
assert_eq!(files(&dir), 0);
|
||||
frame(&mut app);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
let found = d.fields.get("__optimized").cloned().unwrap();
|
||||
assert_eq!(found["achieved"], json!(true), "{found}");
|
||||
assert!(!d.fields.contains_key("__optimizeK"), "the search closed the rows");
|
||||
enter(&mut app);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(files(&dir), 1);
|
||||
}
|
||||
|
||||
/// An Enter in the Optimize to File Size rows runs no search when a field of the dialog, one drawn
|
||||
/// after the rows included, refused the value typed in it on that press, or when a control drawn
|
||||
/// after the rows (an open dropdown) took the press.
|
||||
#[test]
|
||||
fn enter_in_the_optimize_rows_runs_nothing_when_a_later_control_refused_or_took_it() {
|
||||
// `before` stands for the controls drawn after the rows, which act on the press first.
|
||||
let go = |before: fn(&egui::Context)| {
|
||||
let mut d = Dialog::new(save_for_web::KIND, json!({"__optimizeK": 10}));
|
||||
let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
let ctx = egui::Context::default();
|
||||
let mut out = ctx.run_ui(egui::RawInput { events: vec![key], ..Default::default() }, |ui| {
|
||||
before(ui.ctx());
|
||||
save_for_web::optimize_on_enter(ui.ctx(), &mut d);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert!(d.fields.contains_key("__optimizeK"), "the rows stay open");
|
||||
d.fields.contains_key("__optimizeGo")
|
||||
};
|
||||
assert!(go(|_| {}), "a plain Enter runs the search");
|
||||
assert!(!go(crate::widgets::reject_dialog_commit), "a refused value runs nothing");
|
||||
assert!(!go(|ctx| ctx.input_mut(|i| _ = i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))), "a taken press runs nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_starts_at_the_size_of_the_slices_files() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-optimize-slices");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("object.slice.create", json!({"x": 0, "y": 0, "width": 30, "height": 20})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "format", json!("png24"));
|
||||
frame(&mut app);
|
||||
let slices = app.session.execute("webExport.optimizeToFileSize", &json!({"format": "png24", "desiredK": 1048576})).unwrap();
|
||||
let whole = app.session.execute("document.exportForWeb.preview", &json!({"format": "png24"})).unwrap()["bytes"].as_u64().unwrap();
|
||||
let k = |b: u64| json!(save_for_web::size_k(b as usize));
|
||||
assert_ne!(k(slices["bytes"].as_u64().unwrap()), k(whole), "{slices}");
|
||||
// The size asked for holds the files measured.
|
||||
let b = slices["bytes"].as_u64().unwrap();
|
||||
assert!((save_for_web::size_k(b as usize) * 1024.0).floor() as u64 >= b);
|
||||
set(&mut app, "__optimizeOpen", json!(true));
|
||||
frame(&mut app);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.fields.get("__optimizeK"), Some(&k(slices["bytes"].as_u64().unwrap())));
|
||||
assert_eq!((d.fields.get("__optimizeUse"), d.fields.get("__optimizeOpen")), (Some(&json!("allSlices")), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimize_to_file_size_starts_at_the_size_of_the_art_as_it_is_now() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-optimize-revision");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
// One context for every frame, so the preview cache of the first frame is still there.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let frame = |app: &mut VectorcraftApp| ctx.run_ui(Default::default(), |ui| show(app, ui.ctx())).textures_delta.clear();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "format", json!("png24"));
|
||||
frame(&mut app);
|
||||
let bytes = |app: &mut VectorcraftApp| {
|
||||
app.session.execute("document.exportForWeb.preview", &json!({"format": "png24"})).unwrap()["bytes"].as_u64().unwrap()
|
||||
};
|
||||
let before = bytes(&mut app);
|
||||
// The art changes after the preview drew and before the button's click is handled.
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 60, "height": 40})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#3366ff"})).unwrap();
|
||||
let after = bytes(&mut app);
|
||||
assert_ne!(save_for_web::size_k(before as usize), save_for_web::size_k(after as usize));
|
||||
set(&mut app, "__optimizeOpen", json!(true));
|
||||
frame(&mut app);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.fields.get("__optimizeK"), Some(&json!(save_for_web::size_k(after as usize))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_in_k_holds_sizes_past_4_mib_on_every_target() {
|
||||
assert_eq!(save_for_web::size_k(5 * 1024 * 1024), 5120.0);
|
||||
assert_eq!(save_for_web::size_k(0), 0.001);
|
||||
assert_eq!(save_for_web::size_k(1), 0.001);
|
||||
// The largest size a target can hold still rounds up to a size that holds it.
|
||||
assert!(save_for_web::size_k(usize::MAX) * 1024.0 >= usize::MAX as f64 * 0.999);
|
||||
}
|
||||
@@ -683,8 +683,10 @@ const MESSAGE_DEPTH: usize = 5;
|
||||
/// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as
|
||||
/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a
|
||||
/// symbol's or a script property's name, and an `{ident}` placeholder's value, a script identifier),
|
||||
/// stay as they are. A part that starts with `{` is translated only when it is a whole message with
|
||||
/// an exact entry. A part that starts with `[` is translated when it has an exact entry, such as
|
||||
/// stay as they are. A `{to}` placeholder's value that is not quoted, a printer's name such as
|
||||
/// `Office Laser (Floor 2)`, is translated only when it has an exact entry, such as
|
||||
/// `the default printer`. A part that starts with `{` is translated only when it is a whole message
|
||||
/// with an exact entry. A part that starts with `[` is translated when it has an exact entry, such as
|
||||
/// `[x, y] (two numbers)`, or when it fits a template that starts with `[` and an index of digits,
|
||||
/// such as an effect's refusal ``[0] `id`: {why}``.
|
||||
pub fn message(lang: Lang, s: &str) -> String {
|
||||
@@ -727,6 +729,7 @@ fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures
|
||||
(Some((tool, _)), "_1") => (k, tool.clone()),
|
||||
(Some((_, kinds)), "_2") => (k, kinds.clone()),
|
||||
(_, "ident") => (k, v.to_string()),
|
||||
(_, "to") if !quoted(v) => (k, exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())),
|
||||
_ => (k, nested(v)),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user