diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 589c9f196d8..0d428f30863 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -562,6 +562,46 @@ pub fn to_bitmap(gray: &mut [f32], w: usize, method: BitmapMethod) { } } +/// The threshold map of Bitmap's Custom Pattern from a pattern's lightness (0..=1, row-major): +/// pattern pixels ranked by lightness, ties sharing their average rank, the lightest pixel +/// thresholding lowest (it turns white first). A map of `n` pixels thus spreads `n` evenly +/// spaced levels `(k + 0.5) / n`, whatever the pattern's own contrast, as Photoshop's does +/// (measured: a 2x2 pattern of 32/96/160/224, a 3x1 of 50/128/200 and a 7x1 ramp all give +/// exactly those levels). +pub fn custom_pattern_thresholds(lightness: &[f32]) -> Vec { + let n = lightness.len(); + let key = |i: usize| lightness.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0); + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| key(*a).total_cmp(&key(*b))); + let mut out = vec![0.5; n]; + let mut start = 0; + while start < n { + let v = order.get(start).map(|i| key(*i)); + let end = (start..n).find(|&j| order.get(j).map(|i| key(*i)) != v).unwrap_or(n); + // Ranks start..end share their mean. + let rank = (start + end - 1) as f32 / 2.0; + let t = 1.0 - (rank + 0.5) / n as f32; + for i in order.get(start..end).unwrap_or_default() { + if let Some(o) = out.get_mut(*i) { + *o = t; + } + } + start = end; + } + out +} + +/// Bitmap's Custom Pattern: each gray value (0..=1, row-major `w` wide) turns white where it +/// reaches the threshold `map` (`mw` x `mh`, from [`custom_pattern_thresholds`]) tiled from the +/// image's top-left corner, black elsewhere. A map that doesn't fit `mw` x `mh` thresholds at 50%. +pub fn to_bitmap_custom(gray: &mut [f32], w: usize, map: &[f32], mw: usize, mh: usize) { + let fits = w > 0 && mw > 0 && mh > 0 && mw.checked_mul(mh) == Some(map.len()); + for (i, v) in gray.iter_mut().enumerate() { + let t = if fits { map.get((i / w) % mh * mw + (i % w) % mw).copied().unwrap_or(0.5) } else { 0.5 }; + *v = if *v >= t { 1.0 } else { 0.0 }; + } +} + #[cfg(test)] mod tests { use super::*; @@ -722,4 +762,41 @@ mod tests { } } } + + /// The first 8-bit gray level (of a 0..=255 ramp) that `t` turns white. + fn first_white(t: f32) -> u32 { + (0..=255).find(|v| *v as f32 / 255.0 >= t).unwrap_or(256) + } + + #[test] + fn custom_pattern_thresholds_match_photoshop() { + // Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white + // level per pattern pixel, measured against defined patterns. + let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::>(); + let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])); + assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::>(), [237, 201, 164, 128, 92, 55, 19]); + let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])); + assert_eq!(five.iter().map(|t| first_white(*t)).collect::>(), [230, 77, 179, 26, 128]); + // Equal pixels share their rank: 100, 100 both sit at 50%. + let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])); + assert_eq!(ties.iter().map(|t| first_white(*t)).collect::>(), [128, 128, 32, 224]); + assert!(custom_pattern_thresholds(&[]).is_empty()); + assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2); + } + + #[test] + fn custom_pattern_tiles_from_the_top_left() { + // A 2x1 map: even columns need 75%, odd ones 25%. + let map = [0.75, 0.25]; + let mut g = vec![0.5; 6]; + to_bitmap_custom(&mut g, 3, &map, 2, 1); + assert_eq!(g, [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + // A map that doesn't match its size, or an empty image width, is a 50% threshold. + let mut g = vec![0.4, 0.6]; + to_bitmap_custom(&mut g, 2, &map, 3, 1); + assert_eq!(g, [0.0, 1.0]); + let mut g = vec![0.6]; + to_bitmap_custom(&mut g, 0, &map, 2, 1); + assert_eq!(g, [1.0]); + } } diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index b49ad9ae4f2..ab2a5b960f3 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -276,7 +276,7 @@ pub(crate) fn check_resample_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, /// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to /// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution /// mode. Callers check [`check_resample_budget`] first. -fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { +pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { let (ow, oh) = (doc.size.width, doc.size.height); let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64); if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs index e0d06209af3..0bb601c9b74 100644 --- a/crates/engine/src/mode_cmds.rs +++ b/crates/engine/src/mode_cmds.rs @@ -393,9 +393,48 @@ fn color_table(s: &mut Session, p: &Value) -> Result { // ---------- Bitmap ---------- +/// Bitmap's Output resolution range (ppi): what a new document may have. +const BITMAP_RESOLUTION: std::ops::RangeInclusive = 1.0..=crate::document_preset_cmds::MAX_RESOLUTION; + +/// Bitmap's Custom Pattern: a pattern's threshold map (see +/// [`quantize::custom_pattern_thresholds`]) with its width and height. +fn custom_pattern_map(s: &Session, cmd: &str, p: &Value) -> Result<(Vec, usize, usize)> { + if p.get("pattern").is_some_and(|v| !v.is_string() && !v.is_null()) { + return Err(bad(cmd, "`pattern` must be a pattern id or name")); + } + let pat = crate::pattern_cmds::resolve_param(s, cmd, p)?; + // A pattern keeps its own colours: its lightness is what it paints in a Grayscale document, + // over white where it is transparent. + let px = photocraft_compose::pattern::pattern_rgba(&pat, ColorMode::Grayscale); + if px.is_empty() { + return Err(bad(cmd, format!("the pattern \"{}\" is empty or too large", pat.display_name()))); + } + let lightness: Vec = px.iter().map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]]) * q[3] + (1.0 - q[3])).collect(); + Ok((quantize::custom_pattern_thresholds(&lightness), pat.width as usize, pat.height as usize)) +} + fn bitmap(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.mode.bitmap"; - let dpi = s.active().ok_or(EngineError::NoDocument)?.doc.resolution_dpi.max(1.0); + let d = s.active().ok_or(EngineError::NoDocument)?; + let input = f64::from(d.doc.resolution_dpi.max(1.0)); + let (ow, oh) = (d.doc.size.width, d.doc.size.height); + // Output resolution (ppi): Photoshop resamples the image to it, keeping the print size, + // before converting, and the document takes it as its resolution. + let output = finite_num(p, CMD, "resolution", input)?; + if !BITMAP_RESOLUTION.contains(&output) { + return Err(bad(CMD, format!("resolution {output} is outside {}..{} pixels/inch", BITMAP_RESOLUTION.start(), BITMAP_RESOLUTION.end()))); + } + let (nw, nh) = if (output - input).abs() < 1e-6 { + (ow, oh) + } else { + let side = |v: u32| (f64::from(v) * output / input).round().clamp(1.0, 300_000.0) as u32; + (side(ow), side(oh)) + }; + if (nw, nh) != (ow, oh) { + crate::image_cmds::check_resample_budget(CMD, &d.doc, nw, nh, ", or a lower Output resolution")?; + } + let dpi = output as f32; + let mut custom = None; let method = match str_or(p, "method", "diffusion") { "threshold" | "threshold50" => BitmapMethod::Threshold, "pattern" => BitmapMethod::Pattern, @@ -408,21 +447,40 @@ fn bitmap(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("angle {angle} is outside -180..180"))); } let shape = HalftoneShape::from_id(str_or(p, "shape", "round")).ok_or_else(|| bad(CMD, "shape: round|ellipse|line|square|diamond|cross"))?; + // The screen is laid out at the output resolution. BitmapMethod::Halftone { cell: (dpi / freq).max(2.0), angle: angle as f32, shape } } + "customPattern" => { + custom = Some(custom_pattern_map(s, CMD, p)?); + BitmapMethod::Threshold + } m => { - return Err(bad(CMD, format!("method `{m}` (threshold|pattern|diffusion|halftone)"))); + return Err(bad(CMD, format!("method `{m}` (threshold|pattern|diffusion|halftone|customPattern)"))); } }; + if (nw, nh) != (ow, oh) { + // Color Sampler points scale with the pixels, as in Image Size. + let (sx, sy) = (f64::from(nw) / f64::from(ow.max(1)), f64::from(nh) / f64::from(oh.max(1))); + s.set_sampler_map(photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); + } s.edit("Bitmap", |doc, active| { + if (nw, nh) != (doc.size.width, doc.size.height) { + crate::image_cmds::resample_doc(doc, nw, nh, photocraft_algo::resample::Resample::Bicubic); + } + doc.resolution_dpi = dpi; let px = composite(doc, true); let mut gray: Vec = px.iter().map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]])).collect(); - quantize::to_bitmap(&mut gray, doc.size.width as usize, method); + let w = doc.size.width as usize; + match &custom { + Some((map, mw, mh)) => quantize::to_bitmap_custom(&mut gray, w, map, *mw, *mh), + None => quantize::to_bitmap(&mut gray, w, method), + } let out: Vec<[f32; 4]> = gray.iter().map(|g| [*g, *g, *g, 1.0]).collect(); single_layer(doc, active, ColorMode::Bitmap, &out, "Background", true); Ok(()) })?; - Ok(Value::Null) + let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; + Ok(json!({"width": size.width, "height": size.height, "resolution": dpi})) } // ---------- Duotone ---------- @@ -532,7 +590,7 @@ pub fn specs() -> Vec { "image.mode.bitmap", "Bitmap…", ["Image", "Mode"], - r##"{"method":"diffusion|threshold|pattern|halftone"="diffusion","frequency":1..999=53,"angle":-180..180=45,"shape":"round|ellipse|line|square|diamond|cross"="round"} (halftone frequency in lines/inch; flattens)"##, + r##"{"resolution":1..30000=document,"method":"diffusion|threshold|pattern|halftone|customPattern"="diffusion","frequency":1..999=53,"angle":-180..180=45,"shape":"round|ellipse|line|square|diamond|cross"="round","pattern":id|name=Patterns panel selection} (resolution: Output in pixels/inch, resamples first; frequency/angle/shape: Halftone Screen, frequency in lines/inch; pattern: Custom Pattern; flattens)"##, |s| mode_is(s, &[ColorMode::Grayscale], "Bitmap needs a Grayscale image (Image › Mode › Grayscale first)"), bitmap ), diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs index e6892680f73..84b188bb6f1 100644 --- a/crates/engine/src/mode_cmds/tests.rs +++ b/crates/engine/src/mode_cmds/tests.rs @@ -344,6 +344,132 @@ fn bitmap_halftone_rejects_bad_angles_and_frequencies_without_editing_the_docume assert_eq!(doc(&s).mode, ColorMode::Bitmap); } +/// A grayscale document `w` x `h` whose column x holds the 8-bit level `x` (a 0..255 ramp). +fn ramp(w: u32, h: u32, depth: u64, dpi: f32) -> Session { + let mut s = session(w, h, depth, "grayscale"); + paint(&mut s, |x, _| [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0]); + s.edit("dpi", |doc, _| { + doc.resolution_dpi = dpi; + Ok(()) + }) + .unwrap(); + s +} + +/// The first column of row `y` whose pixel is white among columns `x % m == k`. +fn first_white(d: &Document, y: i32, m: i32, k: i32) -> Option { + let surf = d.layers[0].surface().unwrap(); + (0..d.size.width as i32).filter(|x| x % m == k).find(|x| surf.pixel(*x, y)[0] > 0.5) +} + +fn add_pattern(s: &mut Session, name: &str, w: u32, h: u32, levels: &[u8]) { + let mut surf = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false)); + let data: Vec = levels.iter().map(|v| f32::from(*v) / 255.0).collect(); + surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + let pat = photocraft_doc::pattern::Pattern::new(name, surf, w, h); + s.edit("pattern", |doc, _| { + doc.patterns.push(pat); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn bitmap_output_resolution_resamples_and_sets_the_resolution() { + // Photoshop: a 256 x 4 ramp at 72 ppi converted with Output 144 ppi is 512 x 8 at 144 ppi, + // its 50% threshold at column 256; at 36 ppi it is 128 x 2, the threshold at column 64. + for depth in [8, 16] { + let mut s = ramp(256, 4, depth, 72.0); + let r = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 144})).unwrap(); + assert_eq!(r, json!({"width": 512, "height": 8, "resolution": 144.0}), "{depth}"); + let d = doc(&s); + assert_eq!((d.size.width, d.size.height, d.resolution_dpi, d.mode), (512, 8, 144.0, ColorMode::Bitmap), "{depth}"); + assert!(first_white(d, 3, 1, 0).is_some_and(|x| (255..=257).contains(&x)), "{depth}: {:?}", first_white(d, 3, 1, 0)); + // One step back is the grayscale document at its own size and resolution. + s.execute("edit.undo", json!({})).unwrap(); + let d = doc(&s); + assert_eq!((d.size.width, d.size.height, d.resolution_dpi, d.mode), (256, 4, 72.0, ColorMode::Grayscale), "{depth}"); + s.execute("image.mode.bitmap", json!({"method": "diffusion", "resolution": 36})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).size.height, doc(&s).resolution_dpi), (128, 2, 36.0), "{depth}"); + } + // Without `resolution`, the input resolution: the size stays. + let mut s = ramp(256, 4, 8, 300.0); + s.execute("image.mode.bitmap", json!({"method": "threshold"})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).resolution_dpi), (256, 300.0)); + assert_eq!(first_white(doc(&s), 0, 1, 0), Some(128)); +} + +#[test] +fn bitmap_halftone_screen_is_laid_out_at_the_output_resolution() { + // The same 10 lines/inch screen has twice the cell (in pixels) at twice the resolution: the + // output equals the 72 ppi screen of the image upsampled first. + let mut a = ramp(64, 64, 8, 72.0); + a.execute("image.mode.bitmap", json!({"method": "halftone", "frequency": 10, "angle": 0, "resolution": 144})).unwrap(); + let mut b = ramp(64, 64, 8, 72.0); + b.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic", "keepPrintSize": true})).unwrap(); + b.execute("image.mode.bitmap", json!({"method": "halftone", "frequency": 10, "angle": 0})).unwrap(); + let (da, db) = (doc(&a), doc(&b)); + assert_eq!(da.size, db.size); + let (sa, sb) = (da.layers[0].surface().unwrap(), db.layers[0].surface().unwrap()); + let r = da.bounds(); + assert_eq!(sa.read_region(r), sb.read_region(r)); +} + +#[test] +fn bitmap_custom_pattern_thresholds_against_the_tiled_pattern() { + // Measured in Photoshop on a 0..255 ramp: a 7x1 pattern 0, 40 .. 240 turns column x white + // from level 237, 201, 164, 128, 92, 55, 19 (by x % 7): the lighter the pattern pixel, the + // sooner. A 1x3 pattern 30 / 220 / 120 does the same down the rows. + for depth in [8, 16] { + let mut s = ramp(256, 3, depth, 72.0); + add_pattern(&mut s, "Ramp 7", 7, 1, &[0, 40, 80, 120, 160, 200, 240]); + add_pattern(&mut s, "Rows 3", 1, 3, &[30, 220, 120]); + let r = s.execute("image.mode.bitmap", json!({"method": "customPattern", "pattern": "Ramp 7"})).unwrap(); + assert_eq!(r["width"], 256); + let d = doc(&s); + assert_eq!(d.mode, ColorMode::Bitmap); + let firsts: Vec = (0..7).map(|k| first_white(d, 0, 7, k).unwrap()).collect(); + // The first column at or past each level in its residue class. + let expect: Vec = [237, 201, 164, 128, 92, 55, 19].iter().enumerate().map(|(k, t)| (k as i32..256).step_by(7).find(|x| x >= t).unwrap()).collect(); + assert_eq!(firsts, expect, "{depth}"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({"method": "customPattern", "pattern": "Rows 3"})).unwrap(); + let rows: Vec = (0..3).map(|y| first_white(doc(&s), y, 1, 0).unwrap()).collect(); + assert_eq!(rows, [213, 43, 128], "{depth}"); + } +} + +#[test] +fn bitmap_rejects_bad_resolutions_and_patterns_without_editing_the_document() { + let mut s = ramp(64, 4, 16, 72.0); + let before = s.active().unwrap().history.past_len(); + let bad = [ + json!({"resolution": 0}), + json!({"resolution": -72}), + json!({"resolution": 0.5}), + json!({"resolution": 30_001}), + json!({"resolution": 1e39}), + json!({"resolution": "high"}), + json!({"resolution": [72]}), + json!({"method": "customPattern", "pattern": "no such pattern"}), + json!({"method": "customPattern", "pattern": 7}), + json!({"method": "custom"}), + ]; + for p in bad { + assert!(s.execute("image.mode.bitmap", p.clone()).is_err(), "{p}"); + assert_eq!(s.active().unwrap().history.past_len(), before, "{p}"); + let d = doc(&s); + assert_eq!((d.mode, d.size.width, d.resolution_dpi), (ColorMode::Grayscale, 64, 72.0), "{p}"); + } + // NaN can't be written in JSON; null is "not given" (the input resolution). + s.execute("image.mode.bitmap", json!({"resolution": null})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).resolution_dpi), (64, 72.0)); + s.execute("edit.undo", json!({})).unwrap(); + // The bounds themselves are fine. + s.execute("image.mode.bitmap", json!({"resolution": 1})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).size.height, doc(&s).resolution_dpi), (1, 1, 1.0)); +} + #[test] fn duotone_inks_and_display() { let mut s = session(16, 8, 8, "gray"); diff --git a/crates/ui-egui/src/bitmap_dialog.rs b/crates/ui-egui/src/bitmap_dialog.rs new file mode 100644 index 00000000000..04ef5b1d796 --- /dev/null +++ b/crates/ui-egui/src/bitmap_dialog.rs @@ -0,0 +1,166 @@ +//! Image › Mode › Bitmap… (#5559), laid out like Photoshop's dialog: Resolution (Input, read-only, +//! and Output, in pixels/inch or pixels/centimeter), Method (Use: 50% Threshold, Pattern Dither, +//! Diffusion Dither, Halftone Screen, Custom Pattern) with the Custom Pattern picker, enabled only +//! for Custom Pattern. The Halftone Screen settings (Frequency in lines/inch or lines/centimeter, +//! Angle, Shape), which Photoshop asks for in a second dialog after OK, show here only while +//! Halftone Screen is the method. +//! +//! It is the schema dialog of `image.mode.bitmap` with its own body: the fields are the command's +//! params (`resolution` in pixels/inch, `frequency` in lines/inch), so OK, the live preview, +//! `ui.dialog.set` and `ui.dialog.confirm` work as for every schema dialog. The units are view +//! state (`__resUnit`, `__freqUnit`). + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::theme::Tokens; + +pub(crate) const COMMAND: &str = "image.mode.bitmap"; + +/// Centimetres per inch. +const CM: f32 = 2.54; +/// The command's Output resolution range (pixels/inch). +const RESOLUTION: (f32, f32) = (1.0, 30_000.0); +/// The command's Halftone Screen frequency range (lines/inch). +const FREQUENCY: (f32, f32) = (1.0, 999.0); + +const METHODS: [(&str, &str); 5] = [ + ("threshold", "50% Threshold"), + ("pattern", "Pattern Dither"), + ("diffusion", "Diffusion Dither"), + ("halftone", "Halftone Screen"), + ("customPattern", "Custom Pattern"), +]; + +/// Photoshop's order of the Halftone Screen shapes. +const SHAPES: [(&str, &str); 6] = + [("round", "Round"), ("diamond", "Diamond"), ("ellipse", "Ellipse"), ("line", "Line"), ("square", "Square"), ("cross", "Cross")]; + +/// Is this dialog the Bitmap dialog? (A plug-in's own `__spec` dialog never is.) +pub(crate) fn owns(f: &Map) -> bool { + f.get("__filter").and_then(Value::as_bool) == Some(true) && f.get("__command").and_then(Value::as_str) == Some(COMMAND) && !f.contains_key("__spec") +} + +/// Open defaults: Output starts at the document's resolution (Input, as in Photoshop), Custom +/// Pattern at the Patterns panel's pattern. +pub(crate) fn defaults(app: &PhotocraftApp, f: &mut Map) { + let input = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi); + f.insert("__inputResolution".into(), json!(input)); + f.insert("resolution".into(), json!(input)); + match photocraft_engine::pattern_cmds::resolve(&app.session, "") { + Some(p) => f.insert("pattern".into(), json!(p.id)), + None => f.remove("pattern"), + }; + f.entry("__resUnit").or_insert_with(|| json!("ppi")); + f.entry("__freqUnit").or_insert_with(|| json!("lpi")); +} + +fn num(f: &Map, key: &str, default: f32) -> f32 { + f.get(key).and_then(Value::as_f64).map_or(default, |v| v as f32) +} + +fn text(f: &Map, key: &str, default: &str) -> String { + f.get(key).and_then(Value::as_str).unwrap_or(default).to_string() +} + +fn label(ui: &mut egui::Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + ui.add_sized([96.0, 20.0], egui::Label::new(egui::RichText::new(text).color(t.text_dim)).truncate()); +} + +/// A value stored in per-inch units, edited in per-inch or per-centimeter ones: `field` holds the +/// per-inch value, `unit` the view's unit (`per_cm` when its value is per centimeter). +fn per_unit_row(ui: &mut egui::Ui, f: &mut Map, field: &str, range: (f32, f32), default: f32, unit: &str, units: [(&str, &str); 2]) { + let per_inch = num(f, field, default); + let mut cur = text(f, unit, units[0].0); + let per_cm = cur == units[1].0; + let k = if per_cm { CM } else { 1.0 }; + let mut shown = per_inch / k; + if crate::widgets::value_field(ui, &mut shown, range.0 / k..=range.1 / k, "", 70.0).changed() { + f.insert(field.into(), json!(((shown * k).clamp(range.0, range.1) * 1000.0).round() / 1000.0)); + } + let opts: Vec<(String, &str)> = units.iter().map(|(id, l)| (id.to_string(), *l)).collect(); + if crate::widgets::dropdown(ui, &format!("bitmap-{unit}"), &mut cur, &opts, 150.0) { + f.insert(unit.into(), json!(cur)); + } +} + +/// The dialog body. +pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + ui.spacing_mut().item_spacing.y = 6.0; + let res_units = [("ppi", tl!("Pixels/Inch")), ("ppcm", tl!("Pixels/Centimeter"))]; + + crate::widgets::section_label(ui, tl!("Resolution")); + crate::widgets::hairline(ui); + ui.horizontal(|ui| { + label(ui, tl!("Input:")); + let input = num(f, "__inputResolution", 72.0); + let (v, unit) = if text(f, "__resUnit", "ppi") == "ppcm" { (input / CM, res_units[1].1) } else { (input, res_units[0].1) }; + ui.label(egui::RichText::new(format!("{} {unit}", crate::widgets::fmt_num_prec(f64::from(v), 3))).color(t.text)); + }); + ui.horizontal(|ui| { + label(ui, tl!("Output:")); + let input = num(f, "__inputResolution", 72.0); + per_unit_row(ui, f, "resolution", RESOLUTION, input, "__resUnit", res_units); + }); + + ui.add_space(4.0); + crate::widgets::section_label(ui, tl!("Method")); + crate::widgets::hairline(ui); + let mut method = text(f, "method", "diffusion"); + ui.horizontal(|ui| { + label(ui, tl!("Use:")); + let opts: Vec<(String, &str)> = METHODS.iter().map(|(id, l)| (id.to_string(), tl!(l))).collect(); + if crate::widgets::dropdown(ui, "bitmap-method", &mut method, &opts, 190.0) { + f.insert("method".into(), json!(method)); + } + }); + // Photoshop greys the pattern out unless the method is Custom Pattern. + ui.horizontal(|ui| { + ui.add_enabled_ui(method == "customPattern", |ui| { + label(ui, tl!("Custom Pattern:")); + let pat = text(f, "pattern", ""); + if app.session.patterns.items.is_empty() { + ui.label(egui::RichText::new(tl!("No patterns")).color(t.text_faint)); + } else if let Some(id) = crate::preset_panels::pattern_picker(app, ui, &pat) { + f.insert("pattern".into(), json!(id)); + } + }); + }); + + if method == "halftone" { + ui.add_space(4.0); + crate::widgets::section_label(ui, tl!("Halftone Screen")); + crate::widgets::hairline(ui); + ui.horizontal(|ui| { + label(ui, tl!("Frequency:")); + per_unit_row(ui, f, "frequency", FREQUENCY, 53.0, "__freqUnit", [("lpi", tl!("Lines/Inch")), ("lpcm", tl!("Lines/Centimeter"))]); + }); + ui.horizontal(|ui| { + label(ui, tl!("Angle:")); + let mut angle = num(f, "angle", 45.0); + if crate::widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 70.0).changed() { + f.insert("angle".into(), json!((angle.clamp(-180.0, 180.0) * 10.0).round() / 10.0)); + } + }); + ui.horizontal(|ui| { + label(ui, tl!("Shape:")); + let mut shape = text(f, "shape", "round"); + let opts: Vec<(String, &str)> = SHAPES.iter().map(|(id, l)| (id.to_string(), tl!(l))).collect(); + if crate::widgets::dropdown(ui, "bitmap-shape", &mut shape, &opts, 150.0) { + f.insert("shape".into(), json!(shape)); + } + }); + } + + if let Some(mut preview) = f.get("__preview").and_then(Value::as_bool) { + ui.add_space(4.0); + crate::widgets::checkbox(ui, &mut preview, tl!("Preview")); + f.insert("__preview".into(), json!(preview)); + } +} + +#[cfg(test)] +#[path = "bitmap_dialog_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/bitmap_dialog_tests.rs b/crates/ui-egui/src/bitmap_dialog_tests.rs new file mode 100644 index 00000000000..8c7a45b12fe --- /dev/null +++ b/crates/ui-egui/src/bitmap_dialog_tests.rs @@ -0,0 +1,116 @@ +use serde_json::{Map, Value, json}; + +use super::*; + +fn app(dpi: f64, depth: u64) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "mode": "grayscale", "depth": depth, "resolution": dpi})).unwrap(); + app +} + +fn open(app: &mut PhotocraftApp) -> u64 { + crate::filter_dialog::open(app, COMMAND).unwrap() +} + +fn fields(app: &PhotocraftApp, id: u64) -> Map { + app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone() +} + +/// The text the body draws for `f`, and `f` after the frame. +fn drawn(app: &PhotocraftApp, mut f: Map) -> (Vec, Map) { + fn collect(shape: &egui::Shape, text: &mut Vec) { + match shape { + egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| body(app, ui, &mut f)); + out.textures_delta.clear(); + let mut text = Vec::new(); + for s in &out.shapes { + collect(&s.shape, &mut text); + } + (text, f) +} + +#[test] +fn opens_with_output_at_the_input_resolution_and_a_pattern_id() { + let mut app = app(300.0, 16); + let id = open(&mut app); + let f = fields(&app, id); + assert!(owns(&f)); + assert_eq!(f["__inputResolution"].as_f64(), Some(300.0)); + assert_eq!(f["resolution"].as_f64(), Some(300.0)); + assert!(f["pattern"].is_string(), "the schema's placeholder 0 is replaced by a pattern id: {:?}", f["pattern"]); + let p = crate::filter_dialog::params_of(&f); + assert!(p.as_object().unwrap().keys().all(|k| !k.starts_with("__")), "{p}"); +} + +#[test] +fn halftone_settings_show_only_for_halftone_screen() { + let mut app = app(72.0, 8); + let id = open(&mut app); + let mut f = fields(&app, id); + for (method, halftone) in [("diffusion", false), ("threshold", false), ("pattern", false), ("customPattern", false), ("halftone", true)] { + f.insert("method".into(), json!(method)); + let (text, after) = drawn(&app, f.clone()); + for label in ["Frequency:", "Angle:", "Shape:"] { + assert_eq!(text.iter().any(|t| t == label), halftone, "{method}: {label} in {text:?}"); + } + for label in ["Input:", "Output:", "Use:", "Custom Pattern:"] { + assert!(text.iter().any(|t| t == label), "{method}: {label} in {text:?}"); + } + // Drawing the dialog changes no value (no unit round trip drift). + assert_eq!(crate::filter_dialog::params_of(&after), crate::filter_dialog::params_of(&f), "{method}"); + } +} + +#[test] +fn pixels_per_centimeter_show_the_same_resolution() { + let mut app = app(254.0, 8); + let id = open(&mut app); + let mut f = fields(&app, id); + f.insert("__resUnit".into(), json!("ppcm")); + let (text, after) = drawn(&app, f.clone()); + assert!(text.iter().any(|t| t.starts_with("100 ")), "Input 254 ppi is 100 px/cm: {text:?}"); + assert_eq!(after["resolution"].as_f64(), Some(254.0), "the param stays in pixels/inch"); +} + +#[test] +fn ok_resamples_to_the_output_resolution() { + for depth in [8, 16] { + let mut app = app(72.0, depth); + let id = open(&mut app); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("method".into(), json!("threshold")); + d.fields.insert("resolution".into(), json!(144)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height, doc.resolution_dpi, doc.mode), (80, 40, 144.0, photocraft_color::ColorMode::Bitmap), "{depth}"); + } +} + +#[test] +fn ok_with_custom_pattern_and_halftone_screen_converts() { + for method in ["customPattern", "halftone"] { + let mut app = app(72.0, 8); + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("method".into(), json!(method)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.mode), (40, photocraft_color::ColorMode::Bitmap), "{method}"); + } +} + +#[test] +fn the_preview_keeps_the_canvas_size() { + let app = app(72.0, 8); + let st = app.session.active().unwrap(); + let p = json!({"method": "threshold", "resolution": 144}); + let shown = crate::filter_dialog::preview_document(&st.doc, st.active_layer, COMMAND, &p, 1).unwrap(); + assert_eq!((shown.size.width, shown.size.height), (40, 20)); + assert_eq!(shown.mode, photocraft_color::ColorMode::Bitmap); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e27411b7e06..182930232ea 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -361,7 +361,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // parameters reserves its own space (#3769). let room = (ctx.content_rect().height() - DIALOG_CHROME - crate::filter_preview_ui::reserved_height(&fields)).max(120.0); let body = |ui: &mut egui::Ui, fields: &mut serde_json::Map| { - egui::ScrollArea::vertical().id_salt(id.with("body")).max_height(room).show(ui, |ui| crate::filter_dialog::body(ui, fields)); + egui::ScrollArea::vertical().id_salt(id.with("body")).max_height(room).show(ui, |ui| { + if crate::bitmap_dialog::owns(fields) { + crate::bitmap_dialog::body(app, ui, fields); + } else { + crate::filter_dialog::body(ui, fields); + } + }); // The in-dialog preview window sits under the scrolling parameters (#3769), // so it never shifts them. crate::filter_preview_ui::window(app, d.id, ui, fields); diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index a908df5eba3..f8bc91c23b7 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -396,6 +396,9 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map