Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Image: Bitmap dialog with Output resolution and per-method settings (#5559)

David Mann24a86a3f6fa6
diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs
index 589c9f196..0d428f308 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<f32> {
+ 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<usize> = (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::<Vec<_>>();
+ let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240]));
+ assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::<Vec<_>>(), [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::<Vec<_>>(), [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::<Vec<_>>(), [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 3e870aa68..0982a387e 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -244,7 +244,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 fe22a192c..2bcb2e4cf 100644
--- a/crates/engine/src/mode_cmds.rs
+++ b/crates/engine/src/mode_cmds.rs
@@ -388,9 +388,48 @@ fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- Bitmap ----------
+/// Bitmap's Output resolution range (ppi): what a new document may have.
+const BITMAP_RESOLUTION: std::ops::RangeInclusive<f64> = 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<f32>, 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<f32> = 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<Value> {
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,
@@ -403,21 +442,40 @@ fn bitmap(s: &mut Session, p: &Value) -> Result<Value> {
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<f32> = 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 ----------
@@ -523,7 +581,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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 d6d020699..2a556adde 100644
--- a/crates/engine/src/mode_cmds/tests.rs
+++ b/crates/engine/src/mode_cmds/tests.rs
@@ -323,6 +323,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<i32> {
+ 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<f32> = 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<i32> = (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<i32> = [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<i32> = (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 000000000..04ef5b1d7
--- /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<String, Value>) -> 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<String, Value>) {
+ 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<String, Value>, key: &str, default: f32) -> f32 {
+ f.get(key).and_then(Value::as_f64).map_or(default, |v| v as f32)
+}
+
+fn text(f: &Map<String, Value>, 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<String, Value>, 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<String, Value>) {
+ 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 000000000..8c7a45b12
--- /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<String, Value> {
+ 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<String, Value>) -> (Vec<String>, Map<String, Value>) {
+ fn collect(shape: &egui::Shape, text: &mut Vec<String>) {
+ 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 2930889ba..2e1e22475 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -324,7 +324,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<String, Value>| {
- 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 3da073520..7e6183a4c 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -388,6 +388,9 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map<S
if command == "edit.assignProfile" {
assign_profile_defaults(app, fields);
}
+ if command == crate::bitmap_dialog::COMMAND {
+ crate::bitmap_dialog::defaults(app, fields);
+ }
}
/// Assign Profile offers only the profiles the document's colour mode can take (#4951): the
@@ -890,6 +893,13 @@ pub(crate) fn preview_document_for_target(
let doc_id = proxy.id;
s.add_document(proxy, None);
let mut p = params.clone();
+ // Bitmap's Output resolution resamples the image: the preview keeps the canvas's size and
+ // resolution, so its dots and halftone screen show at their printed size (#5559).
+ if command == crate::bitmap_dialog::COMMAND
+ && let Some(o) = p.as_object_mut()
+ {
+ o.remove("resolution");
+ }
add_source_documents(&mut s, doc_id, command, &mut p, documents, run_k);
if let Some(id) = active {
s.select_layer(id).ok()?;
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 5cfc0f8ff..74af5eab6 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -3783,3 +3783,14 @@ navigator Zoom Zvětšení
# View › Guides › right-click a guide
Edit Selected Guides Upravit vybraná vodítka
Clear Selected Guides Vymazat vybraná vodítka
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% práh
+ Pattern Dither Rozptyl se vzorkem
+ Diffusion Dither Difuzní rozptyl
+ Halftone Screen Polotónový rastr
+ Custom Pattern Vlastní vzorek
+ Frequency: Frekvence:
+ Lines/Inch Linky/palec
+ Lines/Centimeter Linky/centimetr
+ Ellipse Elipsa
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 05ac77803..9937ac005 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -3177,3 +3177,14 @@ curves Smooth Glätten
# View › Guides › right-click a guide
Edit Selected Guides Ausgewählte Hilfslinien bearbeiten
Clear Selected Guides Ausgewählte Hilfslinien löschen
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50 %-Schwellenwert
+ Pattern Dither Musterdither
+ Diffusion Dither Diffusionsdither
+ Halftone Screen Rasterung
+ Custom Pattern Eigenes Muster
+ Frequency: Frequenz:
+ Lines/Inch Linien/Zoll
+ Lines/Centimeter Linien/Zentimeter
+ Ellipse Ellipse
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index c6c5ff8f6..3fc33153d 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3875,3 +3875,14 @@ curves Smooth Εξομάλυνση
# View › Guides › right-click a guide
Edit Selected Guides Επεξεργασία επιλεγμένων οδηγών
Clear Selected Guides Απαλοιφή επιλεγμένων οδηγών
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Κατώφλι 50%
+ Pattern Dither Πρόσμιξη μοτίβου
+ Diffusion Dither Πρόσμιξη διάχυσης
+ Halftone Screen Ράστερ ημιτόνων
+ Custom Pattern Προσαρμοσμένο μοτίβο
+ Frequency: Συχνότητα:
+ Lines/Inch Γραμμές/ίντσα
+ Lines/Centimeter Γραμμές/εκατοστό
+ Ellipse Έλλειψη
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index e24171195..da05f3bdb 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -4137,3 +4137,14 @@ navigator Zoom Zoom
# View › Guides › right-click a guide
Edit Selected Guides Editar guías seleccionadas
Clear Selected Guides Borrar guías seleccionadas
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Umbral 50%
+ Pattern Dither Tramado de motivo
+ Diffusion Dither Tramado de difusión
+ Halftone Screen Trama de semitonos
+ Custom Pattern Motivo personalizado
+ Frequency: Frecuencia:
+ Lines/Inch Líneas/pulgada
+ Lines/Centimeter Líneas/centímetro
+ Ellipse Elipse
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index db40d97ab..b0a7d4022 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -3179,3 +3179,15 @@ curves Smooth Lisser
# View › Guides › right-click a guide
Edit Selected Guides Modifier les repères sélectionnés
Clear Selected Guides Effacer les repères sélectionnés
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Seuil 50 %
+ Pattern Dither Simulation par motif
+ Diffusion Dither Simulation par diffusion
+ Halftone Screen Trame de demi-teintes
+ Custom Pattern Motif personnalisé
+ Frequency: Fréquence :
+ Lines/Inch Lignes/pouce
+ Lines/Centimeter Lignes/centimètre
+ Ellipse Ellipse
+ Cross Croix
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 0404b429c..3a1e26455 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -4094,3 +4094,14 @@ cameraRaw Yellow Sárga
# View › Guides › right-click a guide
Edit Selected Guides Kijelölt segédvonalak szerkesztése
Clear Selected Guides Kijelölt segédvonalak törlése
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50%-os küszöb
+ Pattern Dither Mintázatos keverés
+ Diffusion Dither Diffúziós keverés
+ Halftone Screen Féltónusrács
+ Custom Pattern Egyéni mintázat
+ Frequency: Gyakoriság:
+ Lines/Inch Vonal/hüvelyk
+ Lines/Centimeter Vonal/centiméter
+ Ellipse Ellipszis
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 544ead05a..f9a199b65 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -3166,3 +3166,15 @@ curves Smooth Haluskan
# View › Guides › right-click a guide
Edit Selected Guides Edit Panduan Terpilih
Clear Selected Guides Hapus Panduan Terpilih
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Threshold 50%
+ Pattern Dither Dither Pola
+ Diffusion Dither Dither Difusi
+ Halftone Screen Layar Halftone
+ Custom Pattern Pola Kustom
+ Frequency: Frekuensi:
+ Lines/Inch Garis/Inci
+ Lines/Centimeter Garis/Sentimeter
+ Ellipse Elips
+ Cross Silang
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 40b468926..f963107fd 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -4296,3 +4296,14 @@ shape Appearance Aspetto
# View › Guides › right-click a guide
Edit Selected Guides Modifica guide selezionate
Clear Selected Guides Cancella guide selezionate
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Soglia 50%
+ Pattern Dither Dithering pattern
+ Diffusion Dither Dithering diffusione
+ Halftone Screen Retino mezzetinte
+ Custom Pattern Pattern personalizzato
+ Frequency: Frequenza:
+ Lines/Inch Linee/Pollice
+ Lines/Centimeter Linee/Centimetro
+ Ellipse Ellisse
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 1d64bf868..cd944b6d2 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3851,3 +3851,14 @@ curves Smooth スムーズ
# View › Guides › right-click a guide
Edit Selected Guides 選択したガイドを編集
Clear Selected Guides 選択したガイドを消去
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% しきい値
+ Pattern Dither パターンディザ
+ Diffusion Dither 拡散ディザ
+ Halftone Screen ハーフトーンスクリーン
+ Custom Pattern カスタムパターン
+ Frequency: 線数:
+ Lines/Inch 線/インチ
+ Lines/Centimeter 線/センチメートル
+ Ellipse 楕円
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index e76a3c982..ad588433c 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3353,3 +3353,14 @@ curves Smooth 매끄럽게
# View › Guides › right-click a guide
Edit Selected Guides 선택한 안내선 편집
Clear Selected Guides 선택한 안내선 지우기
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% 한계값
+ Pattern Dither 패턴 디더
+ Diffusion Dither 확산 디더
+ Halftone Screen 하프톤 스크린
+ Custom Pattern 사용자 정의 패턴
+ Frequency: 빈도:
+ Lines/Inch 선/인치
+ Lines/Centimeter 선/센티미터
+ Ellipse 타원
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 2c9416c70..8bfc57f59 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3935,3 +3935,14 @@ curves Smooth Vloeiend maken
# View › Guides › right-click a guide
Edit Selected Guides Geselecteerde hulplijnen bewerken
Clear Selected Guides Geselecteerde hulplijnen wissen
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% drempel
+ Pattern Dither Patroondithering
+ Diffusion Dither Diffusiedithering
+ Halftone Screen Halftoonraster
+ Custom Pattern Aangepast patroon
+ Frequency: Frequentie:
+ Lines/Inch Lijnen/inch
+ Lines/Centimeter Lijnen/centimeter
+ Ellipse Ellips
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index eee1e61a9..96fe66724 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3773,3 +3773,14 @@ curves Smooth Wygładź
# View › Guides › right-click a guide
Edit Selected Guides Edytuj zaznaczone prowadnice
Clear Selected Guides Usuń zaznaczone prowadnice
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Próg 50%
+ Pattern Dither Rozpraszanie wzorkiem
+ Diffusion Dither Rozpraszanie dyfuzyjne
+ Halftone Screen Raster półtonowy
+ Custom Pattern Własny wzór
+ Frequency: Częstotliwość:
+ Lines/Inch Linii/cal
+ Lines/Centimeter Linii/centymetr
+ Ellipse Elipsa
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 3e10fe7db..fb6241131 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3965,3 +3965,14 @@ layerLabel No Color Sem cor
# View › Guides › right-click a guide
Edit Selected Guides Editar guias selecionadas
Clear Selected Guides Limpar guias selecionadas
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Limiar de 50%
+ Pattern Dither Pontilhamento de padrão
+ Diffusion Dither Pontilhamento de difusão
+ Halftone Screen Retícula de meio-tom
+ Custom Pattern Padrão personalizado
+ Frequency: Frequência:
+ Lines/Inch Linhas/polegada
+ Lines/Centimeter Linhas/centímetro
+ Ellipse Elipse
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 862788630..b332c660e 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -3144,3 +3144,16 @@ curves Smooth Сгладить
# View › Guides › right-click a guide
Edit Selected Guides Изменить выбранные направляющие
Clear Selected Guides Удалить выбранные направляющие
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Порог 50%
+ Pattern Dither Регулярный дизеринг
+ Diffusion Dither Диффузионный дизеринг
+ Halftone Screen Полутоновый растр
+ Custom Pattern Свой узор
+ Frequency: Линиатура:
+ Lines/Inch Линий/дюйм
+ Lines/Centimeter Линий/см
+ Ellipse Эллипс
+ Diamond Ромб
+ Cross Крест
diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv
index b91b67b3e..e900ca1f4 100644
--- a/crates/ui-egui/src/i18n/sr.tsv
+++ b/crates/ui-egui/src/i18n/sr.tsv
@@ -4248,3 +4248,14 @@ shape Appearance Izgled
# View › Guides › right-click a guide
Edit Selected Guides Uredi izabrane vodilje
Clear Selected Guides Ukloni izabrane vodilje
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Prag 50%
+ Pattern Dither Dither šarom
+ Diffusion Dither Difuzni dither
+ Halftone Screen Polutonski raster
+ Custom Pattern Prilagođena šara
+ Frequency: Frekvencija:
+ Lines/Inch Linija/inč
+ Lines/Centimeter Linija/centimetar
+ Ellipse Elipsa
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index 4c8f06ccc..dc204b027 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -3905,3 +3905,14 @@ cameraData Lens Lens
# View › Guides › right-click a guide
Edit Selected Guides Seçili Kılavuzları Düzenle
Clear Selected Guides Seçili Kılavuzları Temizle
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold %50 Eşik
+ Pattern Dither Desen Titreklik
+ Diffusion Dither Difüzyon Titreklik
+ Halftone Screen Yarım Ton Tarama
+ Custom Pattern Özel Desen
+ Frequency: Frekans:
+ Lines/Inch Çizgi/İnç
+ Lines/Centimeter Çizgi/Santimetre
+ Ellipse Elips
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 39597c15c..334bccfbc 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3874,3 +3874,14 @@ curves Smooth Згладити
# View › Guides › right-click a guide
Edit Selected Guides Редагувати вибрані напрямні
Clear Selected Guides Очистити вибрані напрямні
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Поріг 50%
+ Pattern Dither Візерунковий дизеринг
+ Diffusion Dither Дифузійний дизеринг
+ Halftone Screen Півтоновий растр
+ Custom Pattern Довільний візерунок
+ Frequency: Лініатура:
+ Lines/Inch Ліній/дюйм
+ Lines/Centimeter Ліній/сантиметр
+ Ellipse Еліпс
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index ac7123d85..1c50457d9 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -3661,3 +3661,14 @@ curves Smooth Làm mượt
# View › Guides › right-click a guide
Edit Selected Guides Sửa đường căn đã chọn
Clear Selected Guides Xóa đường căn đã chọn
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold Ngưỡng 50%
+ Pattern Dither Hòa sắc họa tiết
+ Diffusion Dither Hòa sắc khuếch tán
+ Halftone Screen Màn bán sắc
+ Custom Pattern Họa tiết tùy chỉnh
+ Frequency: Tần số:
+ Lines/Inch Đường/inch
+ Lines/Centimeter Đường/centimet
+ Ellipse Elip
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 2307739ed..aaf5a63a6 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2790,3 +2790,16 @@ curves Smooth 平滑
# View › Guides › right-click a guide
Edit Selected Guides 编辑所选参考线
Clear Selected Guides 清除所选参考线
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% 阈值
+ Pattern Dither 图案仿色
+ Diffusion Dither 扩散仿色
+ Halftone Screen 半调网屏
+ Custom Pattern 自定图案
+ Frequency: 频率:
+ Lines/Inch 线/英寸
+ Lines/Centimeter 线/厘米
+ Ellipse 椭圆
+ Cross 十字
+ Method 方法
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 478489f8c..5212df44f 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2775,3 +2775,16 @@ curves Smooth 平滑
# View › Guides › right-click a guide
Edit Selected Guides 編輯所選參考線
Clear Selected Guides 清除所選參考線
+
+# Image › Mode › Bitmap (#5559)
+ 50% Threshold 50% 臨界值
+ Pattern Dither 圖樣混色
+ Diffusion Dither 擴散混色
+ Halftone Screen 半色調網屏
+ Custom Pattern 自訂圖樣
+ Frequency: 頻率:
+ Lines/Inch 線/英吋
+ Lines/Centimeter 線/公分
+ Ellipse 橢圓
+ Cross 十字
+ Method 方法
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 5929e9338..37d046a1d 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -25,6 +25,7 @@ pub mod anchor_tools;
pub mod artboard_tool;
pub mod artboard_ui;
pub(crate) mod background_redraw;
+pub(crate) mod bitmap_dialog;
mod blend_keys;
pub(crate) mod blend_preview;
pub mod blur_pins;