diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 31b5493c..1747cd00 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -28,6 +28,7 @@ pub mod publish; pub mod sample; pub mod templates; pub mod sound; +pub mod swatch; pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png}; @@ -40,6 +41,7 @@ pub use sound::{EnvelopePoint, FrameSound, Sound, SoundEffect, SoundFormat, Soun pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile}; pub use stroke_style::{Cap, Dash, DashKind, Join, StrokeStyle}; pub use camera::Camera; +pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint}; pub use nine_slice::symbol_box; pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose}; pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start}; @@ -1655,10 +1657,22 @@ pub struct Document { /// File › Publish Settings: the formats Publish writes and their options (ADR 0060). #[serde(default, skip_serializing_if = "publish_is_default")] pub publish: Arc, + /// The Swatches panel's colours and gradients (ADR 0078). A file without them opens with + /// the default set, which is written only once changed. + #[serde(default = "default_swatches", skip_serializing_if = "swatches_are_default")] + pub swatches: Arc>, /// Next free id for layers, elements and symbols. pub next_id: u64, } +fn default_swatches() -> Arc> { + Arc::new(swatch::default_set()) +} + +fn swatches_are_default(v: &Arc>) -> bool { + swatch::is_default_set(v) +} + /// What a document file may hold: `scenes`, or (files before scenes) a single `timeline`. #[derive(Deserialize)] struct DocumentFile { @@ -1680,6 +1694,8 @@ struct DocumentFile { document_class: String, #[serde(default)] publish: Arc, + #[serde(default = "default_swatches")] + swatches: Arc>, #[serde(default = "first_id")] next_id: u64, } @@ -1690,7 +1706,7 @@ impl From for Document { if let Some(tl) = f.timeline { scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl })); } - Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, next_id: f.next_id } + Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, swatches: f.swatches, next_id: f.next_id } } } @@ -1711,13 +1727,13 @@ static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() }; impl PartialEq for Document { fn eq(&self, o: &Document) -> bool { - self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) + self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.swatches, &o.swatches) } } impl Default for Document { fn default() -> Self { - let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), next_id: 1 }; + let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), swatches: default_swatches(), next_id: 1 }; let id = LayerId(d.alloc_id()); d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1"))); d @@ -1831,6 +1847,11 @@ impl Document { if !self.document_class.is_empty() && !actions::valid_class_name(&self.document_class) { self.document_class.clear(); } + // Swatches that can't be repaired are dropped; at most MAX_SWATCHES are kept. + let swatches: Vec = self.swatches.iter().filter_map(Swatch::sanitized).take(MAX_SWATCHES).collect(); + if swatches != *self.swatches { + self.swatches = Arc::new(swatches); + } let mut publish = (*self.publish).clone(); publish.sanitize(); if publish != *self.publish { diff --git a/crates/doc/src/sample.rs b/crates/doc/src/sample.rs index 4b8de311..5299f44b 100644 --- a/crates/doc/src/sample.rs +++ b/crates/doc/src/sample.rs @@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec>, tween: Option Document { - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; let (w, h) = (1280.0, 720.0); // --- library ------------------------------------------------------------------------- @@ -147,7 +147,7 @@ pub fn demo() -> Document { /// whose last frame traces a line and goes back to the menu. pub fn interactive() -> Document { use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target}; - let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; const LEN: u32 = 36; let solid = |c: u32| Paint::Solid(Rgba::hex(c)); @@ -211,7 +211,7 @@ pub fn interactive() -> Document { /// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens. /// Every element keeps one `Arc` across its keyframes, as a real tweened shape does. pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document { - let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: 1 }; + let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 }; let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000)); let mut seed = 0x2545_f491_u32; let mut rnd = move || { diff --git a/crates/doc/src/swatch.rs b/crates/doc/src/swatch.rs new file mode 100644 index 00000000..53521829 --- /dev/null +++ b/crates/doc/src/swatch.rs @@ -0,0 +1,266 @@ +//! The document's swatches (ADR 0078): saved colours and gradients, as Animate keeps them per +//! document in its Swatches panel. +//! +//! A swatch is a colour (with alpha) or a gradient's ramp and options, never its geometry: a +//! gradient swatch poured on a shape is fitted to it, as a new gradient is. A new document +//! starts with [`default_set`]; a document file that has no swatches (every file before ADR +//! 0078) opens with that set too, and the set is not written while it is unchanged. +//! +//! GIMP palettes (`.gpl`, an open plain-text format) import through [`parse_gpl`]. + +use crate::{GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, is_false, is_zero}; +use serde::{Deserialize, Serialize}; + +/// Most swatches a document keeps (Animate's panel holds a few hundred at most). +pub const MAX_SWATCHES: usize = 1024; +/// Longest swatch name, in characters. +pub const MAX_SWATCH_NAME: usize = 128; + +/// One saved colour or gradient. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Swatch { + /// Shown on hover (empty: the colour's hex). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub name: String, + pub paint: SwatchPaint, +} + +/// What a swatch holds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SwatchPaint { + Solid { + color: Rgba, + }, + Linear { + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + }, + Radial { + stops: Vec, + #[serde(default, skip_serializing_if = "Spread::is_pad")] + spread: Spread, + #[serde(default, skip_serializing_if = "is_false")] + linear_rgb: bool, + #[serde(default, skip_serializing_if = "is_zero")] + focal: f32, + }, +} + +impl SwatchPaint { + /// The swatch of a fill: its colour, or its gradient's ramp and options (where it lies is + /// left behind). `None` for a bitmap fill, which a swatch can't hold. + pub fn from_paint(p: &Paint) -> Option { + match p { + Paint::Solid(c) => Some(SwatchPaint::Solid { color: *c }), + Paint::Linear { stops, spread, linear_rgb, .. } => Some(SwatchPaint::Linear { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb }), + Paint::Radial { stops, spread, linear_rgb, focal, .. } => Some(SwatchPaint::Radial { stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal }), + Paint::Bitmap { .. } => None, + } + } + + /// Its colour, or its gradient's first stop. + pub fn primary_color(&self) -> Rgba { + match self { + SwatchPaint::Solid { color } => *color, + SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => stops.first().map_or(Rgba::BLACK, |s| s.color), + } + } + + pub fn stops(&self) -> Option<&[GradientStop]> { + match self { + SwatchPaint::Solid { .. } => None, + SwatchPaint::Linear { stops, .. } | SwatchPaint::Radial { stops, .. } => Some(stops), + } + } + + pub fn is_gradient(&self) -> bool { + !matches!(self, SwatchPaint::Solid { .. }) + } + + /// The key `paint.set_fill` and swatch files use for its kind. + pub fn kind(&self) -> &'static str { + match self { + SwatchPaint::Solid { .. } => "solid", + SwatchPaint::Linear { .. } => "linear", + SwatchPaint::Radial { .. } => "radial", + } + } + + /// Repaired: colours in range, 2 to [`MAX_GRADIENT_STOPS`] stops in order, the focal point + /// in range. `None` when it can't be (a gradient with fewer than two stops). + pub fn sanitized(&self) -> Option { + let stops = |s: &[GradientStop]| -> Option> { + if s.len() < 2 { + return None; + } + let mut v: Vec = s.iter().take(MAX_GRADIENT_STOPS).map(|g| GradientStop { offset: if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 }, color: g.color.sanitized() }).collect(); + v.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + Some(v) + }; + Some(match self { + SwatchPaint::Solid { color } => SwatchPaint::Solid { color: color.sanitized() }, + SwatchPaint::Linear { stops: s, spread, linear_rgb } => SwatchPaint::Linear { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb }, + SwatchPaint::Radial { stops: s, spread, linear_rgb, focal } => SwatchPaint::Radial { stops: stops(s)?, spread: *spread, linear_rgb: *linear_rgb, focal: if focal.is_finite() { focal.clamp(-MAX_FOCAL, MAX_FOCAL) } else { 0.0 } }, + }) + } +} + +impl Swatch { + pub fn new(name: &str, paint: SwatchPaint) -> Swatch { + Swatch { name: clean_name(name), paint } + } + pub fn solid(c: Rgba) -> Swatch { + Swatch { name: String::new(), paint: SwatchPaint::Solid { color: c } } + } + /// Repaired (see [`SwatchPaint::sanitized`]), its name trimmed and bounded. + pub fn sanitized(&self) -> Option { + Some(Swatch { name: clean_name(&self.name), paint: self.paint.sanitized()? }) + } +} + +/// A swatch name: one line, trimmed, at most [`MAX_SWATCH_NAME`] characters. +pub fn clean_name(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_SWATCH_NAME).collect::().trim().to_string() +} + +fn stop(offset: f32, rgb: u32) -> GradientStop { + GradientStop { offset, color: Rgba::hex(rgb) } +} + +/// A new document's swatches: greys from black to white, the primaries and secondaries (the +/// picker's web-safe palette has the rest), then seven gradients. +pub fn default_set() -> Vec { + let colours = [0x000000, 0x333333, 0x666666, 0x999999, 0xcccccc, 0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0x00ffff, 0xff00ff]; + let mut v: Vec = colours.iter().map(|c| Swatch::solid(Rgba::hex(*c))).collect(); + let linear = |stops| SwatchPaint::Linear { stops, spread: Spread::Pad, linear_rgb: false }; + let radial = |stops| SwatchPaint::Radial { stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0 }; + v.extend([ + Swatch::new("Black to white", linear(vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)])), + Swatch::new("White to black", radial(vec![stop(0.0, 0xffffff), stop(1.0, 0x000000)])), + Swatch::new("Red ball", radial(vec![stop(0.0, 0xff8080), stop(1.0, 0x990000)])), + Swatch::new("Green ball", radial(vec![stop(0.0, 0x80ff80), stop(1.0, 0x006600)])), + Swatch::new("Blue ball", radial(vec![stop(0.0, 0x80b0ff), stop(1.0, 0x000099)])), + Swatch::new("Spectrum", linear(vec![stop(0.0, 0xff0000), stop(0.2, 0xffff00), stop(0.4, 0x00ff00), stop(0.6, 0x00ffff), stop(0.8, 0x0000ff), stop(1.0, 0xff00ff)])), + Swatch::new("Gold", linear(vec![stop(0.0, 0xfff2a8), stop(0.5, 0xd4a017), stop(1.0, 0x7a5200)])), + ]); + v +} + +/// Whether `v` is exactly the default set (then a document file leaves it out). +pub fn is_default_set(v: &[Swatch]) -> bool { + let d = default_set(); + v.len() == d.len() && v.iter().zip(&d).all(|(a, b)| a == b) +} + +/// Largest palette file read, in bytes. +pub const MAX_PALETTE_BYTES: usize = 1 << 20; + +/// Reads a GIMP palette (`.gpl`): a `GIMP Palette` line, optional `Name:` and `Columns:` +/// lines and `#` comments, then one colour per line, `R G B` (0 to 255) and an optional name. +/// Lines that aren't colours are skipped; at most [`MAX_SWATCHES`] colours are read. The +/// palette's own name comes back with the colours. +pub fn parse_gpl(text: &str) -> Result<(String, Vec), String> { + if text.len() > MAX_PALETTE_BYTES { + return Err("the palette file is too large".into()); + } + let mut lines = text.lines(); + let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); + if first != "GIMP Palette" { + return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); + } + let mut name = String::new(); + let mut out = Vec::new(); + for line in lines { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(n) = l.strip_prefix("Name:") { + name = clean_name(n); + continue; + } + if l.starts_with("Columns:") || l.starts_with("Channels:") { + continue; + } + let mut parts = l.split_whitespace(); + let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| f32::from(v) / 255.0); + let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; + let rest: Vec<&str> = parts.collect(); + let label = rest.join(" "); + // GIMP names unnamed colours "Untitled"; the hex says more. + let label = if label == "Untitled" { String::new() } else { label }; + out.push(Swatch::new(&label, SwatchPaint::Solid { color: Rgba::new(r, g, b, 1.0) })); + if out.len() >= MAX_SWATCHES { + break; + } + } + if out.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok((name, out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_set_is_valid_and_recognised() { + let d = default_set(); + assert_eq!(d.len(), 19); + assert!(is_default_set(&d)); + assert!(d.iter().all(|s| s.sanitized().as_ref() == Some(s)), "nothing to repair"); + assert_eq!(d.iter().filter(|s| s.paint.is_gradient()).count(), 7); + let mut other = d.clone(); + other.swap(0, 1); + assert!(!is_default_set(&other)); + assert!(!is_default_set(&[])); + } + + #[test] + fn swatches_are_repaired() { + let bad = Swatch { name: " a\nb ".into(), paint: SwatchPaint::Radial { stops: vec![GradientStop { offset: 2.0, color: Rgba::new(f32::NAN, 9.0, -1.0, 1.0) }, GradientStop { offset: -1.0, color: Rgba::WHITE }], spread: Spread::Pad, linear_rgb: false, focal: 5.0 } }; + let s = bad.sanitized().unwrap(); + assert_eq!(s.name, "ab"); + let SwatchPaint::Radial { stops, focal, .. } = &s.paint else { panic!() }; + assert_eq!((stops[0].offset, stops[1].offset), (0.0, 1.0), "in order and in range"); + assert_eq!(stops[1].color, Rgba::new(0.0, 1.0, 0.0, 1.0)); + assert_eq!(*focal, MAX_FOCAL); + let one = Swatch { name: String::new(), paint: SwatchPaint::Linear { stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }], spread: Spread::Pad, linear_rgb: false } }; + assert!(one.sanitized().is_none(), "a gradient needs two stops"); + assert_eq!(clean_name(&"x".repeat(500)).chars().count(), MAX_SWATCH_NAME); + } + + #[test] + fn a_swatch_keeps_a_fills_ramp_not_its_geometry() { + let p = Paint::linear(crate::Vec2::new(5.0, 5.0), crate::Vec2::new(50.0, 5.0), vec![stop(0.0, 0xff0000), stop(1.0, 0x0000ff)]); + let s = SwatchPaint::from_paint(&p).unwrap(); + assert_eq!(s.kind(), "linear"); + assert_eq!(s.primary_color(), Rgba::hex(0xff0000)); + assert!(SwatchPaint::from_paint(&Paint::Bitmap { bitmap: crate::BitmapId(1), repeat: true, matrix: crate::Affine::IDENTITY }).is_none()); + } + + #[test] + fn gimp_palettes_are_read() { + let text = "GIMP Palette\nName: Brand\nColumns: 4\n# a comment\n255 0 0\tCrimson red\n 0 128 255 Untitled\n300 0 0 too bright\nnot a colour\n\n10 20 30\n"; + let (name, sw) = parse_gpl(text).unwrap(); + assert_eq!(name, "Brand"); + assert_eq!(sw.len(), 3); + assert_eq!(sw[0].name, "Crimson red"); + assert_eq!(sw[0].paint, SwatchPaint::Solid { color: Rgba::hex(0xff0000) }); + assert_eq!(sw[1].name, "", "GIMP's Untitled shows as the hex"); + assert_eq!(sw[2].paint.primary_color().to_hex(), "#0a141e"); + // A byte-order mark and Windows line ends are fine. + assert!(parse_gpl("\u{feff}GIMP Palette\r\n1 2 3\r\n").is_ok()); + for bad in ["", "JASC-PAL\n0 0 0", "GIMP Palette\nName: empty\n", "GIMP Palette\n1 2\n"] { + assert!(parse_gpl(bad).is_err(), "{bad:?}"); + } + let many = format!("GIMP Palette\n{}", "1 2 3\n".repeat(MAX_SWATCHES + 10)); + assert_eq!(parse_gpl(&many).unwrap().1.len(), MAX_SWATCHES, "bounded"); + assert!(parse_gpl(&"x".repeat(MAX_PALETTE_BYTES + 1)).is_err()); + } +} diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index be012bf2..1e16b069 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -378,7 +378,7 @@ fn set_fill(s: &mut Session, p: &Value) -> Result { Ok(json!({"ok": true})) } -fn set_stroke(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_stroke(s: &mut Session, p: &Value) -> Result { let remove = p.get("color").is_some_and(Value::is_null); let color = opt_color(p, "color")?; let width = opt_f32(p, "width")?; diff --git a/crates/engine/src/cmds_paint.rs b/crates/engine/src/cmds_paint.rs index 4913d64c..e53f2ca6 100644 --- a/crates/engine/src/cmds_paint.rs +++ b/crates/engine/src/cmds_paint.rs @@ -479,7 +479,7 @@ fn default_stops() -> Vec { } /// The `stops` param: 2 to 15 stops, each `{offset, color}`, put in order of offset. -fn opt_stops(p: &Value) -> Result>> { +pub(crate) fn opt_stops(p: &Value) -> Result>> { let bad = || EngineError::Param(format!("param 'stops' must be a list of 2 to {MAX_GRADIENT_STOPS} stops like {{\"offset\": 0.5, \"color\": \"#ff8800\"}}")); let list = match p.get("stops") { None | Some(Value::Null) => return Ok(None), @@ -596,7 +596,7 @@ pub fn fill_json(p: &Paint) -> Value { } } -fn opt_focal(p: &Value) -> Result> { +pub(crate) fn opt_focal(p: &Value) -> Result> { let f = opt_f32(p, "focal")?; if f.is_some_and(|f| !(-MAX_FOCAL..=MAX_FOCAL).contains(&f)) { return Err(EngineError::Param(format!("param 'focal' must be between -{MAX_FOCAL} and {MAX_FOCAL}"))); @@ -605,7 +605,7 @@ fn opt_focal(p: &Value) -> Result> { } /// `paint.set_fill`: the Colour panel's fill (type, stops, overflow, linear RGB, bitmap). -fn set_fill(s: &mut Session, p: &Value) -> Result { +pub(crate) fn set_fill(s: &mut Session, p: &Value) -> Result { let swatch = s.style.fill_paint(); let kind = match opt_str(p, "type")? { None => fill_kind(&swatch), diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 6604d7ef..1fff91c9 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -47,6 +47,9 @@ pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> { // user's own brushes are their preferences, and a brush set is a file. "brush" if id == "brush.preset_list" => Ok(()), "brush" => Err("plug-ins can't change your brushes or read and write brush sets"), + // The document's swatches are document data; swatch files are files. + "swatch" if matches!(id, "swatch.import" | "swatch.export") => Err("plug-ins can't read or write swatch files"), + "swatch" => Ok(()), "plugin" => Err("plug-ins can't install, run or remove plug-ins"), "control" => Err("plug-ins can't play the movie"), ns if DOCUMENT.contains(&ns) => Ok(()), diff --git a/crates/engine/src/cmds_swatch.rs b/crates/engine/src/cmds_swatch.rs new file mode 100644 index 00000000..01697060 --- /dev/null +++ b/crates/engine/src/cmds_swatch.rs @@ -0,0 +1,302 @@ +//! The Swatches panel's commands (ADR 0078): the document's saved colours and gradients. +//! +//! Swatches live in the document (`Document::swatches`), so every change here is an undo step +//! and is saved with the file, as Animate keeps them per document. Applying a swatch is +//! `paint.set_fill` (fill) or `element.set_stroke` (stroke) underneath, so the selection and +//! the tool colour change exactly as they do from the Colour panel. +//! +//! A swatch set moves between documents and computers as a small JSON file +//! (`swatch.export` / `swatch.import`); GIMP palettes (`.gpl`, an open plain-text format) +//! import too. Adobe's `.aco`, `.ase` and `.clr` formats are proprietary and not read. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::swatch::{MAX_PALETTE_BYTES, clean_name, default_set, parse_gpl}; +use anicraft_doc::{GradientStop, MAX_SWATCHES, Rgba, Spread, Swatch, SwatchPaint}; +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, params, mutates, run| CommandSpec { id, label, menu: "", shortcut: None, params, mutates, run }; + vec![ + c("swatch.list", "Swatches", "{} the document's swatches, in the Swatches panel's order → {swatches: [{index, name, type, color | stops, ..}], count}", false, list as crate::RunFn), + c( + "swatch.add", + "Add Swatch", + "{from?: fill|stroke (default fill: the fill swatch's colour or gradient; stroke: the stroke colour), or the swatch itself: type?: solid|linear|radial, color? (\"#rrggbb\" | \"#rrggbbaa\", solid), stops?: [{offset: 0..1, color}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial); name?, at? (index; default: the end)} → {index, count}", + true, + add, + ), + c("swatch.remove", "Delete Swatch", "{index} → {count}", true, remove), + c("swatch.move", "Move Swatch", "{from, to} (indices: the swatch at `from` ends up at `to`) → {index}", true, move_swatch), + c("swatch.duplicate", "Duplicate Swatch", "{index} puts a copy right after it → {index, count}", true, duplicate), + c("swatch.rename", "Rename Swatch", "{index, name} (empty: no name, the hex shows on hover)", true, rename), + c( + "swatch.apply", + "Apply Swatch", + "{index, target?: fill|stroke (default fill), selection?: bool (default true)} sets the fill swatch (as paint.set_fill: a gradient is fitted to each shape) or the stroke colour, and unless `selection` is false the selected shapes' fills or strokes. A gradient swatch can't be a stroke (strokes are one colour) → {target, changed}", + true, + apply, + ), + c("swatch.clear", "Clear Swatches", "{} removes every swatch but black and white (Animate's Clear Colors; undoable)", true, clear), + c("swatch.reset", "Default Swatches", "{} replaces the swatches with a new document's set (undoable)", true, reset), + c("swatch.import", "Import Swatches", "{path: a swatch file (.json, from swatch.export) or a GIMP palette (.gpl), replace?: bool (default false: added at the end)} → {imported, count}", true, import), + c("swatch.export", "Export Swatches", "{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}", false, export), + ] +} + +/// `#rrggbb`, or `#rrggbbaa` when not opaque. +pub fn hex(c: Rgba) -> String { + let c = c.sanitized(); + if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) } +} + +fn stops_json(stops: &[GradientStop]) -> Value { + json!(stops.iter().map(|s| json!({"offset": s.offset, "color": hex(s.color)})).collect::>()) +} + +/// A swatch as commands and swatch files write it. +pub fn swatch_json(s: &Swatch) -> Value { + let mut v = match &s.paint { + SwatchPaint::Solid { color } => json!({"type": "solid", "color": hex(*color)}), + SwatchPaint::Linear { stops, spread, linear_rgb } => json!({"type": "linear", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb}), + SwatchPaint::Radial { stops, spread, linear_rgb, focal } => json!({"type": "radial", "stops": stops_json(stops), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}), + }; + if !s.name.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("name".into(), json!(s.name)); + } + v +} + +/// A swatch from its JSON (see `swatch.add`). `None` when `v` names no paint (no type, colour +/// or stops), so the caller can fall back to the current one. +pub fn swatch_from_json(v: &Value) -> Result> { + let kind = opt_str(v, "type")?; + let color = opt_color(v, "color")?; + let stops = crate::cmds_paint::opt_stops(v)?; + let spread = match opt_str(v, "spread")? { + None => Spread::Pad, + Some(k) => Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?, + }; + let linear_rgb = opt_bool(v, "linear_rgb")?.unwrap_or(false); + let focal = crate::cmds_paint::opt_focal(v)?.unwrap_or(0.0); + let kind = match (kind, &color, &stops) { + (None, None, None) => return Ok(None), + (Some(k), ..) => k, + (None, _, Some(_)) => "linear", + (None, Some(_), None) => "solid", + }; + let need_stops = || stops.clone().ok_or_else(|| EngineError::Param(format!("a {kind} swatch needs 'stops' (2 to 15 like {{\"offset\": 0, \"color\": \"#ff0000\"}})"))); + let paint = match kind { + "solid" => SwatchPaint::Solid { color: color.ok_or_else(|| EngineError::Param("a solid swatch needs 'color' (like \"#ff8800\")".into()))? }, + "linear" => SwatchPaint::Linear { stops: need_stops()?, spread, linear_rgb }, + "radial" => SwatchPaint::Radial { stops: need_stops()?, spread, linear_rgb, focal }, + other => return Err(EngineError::Param(format!("unknown swatch type '{other}' (solid, linear or radial)"))), + }; + let name = opt_str(v, "name")?.unwrap_or(""); + Swatch::new(name, paint).sanitized().map(Some).ok_or_else(|| EngineError::Param("that swatch can't be kept (a gradient needs two stops)".into())) +} + +fn index_param(s: &Session, p: &Value, key: &str) -> Result { + let n = s.doc.swatches.len(); + let i = opt_u64(p, key)?.ok_or_else(|| EngineError::Param(format!("param '{key}' is required (a swatch's index)")))?; + usize::try_from(i).ok().filter(|i| *i < n).ok_or_else(|| if n == 0 { EngineError::State("the document has no swatches".into()) } else { EngineError::Param(format!("param '{key}' must be a swatch index, 0 to {}", n - 1)) }) +} + +fn swatches_mut(s: &mut Session) -> &mut Vec { + Arc::make_mut(&mut s.doc.swatches) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let v: Vec = s + .doc + .swatches + .iter() + .enumerate() + .map(|(i, sw)| { + let mut j = swatch_json(sw); + if let Some(o) = j.as_object_mut() { + o.insert("index".into(), json!(i)); + } + j + }) + .collect(); + Ok(json!({"count": v.len(), "swatches": v})) +} + +/// The swatch `swatch.add` makes from the current colours: the fill swatch, or the stroke. +fn current(s: &Session, from: &str) -> Result { + match from { + "fill" => SwatchPaint::from_paint(&s.style.fill_paint()).map(|p| Swatch { name: String::new(), paint: p }).ok_or_else(|| EngineError::State("a bitmap fill can't be a swatch (swatches hold colours and gradients)".into())), + "stroke" => Ok(Swatch::solid(s.style.stroke)), + other => Err(EngineError::Param(format!("param 'from' must be fill or stroke, not '{other}'"))), + } +} + +fn add(s: &mut Session, p: &Value) -> Result { + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let mut sw = match (opt_str(p, "from")?, swatch_from_json(p)?) { + (Some(_), Some(_)) => return Err(EngineError::Param("give either 'from' or the swatch's own type, colour or stops, not both".into())), + (None, Some(sw)) => sw, + (from, None) => current(s, from.unwrap_or("fill"))?, + }; + if let Some(n) = opt_str(p, "name")? { + sw.name = clean_name(n); + } + let n = s.doc.swatches.len(); + let at = match opt_u64(p, "at")? { + None => n, + Some(i) => usize::try_from(i).ok().filter(|i| *i <= n).ok_or_else(|| EngineError::Param(format!("param 'at' must be 0 to {n}")))?, + }; + swatches_mut(s).insert(at, sw); + Ok(json!({"index": at, "count": n + 1})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let v = swatches_mut(s); + v.remove(i); + Ok(json!({"count": v.len()})) +} + +fn move_swatch(s: &mut Session, p: &Value) -> Result { + let from = index_param(s, p, "from")?; + let to = index_param(s, p, "to")?; + if from != to { + let v = swatches_mut(s); + let sw = v.remove(from); + v.insert(to, sw); + } + Ok(json!({"index": to})) +} + +fn duplicate(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + if s.doc.swatches.len() >= MAX_SWATCHES { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let v = swatches_mut(s); + let copy = v.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + v.insert(i + 1, copy); + Ok(json!({"index": i + 1, "count": v.len()})) +} + +fn rename(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let name = clean_name(str_req(p, "name")?); + if let Some(sw) = swatches_mut(s).get_mut(i) { + sw.name = name.clone(); + } + Ok(json!({"index": i, "name": name})) +} + +fn apply(s: &mut Session, p: &Value) -> Result { + let i = index_param(s, p, "index")?; + let sw = s.doc.swatches.get(i).cloned().ok_or_else(|| EngineError::Param("no such swatch".into()))?; + let selection = opt_bool(p, "selection")?.unwrap_or(true); + match opt_str(p, "target")?.unwrap_or("fill") { + "fill" => { + let mut fill = swatch_json(&sw); + if let Some(o) = fill.as_object_mut() { + o.remove("name"); + o.insert("selection".into(), json!(selection)); + } + let r = crate::cmds_paint::set_fill(s, &fill)?; + Ok(json!({"target": "fill", "changed": r.get("changed").cloned().unwrap_or(json!(0))})) + } + "stroke" => { + let SwatchPaint::Solid { color } = sw.paint else { + return Err(EngineError::State("strokes are one colour: apply a gradient swatch to the fill instead".into())); + }; + s.style.stroke = color; + s.style.use_stroke = true; + let changed = if selection && !s.selection.is_empty() { + s.each_layer(false, |s| crate::cmds_draw::set_stroke(s, &json!({"color": hex(color)})))?; + s.selection.len() + } else { + 0 + }; + Ok(json!({"target": "stroke", "changed": changed})) + } + other => Err(EngineError::Param(format!("param 'target' must be fill or stroke, not '{other}'"))), + } +} + +fn clear(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + Ok(json!({"count": 2})) +} + +fn reset(s: &mut Session, _: &Value) -> Result { + s.doc.swatches = Arc::new(default_set()); + Ok(json!({"count": s.doc.swatches.len()})) +} + +/// The JSON swatch file: `{"format": "anicraft-swatches", "version": 1, "swatches": [..]}`. +pub fn file_json(swatches: &[Swatch]) -> String { + let v = json!({"format": FORMAT, "version": 1, "swatches": swatches.iter().map(swatch_json).collect::>()}); + serde_json::to_string_pretty(&v).unwrap_or_default() +} + +const FORMAT: &str = "anicraft-swatches"; + +/// The swatches in a swatch file (JSON) or a GIMP palette, told apart by their content. +pub fn parse_file(text: &str) -> Result> { + if text.len() > MAX_PALETTE_BYTES { + return Err(EngineError::Param("the swatch file is too large".into())); + } + if text.trim_start_matches('\u{feff}').trim_start().starts_with("GIMP Palette") { + return parse_gpl(text).map(|(_, v)| v).map_err(EngineError::Param); + } + let v: Value = serde_json::from_str(text).map_err(|e| EngineError::Param(format!("this isn't a swatch file or a GIMP palette ({e})")))?; + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err(EngineError::Param(format!("this JSON isn't a swatch file (its \"format\" must be \"{FORMAT}\")"))); + } + let list = v.get("swatches").and_then(Value::as_array).ok_or_else(|| EngineError::Param("the swatch file has no \"swatches\" list".into()))?; + let mut out = Vec::new(); + for item in list.iter().take(MAX_SWATCHES) { + // A swatch this version can't read is skipped, so a newer file still opens. + if let Ok(Some(sw)) = swatch_from_json(item) { + out.push(sw); + } + } + if out.is_empty() { + return Err(EngineError::Param("the swatch file has no swatches in it".into())); + } + Ok(out) +} + +fn import(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if crate::vfs::len(&path)? > MAX_PALETTE_BYTES as u64 { + return Err(EngineError::Param(format!("{} is too large to be a swatch file", path.display()))); + } + let found = parse_file(&crate::vfs::read_to_string(&path)?)?; + let replace = opt_bool(p, "replace")?.unwrap_or(false); + let v = swatches_mut(s); + if replace { + v.clear(); + } + let room = MAX_SWATCHES.saturating_sub(v.len()); + if room == 0 { + return Err(EngineError::State(format!("a document keeps at most {MAX_SWATCHES} swatches; delete some first"))); + } + let n = found.len().min(room); + v.extend(found.into_iter().take(n)); + Ok(json!({"imported": n, "count": v.len()})) +} + +fn export(s: &mut Session, p: &Value) -> Result { + let path = PathBuf::from(str_req(p, "path")?); + if s.doc.swatches.is_empty() { + return Err(EngineError::State("the document has no swatches to export".into())); + } + let text = file_json(&s.doc.swatches); + crate::vfs::write(&path, text.as_bytes())?; + Ok(json!({"written": path.display().to_string(), "swatches": s.doc.swatches.len(), "bytes": text.len()})) +} diff --git a/crates/engine/src/confirm.rs b/crates/engine/src/confirm.rs index 6f9707b0..5881bdda 100644 --- a/crates/engine/src/confirm.rs +++ b/crates/engine/src/confirm.rs @@ -38,6 +38,10 @@ fn plural(n: usize, word: &str) -> String { if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") } } +fn swatches(n: usize) -> String { + if n == 1 { "1 swatch".into() } else { format!("{n} swatches") } +} + fn target_layer<'a>(s: &'a Session, p: &Value) -> Option<&'a Layer> { let id = p.get("layer").and_then(Value::as_u64).map_or(s.layer, LayerId); s.timeline().layer(id) @@ -124,6 +128,35 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option { irreversible: true, }) } + // Swatches are document data and undoable (ADR 0078): replacing many asks by default. + "swatch.export" => { + let path = Path::new(p.get("path").and_then(Value::as_str)?); + crate::vfs::exists(path).then(|| overwrite(path, "Exporting the swatches")) + } + "swatch.clear" => { + let n = s.doc.swatches.len(); + (n > 2).then(|| Confirmation { + title: "Clear swatches?".into(), + message: format!("{} will be removed, leaving black and white. You can undo this.", swatches(n)), + action: "Clear Swatches".into(), + irreversible: false, + }) + } + "swatch.reset" => { + let custom = !anicraft_doc::swatch::is_default_set(&s.doc.swatches) && !s.doc.swatches.is_empty(); + custom.then(|| Confirmation { + title: "Load the default swatches?".into(), + message: "The document's swatches will be replaced with a new document's set. You can undo this.".into(), + action: "Load Default Swatches".into(), + irreversible: false, + }) + } + "swatch.import" if p.get("replace").and_then(Value::as_bool) == Some(true) && !s.doc.swatches.is_empty() => Some(Confirmation { + title: "Replace swatches?".into(), + message: format!("The document's {} will be replaced with the file's. You can undo this.", swatches(s.doc.swatches.len())), + action: "Replace Swatches".into(), + irreversible: false, + }), "brush.preset_export" => { let path = Path::new(p.get("path").and_then(Value::as_str)?); crate::vfs::exists(path).then(|| overwrite(path, "Exporting the brushes")) diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 1794355a..9f420841 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -249,6 +249,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize { /// Estimated total bytes of a document (as if nothing were shared). Used for reporting. pub fn document_bytes(doc: &Document) -> usize { - let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), next_id: doc.next_id }; + let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), swatches: doc.swatches.clone(), next_id: doc.next_id }; unique_bytes(doc, &empty) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9b451503..3a6e021c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -38,6 +38,7 @@ pub mod cmds_text; mod cmds_timeline; mod cmds_width; mod cmds_stroke; +pub mod cmds_swatch; pub mod confirm; pub mod editing; pub mod explorer; @@ -153,6 +154,7 @@ pub fn commands() -> Vec { v.extend(cmds_brush::specs()); v.extend(cmds_erase::specs()); v.extend(cmds_paint::specs()); + v.extend(cmds_swatch::specs()); v.extend(cmds_text::specs()); v.extend(cmds_width::specs()); v.extend(cmds_stroke::specs()); @@ -1089,3 +1091,5 @@ mod tests_bone_chain; mod path_text_tests; #[cfg(test)] mod group_tests; +#[cfg(test)] +mod swatch_tests; diff --git a/crates/engine/src/plugin_tests.rs b/crates/engine/src/plugin_tests.rs index b1b6acc0..f72cd127 100644 --- a/crates/engine/src/plugin_tests.rs +++ b/crates/engine/src/plugin_tests.rs @@ -176,6 +176,8 @@ fn every_command_namespace_has_a_plugin_policy() { "publish" => assert_eq!(verdict.is_ok(), c.id == "publish.settings_get", "{}", c.id), // Brushes (ADR 0068): list yes; your own brushes and brush set files no. "brush" => assert_eq!(verdict.is_ok(), c.id == "brush.preset_list", "{}", c.id), + // Swatches (ADR 0078): document data yes, swatch files no. + "swatch" => assert_eq!(verdict.is_ok(), !matches!(c.id, "swatch.import" | "swatch.export"), "{}", c.id), _ => assert!(verdict.is_ok() || matches!(c.id, "edit.undo" | "edit.redo") || c.id.contains("copy") || c.id.contains("cut") || c.id.contains("paste"), "{} has no plug-in policy (add its namespace to plugin_may_call)", c.id), } } diff --git a/crates/engine/src/swatch_tests.rs b/crates/engine/src/swatch_tests.rs new file mode 100644 index 00000000..fad75e12 --- /dev/null +++ b/crates/engine/src/swatch_tests.rs @@ -0,0 +1,244 @@ +//! The Swatches panel's commands (ADR 0078). + +use crate::Session; +use anicraft_doc::{Document, ElementId, ElementKind, Paint, Rgba, Shape, Swatch, SwatchPaint}; +use serde_json::{Value, json}; +use std::path::Path; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")) +} + +fn blank() -> Session { + Session::new(Document::default()) +} + +fn shape(s: &Session, id: u64) -> Shape { + s.visible_elements() + .iter() + .find(|e| e.id == ElementId(id)) + .and_then(|e| match &e.kind { + ElementKind::Shape(sh) => Some(sh.clone()), + _ => None, + }) + .expect("a shape") +} + +/// A selected 100 × 100 square at (x, 100), red with a black stroke. +fn square(s: &mut Session, x: f32) -> u64 { + run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"}))["element"].as_u64().unwrap() +} + +fn find(s: &Session, name: &str) -> usize { + s.doc.swatches.iter().position(|w| w.name == name).unwrap_or_else(|| panic!("no swatch {name}")) +} + +#[test] +fn a_new_document_has_the_default_swatches_and_older_files_open_with_them() { + let s = blank(); + assert_eq!(s.doc.swatches.len(), 19); + // A file from before swatches (no "swatches" key) opens with the default set; the set is + // not written while unchanged, so such files stay as they were. + let text = crate::format::to_json(&s.doc).unwrap(); + assert!(!text.contains("\"swatches\""), "the default set isn't written"); + let back = crate::format::from_json(&text).unwrap(); + assert!(anicraft_doc::swatch::is_default_set(&back.swatches)); +} + +#[test] +fn swatches_round_trip_through_the_file() { + let mut s = blank(); + run(&mut s, "swatch.clear", json!({"confirm": true})); + run(&mut s, "swatch.add", json!({"color": "#12345680", "name": "Ink"})); + run(&mut s, "swatch.add", json!({"type": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.7, "color": "#ff000080"}], "spread": "reflect", "linear_rgb": true, "focal": 0.5, "name": "Glow"})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(*back.swatches, *s.doc.swatches); + assert_eq!(back.swatches.len(), 4); + let SwatchPaint::Radial { spread, linear_rgb, focal, stops } = &back.swatches[3].paint else { panic!("a radial swatch") }; + assert_eq!((spread.key(), *linear_rgb, *focal, stops.len()), ("reflect", true, 0.5, 2)); + // An explicitly empty list stays empty (it isn't the default set). + let mut e = blank(); + run(&mut e, "swatch.clear", json!({"confirm": true})); + run(&mut e, "swatch.remove", json!({"index": 0})); + run(&mut e, "swatch.remove", json!({"index": 0})); + let back = crate::format::from_json(&crate::format::to_json(&e.doc).unwrap()).unwrap(); + assert!(back.swatches.is_empty()); + // A damaged file's swatches are repaired or dropped on open. + let mut v: Value = serde_json::from_str(&text).unwrap(); + v["document"]["swatches"] = json!([{"paint": {"type": "linear", "stops": [{"offset": 0, "color": {"r": 0, "g": 0, "b": 0, "a": 1}}]}}, {"name": "ok", "paint": {"type": "solid", "color": {"r": 9, "g": 0.5, "b": 0, "a": 1}}}]); + let fixed = crate::format::from_json(&v.to_string()).unwrap(); + assert_eq!(fixed.swatches.len(), 1); + assert_eq!(fixed.swatches[0].paint.primary_color().r, 1.0); +} + +#[test] +fn add_takes_the_current_fill_or_stroke_or_a_given_swatch() { + let mut s = blank(); + let n = s.doc.swatches.len(); + s.style.set_fill_color(Rgba::hex(0x3366ff)); + s.style.stroke = Rgba::hex(0x00aa00); + assert_eq!(run(&mut s, "swatch.add", json!({}))["index"], n); + assert_eq!(s.doc.swatches[n].paint, SwatchPaint::Solid { color: Rgba::hex(0x3366ff) }); + run(&mut s, "swatch.add", json!({"from": "stroke", "at": 0, "name": "Leaf"})); + assert_eq!((s.doc.swatches[0].name.as_str(), s.doc.swatches[0].paint.primary_color()), ("Leaf", Rgba::hex(0x00aa00))); + // A gradient fill swatch adds its ramp and options. + run(&mut s, "paint.set_fill", json!({"type": "radial", "spread": "repeat", "selection": false})); + let i = run(&mut s, "swatch.add", json!({"from": "fill"}))["index"].as_u64().unwrap() as usize; + assert!(matches!(&s.doc.swatches[i].paint, SwatchPaint::Radial { spread: anicraft_doc::Spread::Repeat, .. })); + // Each add is one undo step. + let len = s.doc.swatches.len(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), len - 1); + for bad in [json!({"from": "middle"}), json!({"type": "solid"}), json!({"type": "linear"}), json!({"type": "conic", "color": "#000000"}), json!({"from": "fill", "color": "#000000"}), json!({"color": "#00"}), json!({"color": "#000000", "at": 9999})] { + assert!(s.execute("swatch.add", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn remove_move_duplicate_and_rename() { + let mut s = blank(); + let n = s.doc.swatches.len(); + let red = s.doc.swatches[6].clone(); + run(&mut s, "swatch.move", json!({"from": 6, "to": 0})); + assert_eq!(s.doc.swatches[0], red); + assert_eq!(s.doc.swatches.len(), n); + run(&mut s, "swatch.move", json!({"from": 0, "to": n - 1})); + assert_eq!(s.doc.swatches[n - 1], red, "to the end"); + assert_eq!(run(&mut s, "swatch.duplicate", json!({"index": n - 1}))["index"], n); + assert_eq!(s.doc.swatches[n], red); + run(&mut s, "swatch.rename", json!({"index": n, "name": " Fire engine "})); + assert_eq!(s.doc.swatches[n].name, "Fire engine"); + run(&mut s, "swatch.remove", json!({"index": n})); + assert_eq!(s.doc.swatches.len(), n); + for (id, bad) in [("swatch.remove", json!({"index": n})), ("swatch.remove", json!({})), ("swatch.move", json!({"from": 0, "to": n})), ("swatch.duplicate", json!({"index": -1})), ("swatch.rename", json!({"index": 0}))] { + assert!(s.execute(id, &bad).is_err(), "{id} {bad}"); + } +} + +#[test] +fn apply_sets_the_fill_or_the_stroke_of_the_selection_and_the_tool() { + let mut s = blank(); + let id = square(&mut s, 50.0); + let blue = find_colour(&s, 0x0000ff); + // Fill: the selection and the fill swatch. + assert_eq!(run(&mut s, "swatch.apply", json!({"index": blue}))["changed"], 1); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::hex(0x0000ff))); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::BLACK, "the stroke is untouched"); + // Stroke: the selection's lines and the stroke colour; the fill stays. + let yellow = find_colour(&s, 0xffff00); + run(&mut s, "swatch.apply", json!({"index": yellow, "target": "stroke"})); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + assert_eq!(s.style.stroke, Rgba::hex(0xffff00)); + assert_eq!(shape(&s, id).fill, Some(Paint::Solid(Rgba::hex(0x0000ff)))); + // A gradient swatch is fitted to the shape, and the swatch holds it. + let glow = find(&s, "Red ball"); + run(&mut s, "swatch.apply", json!({"index": glow})); + let Some(Paint::Radial { center, radius, stops, .. }) = shape(&s, id).fill else { panic!("a radial fill") }; + assert_eq!(stops[0].color, Rgba::hex(0xff8080)); + assert!(center.x.abs() < 1e-3 && center.y.abs() < 1e-3 && (radius - 50.0).abs() < 1.0, "fitted to the 100-unit square: {center:?} {radius}"); + assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. }))); + // Strokes are one colour. + assert!(s.execute("swatch.apply", &json!({"index": glow, "target": "stroke"})).is_err()); + // With `selection: false` only the tool colour changes. + let white = find_colour(&s, 0xffffff); + assert_eq!(run(&mut s, "swatch.apply", json!({"index": white, "selection": false}))["changed"], 0); + assert_eq!(s.style.fill_paint(), Paint::Solid(Rgba::WHITE)); + assert!(matches!(shape(&s, id).fill, Some(Paint::Radial { .. }))); + // Nothing selected: the tool colour. + run(&mut s, "edit.deselect", json!({})); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "stroke"})); + assert_eq!(s.style.stroke, Rgba::hex(0x0000ff)); + assert_eq!(shape(&s, id).stroke.unwrap().color, Rgba::hex(0xffff00)); + // On the selection: one undo step (the tool colour alone is no document change). + run(&mut s, "edit.select_all", json!({})); + let before = s.history_len(); + run(&mut s, "swatch.apply", json!({"index": blue, "target": "fill"})); + assert_eq!(s.history_len(), before + 1); + assert!(s.execute("swatch.apply", &json!({"index": 0, "target": "outline"})).is_err()); +} + +fn find_colour(s: &Session, rgb: u32) -> usize { + s.doc.swatches.iter().position(|w| w.paint == SwatchPaint::Solid { color: Rgba::hex(rgb) }).expect("a default colour") +} + +#[test] +fn clear_and_reset_ask_first_and_undo() { + let mut s = blank(); + let c = s.confirmation("swatch.clear", &json!({})).expect("clearing 19 swatches asks"); + assert!(!c.irreversible, "undoable, so it asks by default only"); + run(&mut s, "swatch.clear", json!({})); + assert_eq!(*s.doc.swatches, vec![Swatch::solid(Rgba::BLACK), Swatch::solid(Rgba::WHITE)]); + assert!(s.confirmation("swatch.clear", &json!({})).is_none(), "nothing to lose"); + assert!(s.confirmation("swatch.reset", &json!({})).is_some()); + run(&mut s, "swatch.reset", json!({})); + assert!(anicraft_doc::swatch::is_default_set(&s.doc.swatches)); + assert!(s.confirmation("swatch.reset", &json!({})).is_none(), "already the default set"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.swatches.len(), 2); +} + +#[test] +fn swatch_files_export_and_import() { + crate::vfs::use_memory(); + let mut s = blank(); + run(&mut s, "swatch.add", json!({"type": "linear", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff00"}], "name": "Fade"})); + let v = run(&mut s, "swatch.export", json!({"path": "set.json"})); + assert_eq!(v["swatches"], 20); + let text = crate::vfs::read_to_string(Path::new("set.json")).unwrap(); + assert!(text.contains("\"format\": \"anicraft-swatches\"") && text.contains("\"Fade\"") && text.contains("#ffffff00")); + assert!(s.confirmation("swatch.export", &json!({"path": "set.json"})).is_some_and(|c| c.irreversible), "overwriting a file asks"); + // Another document: added at the end, or replacing (which asks by default). + let mut t = blank(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "set.json"}))["count"], 39); + assert!(t.confirmation("swatch.import", &json!({"path": "set.json", "replace": true})).is_some_and(|c| !c.irreversible)); + run(&mut t, "swatch.import", json!({"path": "set.json", "replace": true})); + assert_eq!(*t.doc.swatches, *s.doc.swatches, "the same swatches, exactly"); + // Unknown swatches in a newer file are skipped; junk is refused. + crate::vfs::put(Path::new("new.json"), br##"{"format": "anicraft-swatches", "version": 2, "swatches": [{"type": "conic"}, {"type": "solid", "color": "#010203"}]}"##.to_vec()).unwrap(); + let before = t.doc.swatches.len(); + assert_eq!(run(&mut t, "swatch.import", json!({"path": "new.json"}))["imported"], 1); + assert_eq!(t.doc.swatches.len(), before + 1); + for (name, body) in [("a.json", "{}"), ("b.json", "[1, 2]"), ("c.json", "not json"), ("d.json", r#"{"format": "anicraft-brushes"}"#), ("e.json", r#"{"format": "anicraft-swatches", "swatches": []}"#)] { + crate::vfs::put(Path::new(name), body.as_bytes().to_vec()).unwrap(); + assert!(t.execute("swatch.import", &json!({"path": name})).is_err(), "{name}"); + } + assert!(t.execute("swatch.import", &json!({"path": "missing.json"})).is_err()); +} + +#[test] +fn gimp_palettes_import() { + crate::vfs::use_memory(); + let mut s = blank(); + crate::vfs::put(Path::new("brand.gpl"), b"GIMP Palette\nName: Brand\nColumns: 3\n#\n230 57 70\tRed\n 29 53 87\tNavy\n241 250 238 Untitled\n".to_vec()).unwrap(); + run(&mut s, "swatch.import", json!({"path": "brand.gpl", "replace": true, "confirm": true})); + assert_eq!(s.doc.swatches.len(), 3); + assert_eq!(s.doc.swatches[0].name, "Red"); + assert_eq!(s.doc.swatches[1].paint.primary_color().to_hex(), "#1d3557"); + assert_eq!(s.doc.swatches[2].name, ""); + // Then they paint like any swatch. + let id = square(&mut s, 0.0); + run(&mut s, "swatch.apply", json!({"index": 1})); + assert_eq!(shape(&s, id).fill.map(|p| p.primary_color().to_hex()), Some("#1d3557".into())); +} + +#[test] +fn swatches_are_bounded() { + let mut s = blank(); + s.doc.swatches = std::sync::Arc::new(vec![Swatch::solid(Rgba::BLACK); anicraft_doc::MAX_SWATCHES]); + assert!(s.execute("swatch.add", &json!({"color": "#ffffff"})).is_err()); + assert!(s.execute("swatch.duplicate", &json!({"index": 0})).is_err()); + let list = run(&mut s, "swatch.list", json!({})); + assert_eq!(list["count"], anicraft_doc::MAX_SWATCHES); + assert_eq!(list["swatches"][3]["index"], 3); +} + +#[test] +fn plug_ins_edit_swatches_but_not_swatch_files() { + use crate::cmds_plugin::plugin_may_call; + for id in ["swatch.add", "swatch.apply", "swatch.remove", "swatch.move", "swatch.list", "swatch.clear"] { + assert!(plugin_may_call(id).is_ok(), "{id}"); + } + assert!(plugin_may_call("swatch.import").is_err() && plugin_may_call("swatch.export").is_err()); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 28047592..1bae2426 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -558,6 +558,11 @@ fn panic_hunt_every_command() { json!({"points": [[0, 0], [10, 0]], "preset": "nope", "curve": "wobbly", "spacing": 1, "jitter": -1, "name": "", "from": "missing", "names": [1, 2]}), json!({"points": [[f64::MAX, 0]], "curve": [[f64::NAN, 2]], "pressure_size": "yes", "pressure_opacity": 1, "as_stroke": "no", "name": "Chalk", "to": "Pencil"}), json!({"points": (0..2000).map(|i| json!([f64::from(i), f64::from(i % 7) * 3.0, f64::from(i % 3) * 0.5])).collect::>(), "preset": "ink_pen", "as_stroke": true, "name": "a".repeat(5000)}), + // Swatches (ADR 0078): junk kinds, indices and paints, both targets, a missing file. + json!({"index": 0, "from": 18, "to": 0, "target": "stroke", "name": "a".repeat(5000)}), + json!({"index": 12, "target": "stroke", "selection": false, "type": "radial", "stops": [{"offset": 0, "color": "#000000"}, {"offset": 1, "color": "#ffffff"}], "focal": 0.98, "at": 0}), + json!({"index": u64::MAX, "from": "nowhere", "target": 3, "type": "conic", "stops": [{"offset": 2, "color": "#00"}], "spread": "wrap", "path": "no/such/palette.gpl"}), + json!({"color": "#ff000000", "name": "\u{0}\n", "at": u64::MAX, "replace": true, "path": ""}), // Stroke styles (ADR 0046): junk, extremes and patterns that would be very fine. json!({"cap": "none", "join": "miter", "miter": 100, "dash": [0, 1e-30], "dash_offset": -1e4, "style": "dashed"}), json!({"cap": 7, "join": "mitre", "miter": f64::NAN, "dash": vec![1e4; 16], "dot_spacing": 0, "style": "dotted"}),