diff --git a/Cargo.lock b/Cargo.lock index 9e03100ede..7b0de73006 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", ] diff --git a/Cargo.toml b/Cargo.toml index 9cb9a3a7d2..6d2ab9e37b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index adc52f9d8c..4f8e326981 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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!( diff --git a/apps/vectorcraft/src/presentation.rs b/apps/vectorcraft/src/presentation.rs index 3910984c93..7c2f1dc48a 100644 --- a/apps/vectorcraft/src/presentation.rs +++ b/apps/vectorcraft/src/presentation.rs @@ -54,6 +54,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator) -> 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() } diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 74e05e698f..db3518c26e 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -9,9 +9,8 @@ impl PrintService for SystemPrint { system::printers() } fn print(&mut self, job: &PrintJob) -> Result { - 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 { 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 { @@ -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")); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 8bdff7103d..2cca6e264d 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -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 => { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index c7c3e408b4..f8b62ac815 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { 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], 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], spec: &BlendSpec) -> Vec { @@ -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)); + } } diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5bd31f7699..c556f2f5b0 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -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 { - 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 { 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; diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index c5d3d70fd2..932527a397 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "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 { 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 { 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| { let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index b9015a4cc7..05dae578ce 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "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 { "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 ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 9ca565667d..241d252816 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -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 { 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 { let mapped_pts: Vec = 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| { let path = match tol { Some(tol) => PathData::single(fit_freehand(&pts, tol, false)), diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ea6aaa7ffc..adc73c2c85 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "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., 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 .html / .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 mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{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., 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 .html / .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-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 mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "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 for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,