PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Merge origin/main into feat/file-215-2-mezzotint-halftone
David Manne74f4758d809
diff --cc crates/io/src/smart_map.rsindex e052d556e,5ec4db118..91b50ec0e--- a/crates/io/src/smart_map.rs+++ b/crates/io/src/smart_map.rs@@@ -173,23 -262,22 +262,25 @@@ fn known_by_command(command: &str) -> Oconst CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")];/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each).--const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [-- (b"FnDt", "fineDots"),-- (b"MdmD", "mediumDots"),-- (b"GrnD", "grainyDots"),-- (b"CrsD", "coarseDots"),-- (b"ShrL", "shortLines"),-- (b"MdmL", "mediumLines"),-- (b"LngL", "longLines"),-- (b"ShSt", "shortStrokes"),-- (b"MdmS", "mediumStrokes"),-- (b"LngS", "longStrokes"),++const MEZZOTINT_TYPES: [(&str, &str); 10] = [++ ("FnDt", "fineDots"),++ ("MdmD", "mediumDots"),++ ("GrnD", "grainyDots"),++ ("CrsD", "coarseDots"),++ ("ShrL", "shortLines"),++ ("MdmL", "mediumLines"),++ ("LngL", "longLines"),++ ("ShSt", "shortStrokes"),++ ("MdmS", "mediumStrokes"),++ ("LngS", "longStrokes"),];/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within/// the dialog's ranges; anything else is kept verbatim.fn color_halftone_params(f: &Descriptor) -> Option<J> {- only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"])?;++ if !only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"]) {++ return None;++ }let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?;let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a));Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?}))@@@ -206,21 -294,45 +297,46 @@@ fn int(d: &Descriptor, key: &str) -> Op}}- /// `Some(())` when every setting of `f` is one of `keys`, each at most once: a filter with a- /// setting we don't write back (or a repeated one) stays verbatim instead of losing it on save.- fn only_keys(f: &Descriptor, keys: &[&str]) -> Option<()> {- let known = f.items.iter().all(|(k, _)| keys.iter().any(|key| k.is(key)));- (known && keys.iter().all(|key| f.items.iter().filter(|(k, _)| k.is(key)).count() <= 1)).then_some(())+ /// `v` when it lies in `lo..=hi` (the filter dialog's range); out-of-range settings are not+ /// opened as editable filters, so a re-save keeps Photoshop's value instead of a clamped one.+ fn in_range(v: f64, lo: f64, hi: f64) -> Option<f64> {+ (lo..=hi).contains(&v).then_some(v)}- /// The value of the enum `key` when its type is `type_id` (a mistyped enum is not modelled).- fn typed_enum<'a>(f: &'a Descriptor, key: &str, type_id: &str) -> Option<&'a [u8]> {- match f.get(key)? {- Value::Enumerated { type_id: t, value } if t.is(type_id) => Some(value.as_bytes()),- _ => None,- }+ /// Integer `key` of `f` when it lies in `lo..=hi`.+ fn int_in(f: &Descriptor, key: &str, lo: i32, hi: i32) -> Option<i32> {+ int(f, key).filter(|v| (lo..=hi).contains(v))}-/// True when `f` holds only the given keys. A filter with a setting we don't know about (Radial-/// Blur's off-centre centre, for one) is kept verbatim rather than losing that setting.++/// True when `f` holds only the given keys, each at most once. A filter with a setting we don't++/// know about (Radial Blur's off-centre centre, for one) or a repeated one is kept verbatim++/// rather than losing that setting on save.+ fn only_keys(f: &Descriptor, keys: &[&str]) -> bool {- f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x)))++ f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x))) && keys.iter().all(|x| f.items.iter().filter(|(k, _)| k.is(x)).count() <= 1)+ }++ /// Our name for enum `key`'s value in `f`, from `(PSD value, our name)` pairs.+ fn enum_name(f: &Descriptor, key: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> {+ let v = enum_of(f, key)?;+ table.iter().find(|(c, _)| v == &c[..]).map(|(_, n)| *n)+ }++ /// Enum `type_id` holding the PSD value of our name `p[key]` (`default` when absent).+ fn enum_param(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Result<Value, String> {+ let name = match p.get(key) {+ None | Some(J::Null) => default,+ Some(v) => v.as_str().ok_or_else(|| format!("setting `{key}` is not text"))?,+ };+ let code = table.iter().find(|(_, n)| *n == name).map(|(c, _)| **c).ok_or_else(|| format!("{key} `{name}` has no PSD equivalent"))?;+ Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(code) })+ }++ /// Smart Blur `SmBQ` / `SmBM` and Radial Blur `BlrM` / `BlrQ` values (measured in Photoshop).+ const SMART_BLUR_QUALITY: [(&[u8; 4], &str); 3] = [(b"SBQL", "low"), (b"SBQM", "medium"), (b"SBQH", "high")];+ const SMART_BLUR_MODE: [(&[u8; 4], &str); 3] = [(b"SBMN", "normal"), (b"SBME", "edgeOnly"), (b"SBMO", "overlayEdge")];+ const RADIAL_METHOD: [(&[u8; 4], &str); 2] = [(b"Spn ", "spin"), (b"Zm ", "zoom")];+ const RADIAL_QUALITY: [(&[u8; 4], &str); 3] = [(b"Drft", "draft"), (b"Gd ", "good"), (b"Bst ", "best")];+fn channel_key(d: &Descriptor) -> Option<&'static str> {let Some(Value::Reference(items)) = d.get("Chnl") else { return None };let Some(ReferenceItem::Enumerated { value, .. }) = items.first() else { return None };@@@ -320,14 -519,64 +523,61 @@@ fn known_params(class: &str, f: Option<};json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)})}+ ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({+ "radius": in_range(px(f, "Rds ")?, 1.0, 100.0)?,+ "threshold": int_in(f, "Thsh", 2, 255)?,+ }),+ ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({+ "radius": in_range(px(f, "Rds ")?, 0.1, 100.0)?,+ "threshold": in_range(px(f, "Thsh")?, 0.1, 100.0)?,+ "quality": enum_name(f, "SmBQ", &SMART_BLUR_QUALITY)?,+ "mode": enum_name(f, "SmBM", &SMART_BLUR_MODE)?,+ }),+ ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({+ "amount": int_in(f, "Amnt", 1, 100)?,+ "method": enum_name(f, "BlrM", &RADIAL_METHOD)?,+ "quality": enum_name(f, "BlrQ", &RADIAL_QUALITY)?,+ }),("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}),-- ("Mztn", Some(f)) => {- only_keys(f, &["MztT"])?;- let t = typed_enum(f, "MztT", "MztT")?;- let t = enum_of(f, "MztT")?;-- json!({"type": MEZZOTINT_TYPES.iter().find(|(c, _)| t == &c[..])?.1})-- }++ ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_from(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}),("ClrH", Some(f)) => color_halftone_params(f)?,("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}),+ (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?,+ ("DstS", Some(f)) => {+ if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) {+ return None;+ }+ json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?})+ }+ ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}),+ ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}),+ ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}),+ ("Pntl", Some(f)) => {+ let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?});+ // Pointillize paints the gaps in the background colour the entry carries.+ if item.get("BckC").is_some() {+ p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?;+ }+ p+ }+ ("Wnd ", Some(f)) => json!({+ "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?,+ "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?,+ }),+ ("Extr", Some(f)) => json!({+ "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?,+ "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?,+ "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?,+ "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?,+ "solidFrontFaces": bool_at(f, "ExtF")?,+ "maskIncompleteBlocks": bool_at(f, "ExtM")?,+ }),+ ("Tls ", Some(f)) => tiles_params(f, item)?,+ ("Ofst", Some(f)) => {+ let fill = OFFSET_FILL.iter().find(|(psd, _)| enum_of(f, "Fl ") == Some(psd.as_bytes()))?.1;+ json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": fill})+ }+ ("Cstm", Some(f)) => custom_params(f)?,("Lvls", Some(f)) => levels_params(f)?,("Crvs", Some(f)) => curves_params(f)?,_ => return None,@@@ -643,8 -941,8 +942,8 @@@ fn fltr_for(k: &Known, p: &J) -> Result// Photoshop's Mezzotint has no seed (it is random on every render), so `seed` is not saved."Mztn" => {let t = p.get("type").and_then(J::as_str).unwrap_or("fineDots");-- let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or(b"FnDt", |(c, _)| *c);-- d.with("MztT", Value::Enumerated { type_id: Id::new("MztT"), value: Id::Code(*code) })++ let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or("FnDt", |(c, _)| *c);++ d.with("MztT", enumv("MztT", code))}"ClrH" => {// Longs within the dialog's ranges (what the engine accepts: radius 4..127, angles ±360).@@@ -1257,7 -2347,7 +2348,7 @@@ mod testsassert_eq!(int(&d, "filterID"), Some(1_299_870_830));let fltr = get_desc(&d, "Fltr").unwrap();assert!(fltr.class_id.is("Mztn"));-- assert_eq!(enum_of(fltr, "MztT"), Some(&code[..]));++ assert_eq!(enum_of(fltr, "MztT"), Some(code.as_bytes()));assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT")));assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}");}@@@ -1326,22 -2416,17 +2417,22 @@@.with("Ang4", Value::Integer(40))};let cases = [- measured_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")),- measured_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")),- measured_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")),- measured_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")),- measured_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")),+ pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")),+ pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")),+ pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")),+ pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")),+ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")),+ // A mistyped enum and settings we don't write back.- measured_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")),- measured_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")),- measured_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")),- measured_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")),++ pixelate_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")),++ pixelate_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")),++ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")),++ pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")),];for item in cases {let f = filter_from_item(&item);