Skip to content

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

Indexed Color: integer counts, palette stops and asynchronous previews (#1741)

Elvis33LEadc1f76df4a7
diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs
index 7c4bfbbe3..3b6feb20f 100644
--- a/crates/algo/src/quantize.rs
+++ b/crates/algo/src/quantize.rs
@@ -8,6 +8,9 @@
use photocraft_color::convert::srgb_to_lab;
use serde::{Deserialize, Serialize};
+mod nearest;
+use nearest::Nearest;
+
pub type Rgb8 = [u8; 3];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -233,10 +236,11 @@ fn kmeans(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) {
return;
}
for _ in 0..iters {
+ let lookup = Nearest::new(centers.iter().copied());
let mut sum = vec![[0.0f64; 3]; centers.len()];
let mut cnt = vec![0.0f64; centers.len()];
for (p, w) in pts {
- let i = nearest_f(centers, *p);
+ let i = lookup.find(*p);
for a in 0..3 {
sum[i][a] += f64::from(p[a]) * f64::from(*w);
}
@@ -250,17 +254,6 @@ fn kmeans(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) {
}
}
-fn nearest_f(centers: &[[f32; 3]], p: [f32; 3]) -> usize {
- let mut best = (f32::MAX, 0);
- for (i, c) in centers.iter().enumerate() {
- let d = (c[0] - p[0]).powi(2) + (c[1] - p[1]).powi(2) + (c[2] - p[2]).powi(2);
- if d < best.0 {
- best = (d, i);
- }
- }
- best.1
-}
-
fn lab_to_rgb8(lab: [f32; 3]) -> Rgb8 {
photocraft_color::convert::lab_to_srgb(lab).map(to8)
}
@@ -271,7 +264,13 @@ pub fn build_palette(px: &[[f32; 4]], kind: PaletteKind, colors: usize, forced:
let colors = colors.clamp(2, 256);
let mut pal = forced_colors(forced);
let room = colors.saturating_sub(pal.len());
- let hist = histogram(px);
+ // Fixed palettes, or computed palettes already filled by forced colours, need no scan.
+ // Exact still counts every colour to enforce its 256-colour limit.
+ let hist = if kind == PaletteKind::Exact || (room > 0 && matches!(kind, PaletteKind::Adaptive | PaletteKind::Perceptual | PaletteKind::Selective)) {
+ histogram(px)
+ } else {
+ Vec::new()
+ };
let computed: Vec<Rgb8> = match kind {
PaletteKind::Exact => {
if hist.len() > 256 {
@@ -331,17 +330,6 @@ pub fn build_palette(px: &[[f32; 4]], kind: PaletteKind, colors: usize, forced:
Ok(pal)
}
-fn nearest(pal: &[Rgb8], c: [f32; 3]) -> usize {
- let mut best = (f32::MAX, 0);
- for (i, e) in pal.iter().enumerate() {
- let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum();
- if d < best.0 {
- best = (d, i);
- }
- }
- best.1
-}
-
/// 8×8 Bayer threshold in -0.5..0.5.
pub fn bayer8(x: usize, y: usize) -> f32 {
const M: [u8; 64] = [
@@ -363,6 +351,19 @@ fn hash01(x: usize, y: usize, seed: u32) -> f32 {
/// index per pixel. Pixels with alpha < ½ become index `transparent` (and alpha 0) when given;
/// otherwise alpha is kept. `amount` (0..=1) scales diffusion / pattern / noise strength.
pub fn quantize(px: &mut [[f32; 4]], w: usize, pal: &[Rgb8], dither: Dither, amount: f32, transparent: Option<usize>) -> Vec<u8> {
+ let lookup = Nearest::new(pal.iter().map(|c| c.map(f32::from)));
+ quantize_with(px, w, pal, dither, amount, transparent, |c| lookup.find(c.map(|v| v * 255.0)))
+}
+
+fn quantize_with(
+ px: &mut [[f32; 4]],
+ w: usize,
+ pal: &[Rgb8],
+ dither: Dither,
+ amount: f32,
+ transparent: Option<usize>,
+ nearest: impl Fn([f32; 3]) -> usize + Sync,
+) -> Vec<u8> {
let h = px.len().checked_div(w).unwrap_or(0);
let mut idx = vec![0u8; px.len()];
// Typical palette spacing sets the ordered/noise dither amplitude.
@@ -390,7 +391,7 @@ pub fn quantize(px: &mut [[f32; 4]], w: usize, pal: &[Rgb8], dither: Dither, amo
_ => {}
}
let c = c.map(|v| v.clamp(0.0, 1.0));
- let k = nearest(pal, c);
+ let k = nearest(c);
*ip = k as u8;
let e = pal[k].map(|v| f32::from(v) / 255.0);
*p = [e[0], e[1], e[2], if transparent.is_some() { 1.0 } else { pv[3] }];
@@ -437,7 +438,7 @@ pub fn quantize(px: &mut [[f32; 4]], w: usize, pal: &[Rgb8], dither: Dither, amo
}
}
let c = c.map(|v| v.clamp(0.0, 1.0));
- let k = nearest(pal, c);
+ let k = nearest(c);
idx[i] = k as u8;
let e = pal[k].map(|v| f32::from(v) / 255.0);
if dither == Dither::Diffusion {
@@ -611,6 +612,71 @@ mod tests {
}
}
+ #[test]
+ #[ignore = "24 MP release timing comparison; run with --release --ignored --nocapture"]
+ fn indexed_diffusion_24mp_release_comparison() {
+ let source = gradient(6000, 4000);
+ let pal = web_palette();
+ for run in 0..4 {
+ let mut linear = source.clone();
+ let mut accelerated = source.clone();
+ let mut before = None;
+ let mut after = None;
+ // Reverse the order on alternating rounds; exclude the first round as warmup.
+ for old in if run % 2 == 0 { [true, false] } else { [false, true] } {
+ let start = std::time::Instant::now();
+ if old {
+ let indices = quantize_with(&mut linear, 6000, &pal, Dither::Diffusion, 0.75, None, |c| linear_rgb_nearest(&pal, c));
+ before = Some((start.elapsed().as_secs_f64() * 1000.0, indices));
+ } else {
+ let indices = quantize(&mut accelerated, 6000, &pal, Dither::Diffusion, 0.75, None);
+ after = Some((start.elapsed().as_secs_f64() * 1000.0, indices));
+ }
+ }
+ let (before_ms, before_indices) = before.unwrap();
+ let (after_ms, after_indices) = after.unwrap();
+ assert_eq!(before_indices.iter().zip(&after_indices).position(|(a, b)| a != b), None, "first differing index");
+ assert_eq!(linear.iter().zip(&accelerated).position(|(a, b)| a != b), None, "first differing pixel");
+ println!(
+ "{}",
+ serde_json::json!({"run":run,"warmup":run==0,"pixels":24_000_000,"palette_entries":216,"linear_ms":before_ms,"accelerated_ms":after_ms})
+ );
+ }
+ }
+
+ fn linear_rgb_nearest(pal: &[Rgb8], c: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ for (i, e) in pal.iter().enumerate() {
+ let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum();
+ if d < best.0 {
+ best = (d, i);
+ }
+ }
+ best.1
+ }
+
+ #[test]
+ fn all_dithers_match_the_original_linear_palette_search_exactly() {
+ let mut source = gradient(93, 61);
+ for (i, p) in source.iter_mut().enumerate() {
+ p[2] = (i % 71) as f32 / 70.0;
+ p[3] = [0.0, 0.2, 0.7, 1.0][i % 4];
+ }
+ for count in [8, 16, 32, 64, 128, 256] {
+ let pal = build_palette(&source, PaletteKind::Selective, count, Forced::BlackWhite).unwrap();
+ for dither in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] {
+ for transparent in [None, Some(1)] {
+ let mut actual = source.clone();
+ let mut expected = source.clone();
+ let indices = quantize(&mut actual, 93, &pal, dither, 0.75, transparent);
+ let old_indices = quantize_with(&mut expected, 93, &pal, dither, 0.75, transparent, |c| linear_rgb_nearest(&pal, c));
+ assert_eq!(indices, old_indices, "{count} {dither:?} {transparent:?}");
+ assert_eq!(actual, expected, "{count} {dither:?} {transparent:?}");
+ }
+ }
+ }
+ }
+
#[test]
fn quantize_maps_to_palette_with_each_dither() {
let pal = vec![[0, 0, 0], [255, 255, 255]];
diff --git a/crates/algo/src/quantize/nearest.rs b/crates/algo/src/quantize/nearest.rs
new file mode 100644
index 000000000..5395d4431
--- /dev/null
+++ b/crates/algo/src/quantize/nearest.rs
@@ -0,0 +1,146 @@
+//! Exact nearest colour search. Balanced median splits bound recursion to O(log n).
+//! Small palettes use a linear scan; no colour buckets, sampling or approximate distances.
+
+#[derive(Clone, Copy)]
+struct Entry {
+ point: [f32; 3],
+ index: usize,
+ axis: usize,
+}
+
+pub(super) struct Nearest {
+ entries: Vec<Entry>,
+ tree: bool,
+}
+
+#[inline]
+fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
+ (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)
+}
+
+impl Nearest {
+ pub(super) fn new(points: impl IntoIterator<Item = [f32; 3]>) -> Self {
+ let mut entries: Vec<Entry> = points.into_iter().enumerate().map(|(index, point)| Entry { point, index, axis: 0 }).collect();
+ let tree = entries.len() > 64 && entries.iter().all(|e| e.point.iter().all(|v| v.is_finite()));
+ if tree {
+ partition(&mut entries);
+ }
+ Self { entries, tree }
+ }
+
+ #[inline]
+ pub(super) fn find(&self, point: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ if !self.tree {
+ // This slice is still in original order, so strict comparison already breaks ties.
+ for entry in &self.entries {
+ let d = distance(entry.point, point);
+ if d < best.0 {
+ best = (d, entry.index);
+ }
+ }
+ } else if point.iter().all(|v| v.is_finite()) {
+ search(&self.entries, point, &mut best);
+ }
+ // Nonfinite queries against finite tree entries have only NaN/infinite distances;
+ // like the original scan, none beats f32::MAX and the fallback remains index zero.
+ best.1
+ }
+}
+
+#[inline]
+fn consider(entry: &Entry, point: [f32; 3], best: &mut (f32, usize)) {
+ let d = distance(entry.point, point);
+ // Original palette order breaks ties, independent of the tree's traversal order.
+ if d < best.0 || (d == best.0 && entry.index < best.1) {
+ *best = (d, entry.index);
+ }
+}
+
+fn partition(entries: &mut [Entry]) {
+ if entries.len() <= 8 {
+ return;
+ }
+ let mut lo = [f32::MAX; 3];
+ let mut hi = [f32::MIN; 3];
+ for e in entries.iter() {
+ for ((lo, hi), p) in lo.iter_mut().zip(hi.iter_mut()).zip(e.point) {
+ *lo = lo.min(p);
+ *hi = hi.max(p);
+ }
+ }
+ let axis = (0..3).max_by(|&a, &b| (hi[a] - lo[a]).total_cmp(&(hi[b] - lo[b]))).unwrap_or(0);
+ let mid = entries.len() / 2;
+ // `mid` comes from this slice's length, never from image data.
+ let (left, pivot, right) = entries.select_nth_unstable_by(mid, |a, b| a.point[axis].total_cmp(&b.point[axis]).then(a.index.cmp(&b.index)));
+ pivot.axis = axis;
+ partition(left);
+ partition(right);
+}
+
+fn search(entries: &[Entry], point: [f32; 3], best: &mut (f32, usize)) {
+ if entries.len() <= 8 {
+ for entry in entries {
+ consider(entry, point, best);
+ }
+ return;
+ }
+ let (left, rest) = entries.split_at(entries.len() / 2);
+ let Some((pivot, right)) = rest.split_first() else { return };
+ consider(pivot, point, best);
+ let delta = point[pivot.axis] - pivot.point[pivot.axis];
+ let (near, far) = if delta <= 0.0 { (left, right) } else { (right, left) };
+ if !near.is_empty() {
+ search(near, point, best);
+ }
+ // The splitting plane is a lower bound, using the same f32 arithmetic as distance().
+ // Equality must be searched as well: a lower original index may win a distance tie.
+ if !far.is_empty() && delta.powi(2) <= best.0 {
+ search(far, point, best);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn linear(points: &[[f32; 3]], query: [f32; 3]) -> usize {
+ let mut best = (f32::MAX, 0);
+ for (index, point) in points.iter().enumerate() {
+ let d = distance(*point, query);
+ if d < best.0 {
+ best = (d, index);
+ }
+ }
+ best.1
+ }
+
+ #[test]
+ fn search_matches_linear_oracle_in_rgb_and_lab_with_ties_and_nonfinite_input() {
+ let mut seed = 123456789u32;
+ let mut random = || {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (seed >> 8) as f32 / 16777215.0
+ };
+ for count in [0, 2, 8, 16, 17, 32, 64, 65, 128, 256] {
+ for (offset, scale) in [(0.0, 255.0), (-128.0, 256.0)] {
+ let points: Vec<[f32; 3]> = (0..count).map(|_| std::array::from_fn(|_| random() * scale + offset)).collect();
+ let lookup = Nearest::new(points.iter().copied());
+ for _ in 0..3000 {
+ let q = std::array::from_fn(|_| random() * scale + offset);
+ assert_eq!(lookup.find(q), linear(&points, q), "count {count}, {q:?}");
+ }
+ for q in [[f32::NAN; 3], [f32::INFINITY; 3], [f32::MAX; 3], [0.0; 3]] {
+ assert_eq!(lookup.find(q), linear(&points, q));
+ }
+ }
+ }
+ let mut points = vec![[1.0; 3]; 256];
+ points[250] = [-1.0; 3];
+ let lookup = Nearest::new(points.iter().copied());
+ assert_eq!(lookup.find([0.0; 3]), 0, "equidistant entries preserve original order");
+ points[0] = [f32::NAN; 3];
+ let lookup = Nearest::new(points.iter().copied());
+ assert_eq!(lookup.find([0.0; 3]), 1);
+ }
+}
diff --git a/crates/engine/examples/indexed_color_perf.rs b/crates/engine/examples/indexed_color_perf.rs
new file mode 100644
index 000000000..6dba948ff
--- /dev/null
+++ b/crates/engine/examples/indexed_color_perf.rs
@@ -0,0 +1,64 @@
+//! Local Indexed Color timing probe. Never commits or uploads the input image.
+//! Run in release: `cargo run -p photocraft-engine --release --example indexed_color_perf -- image.png`.
+//! Reports palette construction, diffusion and the complete CPU preview path (no GPU upload).
+
+use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind};
+use photocraft_engine::Session;
+use serde_json::json;
+use std::{error::Error, time::Instant};
+
+fn elapsed(start: Instant) -> f64 {
+ start.elapsed().as_secs_f64() * 1000.0
+}
+
+fn pixel_hash(px: &[[f32; 4]]) -> String {
+ let mut hash = blake3::Hasher::new();
+ for p in px {
+ for value in p {
+ hash.update(&value.to_bits().to_le_bytes());
+ }
+ }
+ hash.finalize().to_hex().to_string()
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let path = std::env::args().nth(1).ok_or("provide a local image path")?;
+ let bytes = photocraft_format::read::read_file(std::path::Path::new(&path))?;
+ let doc = photocraft_io::import(&path, &bytes)?.document;
+ let px = photocraft_compose::flatten(&doc).px;
+ println!("{}", json!({"width":doc.size.width,"height":doc.size.height,"preview_factor":1}));
+ for count in [8usize, 16, 32, 64, 128, 256] {
+ for run in 0..4 {
+ let start = Instant::now();
+ let clear = px.iter().any(|p| p[3] < 0.5);
+ let mut pal = quantize::build_palette(&px, PaletteKind::Selective, if clear { count.saturating_sub(1).max(2) } else { count }, Forced::BlackWhite)?;
+ let transparent = if clear && pal.len() < 256 {
+ pal.push([255; 3]);
+ Some(pal.len() - 1)
+ } else {
+ None
+ };
+ let palette_ms = elapsed(start);
+ let mut out = px.clone();
+ let start = Instant::now();
+ let indices = quantize::quantize(&mut out, doc.size.width as usize, &pal, Dither::Diffusion, 0.75, transparent);
+ let diffusion_ms = elapsed(start);
+ std::hint::black_box(indices);
+ let start = Instant::now();
+ let proxy = photocraft_compose::proxy::proxy_document(&doc, 1);
+ let mut session = Session::new();
+ session.add_document(proxy, None);
+ session.execute("image.mode.indexedColor", json!({"colors":count}))?;
+ let result = session.active().ok_or("preview has no document")?;
+ let composed = photocraft_compose::flatten(&result.doc);
+ let preview_ms = elapsed(start);
+ println!(
+ "{}",
+ json!({"colors":count,"run":run,"warmup":run==0,"palette_ms":palette_ms,
+ "diffusion_ms":diffusion_ms,"preview_ms":preview_ms,"palette":pal,"pixels_hash":pixel_hash(&out),
+ "preview_hash":pixel_hash(&composed.px)})
+ );
+ }
+ }
+ Ok(())
+}
diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs
index 01f03b505..f9ee2154e 100644
--- a/crates/engine/src/mode_cmds.rs
+++ b/crates/engine/src/mode_cmds.rs
@@ -136,7 +136,13 @@ fn single_layer(doc: &mut Document, active: &mut Option<LayerId>, mode: ColorMod
doc.mode = mode;
doc.depth = SampleType::U8;
let fmt = doc.pixel_format();
- let data: Vec<f32> = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();
+ // Reuse one format-sized pixel buffer instead of allocating a Vec for every pixel.
+ let mut pixel = vec![0.0; fmt.channels()];
+ let mut data = Vec::new();
+ for q in px {
+ photocraft_raster::from_rgba_into(&fmt, *q, &mut pixel);
+ data.extend_from_slice(&pixel);
+ }
let mut l = Layer::raster(name, fmt);
if background {
l.locks.transparency = true;
@@ -185,7 +191,16 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| bad(CMD, "palette: exact|systemMac|systemWindows|web|uniform|perceptual|selective|adaptive"))?;
let forced = parse_forced(str_or(p, "forced", "blackWhite")).ok_or_else(|| bad(CMD, "forced: none|blackWhite|primaries|web"))?;
let dither = parse_dither(str_or(p, "dither", "diffusion")).ok_or_else(|| bad(CMD, "dither: none|diffusion|pattern|noise"))?;
- let colors = num(p, "colors", 256.0).clamp(2.0, 256.0) as usize;
+ let colors = match p.get("colors") {
+ None => 256,
+ Some(value) => {
+ let value = value.as_f64().ok_or_else(|| bad(CMD, "colors must be an integer from 2 to 256"))?;
+ if !value.is_finite() || value.fract() != 0.0 || !(2.0..=256.0).contains(&value) {
+ return Err(bad(CMD, "colors must be an integer from 2 to 256"));
+ }
+ value as usize
+ }
+ };
let amount = num(p, "amount", 75.0).clamp(0.0, 100.0) / 100.0;
let transparency = p.get("transparency").and_then(Value::as_bool).unwrap_or(true);
let (pal_len, transparent) = s.edit("Indexed Color", |doc, active| {
diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs
index ac94c775d..af9eb7989 100644
--- a/crates/engine/src/mode_cmds/tests.rs
+++ b/crates/engine/src/mode_cmds/tests.rs
@@ -81,6 +81,37 @@ fn rotate_arbitrary_other_modes() {
}
}
+#[test]
+fn flattened_mode_pixels_match_the_allocating_conversion_at_every_channel_count() {
+ let px = [[0.0, 0.25, 0.75, 0.0], [0.9, 0.3, 0.2, 0.2], [0.1, 0.7, 0.4, 0.7], [1.0; 4]];
+ for mode in [ColorMode::Indexed, ColorMode::Bitmap, ColorMode::Duotone] {
+ let mut document = Document::with_background("mode", Size::new(2, 2), ColorMode::Rgb, SampleType::F32, photocraft_doc::Color::WHITE);
+ let mut active = None;
+ single_layer(&mut document, &mut active, mode, &px, "result", false);
+ let fmt = document.pixel_format();
+ let mut expected = Surface::new(fmt);
+ let converted: Vec<f32> = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();
+ expected.write_region(document.bounds(), &converted);
+ let actual = document.layers[0].surface().unwrap();
+ assert_eq!(actual.to_interleaved(document.bounds()), expected.to_interleaved(document.bounds()), "{mode:?}");
+ assert_eq!(document.depth, SampleType::U8);
+ assert_eq!(active, Some(document.layers[0].id));
+ }
+}
+
+#[test]
+fn indexed_color_rejects_invalid_counts_without_editing_the_document() {
+ let mut s = session(12, 12, 16, "rgb");
+ let before = s.active().unwrap().history.past_len();
+ for colors in [json!(16.5), json!(0), json!(1), json!(257), json!(512), json!(-2), json!("16"), json!(null), json!(true), json!([]), json!(1e100)] {
+ assert!(s.execute("image.mode.indexedColor", json!({"colors": colors})).is_err(), "{colors}");
+ assert_eq!(s.active().unwrap().history.past_len(), before);
+ assert_eq!((doc(&s).mode, doc(&s).depth), (ColorMode::Rgb, SampleType::U16));
+ }
+ s.execute("image.mode.indexedColor", json!({"colors": 17.0})).unwrap();
+ assert!(doc(&s).color_table.as_ref().unwrap().colors.len() <= 17);
+}
+
#[test]
fn indexed_color_palettes_and_dithers() {
for palette in ["selective", "perceptual", "adaptive", "web", "uniform", "systemMac", "systemWindows"] {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 632df4aba..5e8d93789 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1102,8 +1102,11 @@ fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx:
app.perf.gpu_budget_allowance = allowance;
}
-/// Live preview for an open filter dialog: run the filter on the proxy and upload it.
-fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64, [u32; 2])> {
+/// Live preview for an open filter dialog: run the filter on the proxy and upload it. Heavy
+/// commands compute on one background worker (`filter_preview_worker`); everything else keeps
+/// the deterministic inline path (#1676), which also lets headless/CPU tests inspect previews
+/// without a GPU texture.
+fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> {
// Command dialogs always edit the active document. Never show their preview in another tab.
if app.session.active_index() != Some(idx) {
return None;
@@ -1118,32 +1121,107 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u6
let cmd = d.fields.get("__command")?.as_str()?.to_string();
// Previews edit what the command will: a targeted layer mask included (#780).
let params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields));
- let (doc_id, revision, doc, active) = {
- let st = app.session.documents().get(idx)?;
- (st.doc.id, st.revision, st.doc.clone(), st.active_layer)
+ let st = app.session.documents().get(idx)?;
+ let request = crate::filter_dialog::FilterPreviewKey {
+ doc: st.doc.id,
+ revision: st.revision,
+ dialog: d.id,
+ active: st.active_layer,
+ command: cmd,
+ params,
+ k: crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)),
};
- let k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app));
- let hash = format!("{cmd}{params}").bytes().fold(k as u64 ^ revision.wrapping_mul(0x9e37), |h, b| h.wrapping_mul(31).wrapping_add(b as u64));
- let key = doc_id.0 ^ (1u64 << 61);
- let fresh = matches!(&app.filter_preview, Some(p) if p.doc == doc_id && p.hash == hash);
- if !fresh {
+ let key = request.doc.0 ^ (1u64 << 61);
+ #[cfg(not(target_arch = "wasm32"))]
+ if app.background_jobs && request.command == "image.mode.indexedColor" {
+ if let Some((finished, computed)) = app.filter_preview_worker.poll()
+ && finished == request
+ {
+ match computed {
+ Ok(computed) => publish_filter_preview(app, idx, finished, computed.result, computed.ms),
+ Err(error) => {
+ app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: finished, result: None });
+ crate::notices::error(app, error);
+ }
+ }
+ }
+ let fresh = app.filter_preview.as_ref().is_some_and(|p| p.key == request);
+ if !fresh && !app.filter_preview_worker.busy() {
+ let doc = app.session.documents().get(idx)?.doc.clone();
+ let task = request.clone();
+ if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move || {
+ let t0 = crate::gpu_canvas::now_ms();
+ let result = crate::filter_dialog::preview_document(&doc, task.active, &task.command, &task.params, task.k).map(|doc| {
+ let buffer = photocraft_compose::flatten(&doc);
+ (std::sync::Arc::new(doc), buffer)
+ });
+ crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 }
+ }) {
+ app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None });
+ crate::notices::error(app, error);
+ }
+ }
+ if app.filter_preview_worker.busy() {
+ ctx.request_repaint_after(std::time::Duration::from_millis(16));
+ }
+ let preview = app.filter_preview.as_ref()?;
+ // Keep the last preview during a drag, but never one from another source or dialog.
+ // Completed worker results above must match every parameter before being uploaded.
+ if preview.key.doc != request.doc
+ || preview.key.revision != request.revision
+ || preview.key.dialog != request.dialog
+ || preview.key.active != request.active
+ || preview.key.k != request.k
+ || preview.key.command != request.command
+ {
+ return None;
+ }
+ let result = preview.result.as_ref()?;
+ return Some((preview.key.k, key, [result.size.width, result.size.height]));
+ }
+ // Web and explicitly inline sessions keep the deterministic synchronous path (#1676):
+ // computed inline, uploaded when a GPU texture exists, still inspectable without one.
+ let _ = ctx;
+ if app.filter_preview.as_ref().is_none_or(|p| p.key != request) {
+ let doc = app.session.documents().get(idx)?.doc.clone();
let t0 = crate::gpu_canvas::now_ms();
- let result = crate::filter_dialog::preview_document(&doc, active, &cmd, &params, k).map(std::sync::Arc::new);
+ let result = crate::filter_dialog::preview_document(&doc, request.active, &request.command, &request.params, request.k).map(std::sync::Arc::new);
if let Some(r) = &result {
let buf = photocraft_compose::flatten(r);
let t1 = crate::gpu_canvas::now_ms();
let (display, _) = canvas_display(app, &doc, None);
- // Headless/CPU tests can still inspect the computed preview without a GPU texture.
if let Some(gpu) = app.gpu.as_ref() {
gpu.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth);
}
app.perf.record("filter-preview", r.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1);
}
- app.filter_preview = Some(crate::filter_dialog::FilterPreview { doc: doc_id, revision, hash, k, result });
+ let buffer = result.as_ref().map(|r| photocraft_compose::flatten(r));
+ publish_filter_preview(app, idx, request, result.zip(buffer), crate::gpu_canvas::now_ms() - t0);
}
let preview = app.filter_preview.as_ref()?;
let result = preview.result.as_ref()?;
- Some((preview.k, key, [result.size.width, result.size.height]))
+ Some((preview.key.k, key, [result.size.width, result.size.height]))
+}
+
+fn publish_filter_preview(
+ app: &mut PhotocraftApp,
+ idx: usize,
+ request: crate::filter_dialog::FilterPreviewKey,
+ computed: Option<(std::sync::Arc<photocraft_doc::Document>, photocraft_compose::Buffer)>,
+ ms: f64,
+) {
+ let result = computed.and_then(|(result, buffer)| {
+ let t0 = crate::gpu_canvas::now_ms();
+ let doc = app.session.documents().get(idx)?.doc.clone();
+ let (display, _) = canvas_display(app, &doc, None);
+ // A GPU texture is an optimisation: headless/CPU tests must still see the preview.
+ if let Some(gpu) = app.gpu.as_ref() {
+ gpu.upload_buffer_full(request.doc.0 ^ (1u64 << 61), &texture_buffer(display.as_deref(), &buffer), doc.depth);
+ }
+ app.perf.record("filter-preview", result.size.area(), ms, crate::gpu_canvas::now_ms() - t0);
+ Some(result)
+ });
+ app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request, result });
}
/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners
@@ -1247,7 +1325,7 @@ pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) {
// Upload markers must not outlive the resources they describe: native reopen can reuse
// both the document ID and revision before the next frame while a preview dialog stays open.
let documents = app.session.documents();
- if app.filter_preview.as_ref().is_some_and(|preview| !documents.iter().any(|st| st.doc.id == preview.doc)) {
+ if app.filter_preview.as_ref().is_some_and(|preview| !documents.iter().any(|st| st.doc.id == preview.key.doc)) {
app.filter_preview = None;
}
if app.proxy_uploaded.is_some_and(|(doc, _)| !documents.iter().any(|st| st.doc.id == doc)) {
@@ -1980,7 +2058,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if app.gpu.is_some()
&& gpu_ok
&& let Some((k, key, preview_size)) = ensure_adjust_proxy(app, idx, view.zoom * ctx.pixels_per_point())
- .or_else(|| ensure_filter_preview(app, idx))
+ .or_else(|| ensure_filter_preview(app, idx, &ctx))
.or_else(|| ensure_proxy_preview(app, idx))
{
on_gpu = true;
@@ -3796,6 +3874,56 @@ mod tabs_tests;
#[cfg(test)]
mod tests {
+ #[cfg(not(target_arch = "wasm32"))]
+ #[test]
+ fn indexed_preview_discards_a_finished_job_after_slider_change_or_reopening() {
+ for reopen in [false, true] {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ app.background_jobs = true;
+ crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap();
+ let d = app.ui.dialogs.first().unwrap();
+ let st = app.session.active().unwrap();
+ let old = crate::filter_dialog::FilterPreviewKey {
+ doc: st.doc.id,
+ revision: st.revision,
+ dialog: d.id,
+ active: st.active_layer,
+ command: "image.mode.indexedColor".into(),
+ params: app.with_mask_target("image.mode.indexedColor", crate::filter_dialog::params_of(&d.fields)),
+ k: 1,
+ };
+ let (release, wait) = std::sync::mpsc::channel();
+ let ctx = egui::Context::default();
+ app.filter_preview_worker
+ .start(old.clone(), ctx.clone(), move || {
+ wait.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
+ crate::filter_preview_worker::Computed { result: None, ms: 0.0 }
+ })
+ .unwrap();
+ if reopen {
+ app.ui.dialogs.clear();
+ crate::filter_preview_worker::discard_closed(&mut app);
+ crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap();
+ } else {
+ app.ui.dialogs.first_mut().unwrap().fields.insert("colors".into(), json!(16));
+ }
+ assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none());
+ assert!(app.filter_preview.is_none());
+ release.send(()).unwrap();
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ while app.filter_preview.is_none() {
+ assert!(std::time::Instant::now() < deadline);
+ ensure_filter_preview(&mut app, 0, &ctx);
+ if let Some(preview) = &app.filter_preview {
+ assert_ne!(preview.key, old, "an outdated preview was published");
+ }
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ assert_eq!(app.session.active().unwrap().doc.mode, photocraft_color::ColorMode::Rgb);
+ }
+ }
+
#[test]
fn windows_uses_a_visible_crosshair() {
// #737: Windows' inverting crosshair vanishes over mid-grey; use a black/white glyph.
@@ -4607,14 +4735,14 @@ mod rotation_preview_isolation_tests {
dialog.fields.insert("angle".into(), json!(90.0));
dialog.fields.insert("direction".into(), json!("cw"));
- let (factor, _, size) = ensure_filter_preview(&mut app, 0).expect("CPU preview computed");
+ let (factor, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("CPU preview computed");
assert_eq!(factor, 1);
assert_eq!(size, [48, 96]);
let original = &app.session.active().unwrap().doc;
assert_eq!([original.size.width, original.size.height], [96, 48]);
app.ui.dialogs.last_mut().unwrap().fields.insert("__preview".into(), json!(false));
- assert!(ensure_filter_preview(&mut app, 0).is_none(), "disabling Preview must hide the preview");
+ assert!(ensure_filter_preview(&mut app, 0, &egui::Context::default()).is_none(), "disabling Preview must hide the preview");
assert_eq!([app.session.active().unwrap().doc.size.width, app.session.active().unwrap().doc.size.height], [96, 48]);
}
@@ -4627,10 +4755,10 @@ mod rotation_preview_isolation_tests {
let mut app = PhotocraftApp::new(session, crate::Services::default());
crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap();
app.ui.dialogs.last_mut().unwrap().fields.insert("angle".into(), json!(90.0));
- assert!(ensure_filter_preview(&mut app, 0).is_some());
+ assert!(ensure_filter_preview(&mut app, 0, &egui::Context::default()).is_some());
app.session.execute("file.new", json!({"width": 40, "height": 20})).unwrap();
assert_eq!(app.session.active_index(), Some(1));
- assert!(ensure_filter_preview(&mut app, 0).is_none(), "an inactive tab must never inherit the command preview");
+ assert!(ensure_filter_preview(&mut app, 0, &egui::Context::default()).is_none(), "an inactive tab must never inherit the command preview");
}
}
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index 3e502fc75..27192e564 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -184,6 +184,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
}
for p in parse_spec(spec.params) {
let v = match &p.kind {
+ Kind::Range { default, .. } if command == "image.mode.indexedColor" && p.key == "colors" => json!(default.round().clamp(2.0, 256.0) as u32),
Kind::Range { default, .. } => json!(default),
Kind::Choice(c) => json!(c.first().cloned().unwrap_or_default()),
Kind::Bool(default) => json!(default),
@@ -292,6 +293,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
match p.kind {
Kind::Range { min, max, default } => {
let mut v = f.get(&p.key).and_then(Value::as_f64).unwrap_or(default as f64) as f32;
+ if cmd == "image.mode.indexedColor" && p.key == "colors" {
+ let mut count = v.round().clamp(2.0, 256.0) as u32;
+ crate::widgets::color_count_row(ui, &label(&p.key), &mut count);
+ f.insert(p.key, json!(count));
+ continue;
+ }
let unit = if is_pixel_param(&p.key) {
"px"
} else if p.key == "angle" {
@@ -456,11 +463,20 @@ pub fn preview_document(doc: &Document, active: Option<photocraft_doc::LayerId>,
/// Cached preview state on the app.
pub struct FilterPreview {
+ pub key: FilterPreviewKey,
+ pub result: Option<Arc<Document>>,
+}
+
+/// Match the full request before accepting a worker result, including a reopened dialog.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FilterPreviewKey {
pub doc: photocraft_doc::DocId,
pub revision: u64,
- pub hash: u64,
+ pub dialog: u64,
+ pub active: Option<photocraft_doc::LayerId>,
+ pub command: String,
+ pub params: Value,
pub k: u32,
- pub result: Option<Arc<Document>>,
}
#[cfg(test)]
@@ -494,6 +510,25 @@ mod tests {
assert!(!params_of(&f).as_object().unwrap().contains_key("reference"), "{f:?}");
}
+ #[test]
+ fn indexed_counts_are_integer_json_while_dither_amounts_keep_their_decimals() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ open(&mut app, "image.mode.indexedColor").unwrap();
+ let mut defaults = app.ui.dialogs.first().unwrap().fields.clone();
+ let before = params_of(&defaults)["colors"].clone();
+ egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut defaults)).textures_delta.clear();
+ assert_eq!(before.as_u64(), Some(256));
+ assert_eq!(params_of(&defaults)["colors"], before, "opening a preview must not schedule a second job just to normalize its count");
+ let mut fields = Map::new();
+ fields.insert("__command".into(), json!("image.mode.indexedColor"));
+ fields.insert("colors".into(), json!(17));
+ fields.insert("amount".into(), json!(37.5));
+ egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut fields)).textures_delta.clear();
+ let params = params_of(&fields);
+ assert_eq!(params["colors"].as_u64(), Some(17));
+ assert_eq!(params["amount"].as_f64(), Some(37.5));
+ }
+
#[test]
fn wide_positive_ranges_use_the_logarithmic_slider_path() {
assert!(uses_logarithmic_slider(0.1, 1000.0), "Gaussian Blur radius");
diff --git a/crates/ui-egui/src/filter_preview_worker.rs b/crates/ui-egui/src/filter_preview_worker.rs
new file mode 100644
index 000000000..aec8439f4
--- /dev/null
+++ b/crates/ui-egui/src/filter_preview_worker.rs
@@ -0,0 +1,143 @@
+//! One native preview at a time. The canvas submits the current request again after an old
+//! job finishes, so slider drags cannot queue copies of every intermediate document.
+
+use std::sync::mpsc::{Receiver, TryRecvError};
+
+use crate::filter_dialog::FilterPreviewKey;
+
+pub(crate) struct Computed {
+ pub result: Option<(std::sync::Arc<photocraft_doc::Document>, photocraft_compose::Buffer)>,
+ pub ms: f64,
+}
+
+#[derive(Default)]
+pub(crate) struct Worker {
+ running: Option<(FilterPreviewKey, Receiver<Result<Computed, String>>)>,
+}
+
+impl Worker {
+ pub fn busy(&self) -> bool {
+ self.running.is_some()
+ }
+
+ /// Never wait for a previous computation and never spawn a second concurrent preview.
+ pub fn start(&mut self, key: FilterPreviewKey, ctx: egui::Context, compute: impl FnOnce() -> Computed + Send + 'static) -> Result<bool, String> {
+ if self.busy() {
+ return Ok(false);
+ }
+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
+ std::thread::Builder::new()
+ .name("indexed-color-preview".into())
+ .spawn(move || {
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compute)).map_err(|_| "Filter preview failed".to_string());
+ let _ = tx.send(result);
+ ctx.request_repaint();
+ })
+ .map_err(|e| format!("Could not start filter preview: {e}"))?;
+ self.running = Some((key, rx));
+ Ok(true)
+ }
+
+ pub fn poll(&mut self) -> Option<(FilterPreviewKey, Result<Computed, String>)> {
+ let (_, rx) = self.running.as_ref()?;
+ let result = match rx.try_recv() {
+ Ok(result) => result,
+ Err(TryRecvError::Empty) => return None,
+ Err(TryRecvError::Disconnected) => Err("Filter preview worker disconnected".to_string()),
+ };
+ let (key, _) = self.running.take()?;
+ Some((key, result))
+ }
+}
+
+/// Release results from closed dialogs even when their canvas is no longer being drawn.
+pub(crate) fn discard_closed(app: &mut crate::PhotocraftApp) {
+ let visible = app.ui.dialogs.iter().any(|d| {
+ d.fields.get("__command").and_then(serde_json::Value::as_str) == Some("image.mode.indexedColor")
+ && d.fields.get("__preview").and_then(serde_json::Value::as_bool) == Some(true)
+ });
+ if !visible {
+ let _ = app.filter_preview_worker.poll();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn key(dialog: u64, revision: u64, colors: u32) -> FilterPreviewKey {
+ FilterPreviewKey {
+ doc: photocraft_doc::DocId(1),
+ revision,
+ dialog,
+ active: None,
+ command: "image.mode.indexedColor".into(),
+ params: json!({"colors": colors}),
+ k: 1,
+ }
+ }
+
+ fn finish(worker: &mut Worker) -> (FilterPreviewKey, Result<Computed, String>) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
+ loop {
+ if let Some(result) = worker.poll() {
+ return result;
+ }
+ assert!(std::time::Instant::now() < deadline, "preview worker did not finish");
+ std::thread::sleep(std::time::Duration::from_millis(1));
+ }
+ }
+
+ #[test]
+ fn blocked_preview_does_not_block_ui_or_queue_slider_requests() {
+ let mut worker = Worker::default();
+ let ctx = egui::Context::default();
+ let (release, wait) = std::sync::mpsc::channel();
+ assert!(
+ worker
+ .start(key(1, 0, 8), ctx.clone(), move || {
+ wait.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
+ Computed { result: None, ms: 0.0 }
+ })
+ .unwrap()
+ );
+ for colors in [16, 32, 64, 128, 256] {
+ ctx.run_ui(Default::default(), |ui| {
+ ui.label("The UI still draws");
+ })
+ .textures_delta
+ .clear();
+ assert!(worker.poll().is_none());
+ assert!(!worker.start(key(1, 0, colors), ctx.clone(), || panic!("queued an intermediate request")).unwrap());
+ }
+ release.send(()).unwrap();
+ let (old, result) = finish(&mut worker);
+ assert!(result.is_ok());
+ let latest = key(1, 0, 256);
+ assert_ne!(old, latest); // The canvas must discard this result before uploading.
+ assert!(worker.start(latest.clone(), ctx, || Computed { result: None, ms: 1.0 }).unwrap());
+ assert_eq!(finish(&mut worker).0, latest);
+ }
+
+ #[test]
+ fn request_identity_covers_dialog_revision_layer_and_params() {
+ let original = key(1, 2, 64);
+ assert_ne!(original, key(2, 2, 64));
+ assert_ne!(original, key(1, 3, 64));
+ assert_ne!(original, key(1, 2, 128));
+ let mut layer = original.clone();
+ layer.active = Some(photocraft_doc::LayerId(4));
+ assert_ne!(original, layer);
+ }
+
+ #[test]
+ fn escaped_panic_is_an_error_and_worker_can_be_reused() {
+ let mut worker = Worker::default();
+ worker.start(key(1, 0, 64), Default::default(), || panic!("synthetic preview failure")).unwrap();
+ assert!(finish(&mut worker).1.is_err());
+ assert!(!worker.busy());
+ worker.start(key(1, 0, 128), Default::default(), || Computed { result: None, ms: 0.0 }).unwrap();
+ assert!(finish(&mut worker).1.is_ok());
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 7d4f994ac..bb012b41c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -60,6 +60,8 @@ pub mod file_open;
pub mod file_ui;
pub mod fill_ui;
pub mod filter_dialog;
+#[cfg(not(target_arch = "wasm32"))]
+mod filter_preview_worker;
pub mod gallery_ui;
pub mod gpu_canvas;
pub mod gpu_status;
@@ -403,6 +405,8 @@ pub struct PhotocraftApp {
/// Selection outline cache: (doc, revision, segments).
/// Live filter preview (proxy document with the filter applied).
pub(crate) filter_preview: Option<filter_dialog::FilterPreview>,
+ #[cfg(not(target_arch = "wasm32"))]
+ filter_preview_worker: filter_preview_worker::Worker,
/// Select › Color Range dialog preview (proxy document + mask / image textures).
pub(crate) color_range: Option<color_range_ui::Preview>,
/// Image › Adjustments dialog preview through a temporary clipped adjustment layer.
@@ -543,6 +547,8 @@ impl PhotocraftApp {
proxy_uploaded: None,
outline_cache: None,
filter_preview: None,
+ #[cfg(not(target_arch = "wasm32"))]
+ filter_preview_worker: Default::default(),
color_range: None,
adjust_preview: None,
synthetic: Vec::new(),
@@ -1086,6 +1092,8 @@ impl eframe::App for PhotocraftApp {
// shortcuts see Esc).
if !screen_picker::tick(self, ctx) {
jobs_ui::tick(self, ctx);
+ #[cfg(not(target_arch = "wasm32"))]
+ filter_preview_worker::discard_closed(self);
shortcuts::handle(self, ctx);
}
let arrived: Vec<(String, Vec<u8>)> =
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 6d654adeb..568a5bf99 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -5,6 +5,9 @@ use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Response, Sense, Stroke, S
use crate::theme::{self, Tokens};
+mod color_count;
+pub use color_count::color_count_row;
+
/// An accent insertion line on one edge of `r` while a drag hovers it (vertical: on its left or,
/// `after`, right edge; else on its top or bottom).
pub fn drop_line(ui: &Ui, r: Rect, after: bool, vertical: bool, t: &Tokens) {
diff --git a/crates/ui-egui/src/widgets/color_count.rs b/crates/ui-egui/src/widgets/color_count.rs
new file mode 100644
index 000000000..f75f89a44
--- /dev/null
+++ b/crates/ui-egui/src/widgets/color_count.rs
@@ -0,0 +1,152 @@
+//! Integer-only Indexed Color field and a linear slider with common palette sizes.
+
+use super::*;
+
+const STOPS: [u32; 6] = [8, 16, 32, 64, 128, 256];
+
+fn parse_count(text: &str) -> Option<f64> {
+ text.trim().parse::<u32>().ok().map(f64::from)
+}
+
+fn position(track: Rect, count: u32) -> f32 {
+ track.left() + count.saturating_sub(2) as f32 / 254.0 * track.width()
+}
+
+fn at_pointer(track: Rect, x: f32) -> u32 {
+ // Use the nearest marker: low counts are close together on the linear track.
+ if let Some(stop) = STOPS.iter().copied().min_by(|&a, &b| (position(track, a) - x).abs().total_cmp(&(position(track, b) - x).abs()))
+ && (position(track, stop) - x).abs() <= 6.0
+ {
+ return stop;
+ }
+ let fraction = ((x - track.left()) / track.width().max(1.0)).clamp(0.0, 1.0);
+ (2.0 + fraction * 254.0).round() as u32
+}
+
+/// A count in 2..=256. Direct entry allows every integer; only slider gestures snap to markers.
+pub fn color_count_row(ui: &mut Ui, label: &str, count: &mut u32) -> Response {
+ let t = Tokens::get(ui.ctx());
+ *count = (*count).clamp(2, 256);
+ let before = *count;
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(tl!(label)).color(t.text_dim));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let (rect, _) = ui.allocate_exact_size(vec2(74.0, 24.0), Sense::hover());
+ surface(ui, rect, t.field, false);
+ if !t.bevel {
+ ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
+ }
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(4.0, 2.0))));
+ child.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT;
+ child.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT;
+ child.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE;
+ child.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE;
+ child.style_mut().override_font_id = Some(theme::mono(12.0));
+ child.add(egui::DragValue::new(count).range(2..=256).speed(1.0).max_decimals(0).custom_parser(parse_count));
+ });
+ });
+ let (rect, mut response) = ui.allocate_exact_size(vec2(ui.available_width().max(60.0), 36.0), Sense::click_and_drag());
+ let track = Rect::from_min_max(pos2(rect.left() + 7.0, rect.top() + 7.5), pos2(rect.right() - 7.0, rect.top() + 10.5));
+ if (response.clicked() || response.dragged())
+ && let Some(pointer) = response.interact_pointer_pos()
+ {
+ *count = at_pointer(track, pointer.x).clamp(2, 256);
+ response.request_focus();
+ }
+ if response.has_focus() {
+ ui.input_mut(|input| {
+ for key in [egui::Key::ArrowLeft, egui::Key::ArrowDown] {
+ if input.consume_key(egui::Modifiers::NONE, key) {
+ *count = count.saturating_sub(1).max(2);
+ }
+ }
+ for key in [egui::Key::ArrowRight, egui::Key::ArrowUp] {
+ if input.consume_key(egui::Modifiers::NONE, key) {
+ *count = count.saturating_add(1).min(256);
+ }
+ }
+ });
+ }
+ response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*count), label));
+ let x = position(track, *count);
+ let painter = ui.painter();
+ painter.rect_filled(track, t.radius_sm, t.field_border);
+ painter.rect_filled(Rect::from_min_max(track.min, pos2(x, track.bottom())), t.radius_sm, t.accent);
+ for stop in STOPS {
+ let sx = position(track, stop);
+ painter.line_segment([pos2(sx, track.bottom() + 3.0), pos2(sx, track.bottom() + 6.0)], Stroke::new(1.0, t.text_faint));
+ painter.text(
+ pos2(sx, track.bottom() + 9.0),
+ if stop == 256 { Align2::RIGHT_TOP } else { Align2::CENTER_TOP },
+ stop.to_string(),
+ theme::mono(10.0),
+ t.text_faint,
+ );
+ }
+ let knob = pos2(x, track.center().y);
+ if t.bevel {
+ surface(ui, Rect::from_center_size(knob, vec2(10.0, 16.0)), t.card, true);
+ } else {
+ painter.circle_filled(knob, 6.0, t.text);
+ if response.hovered() || response.dragged() {
+ painter.circle_stroke(knob, 8.0, Stroke::new(2.0, t.accent_soft));
+ }
+ }
+ if *count != before {
+ response.mark_changed();
+ }
+ ui.add_space(4.0);
+ response
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use egui_kittest::{Harness, kittest::Queryable};
+
+ #[test]
+ fn typed_color_counts_reject_fractions_and_allow_arbitrary_integers() {
+ for (text, expected) in [("17", 17), ("256", 256), ("17.5", 64), ("17,5", 64), ("1e2", 64)] {
+ let mut harness = Harness::builder().with_size(vec2(320.0, 100.0)).build_ui_state(
+ |ui, count: &mut u32| {
+ color_count_row(ui, "Colors", count);
+ },
+ 64,
+ );
+ harness.get_by_role(egui::accesskit::Role::SpinButton).click();
+ harness.run();
+ harness.event(egui::Event::Text(text.into()));
+ harness.key_press(egui::Key::Enter);
+ harness.run();
+ assert_eq!(*harness.state(), expected, "{text}");
+ }
+ }
+
+ #[test]
+ fn slider_clicks_snap_to_every_marker_but_allow_intermediate_counts() {
+ for count in STOPS {
+ let mut harness = Harness::builder().with_size(vec2(320.0, 100.0)).build_ui_state(
+ |ui, count: &mut u32| {
+ color_count_row(ui, "Colors", count);
+ },
+ 2,
+ );
+ let rect = harness.get_by_role(egui::accesskit::Role::Slider).rect();
+ let track = rect.shrink2(vec2(7.0, 0.0));
+ let point = pos2(position(track, count) - 4.0, rect.top() + 9.0);
+ harness.event(egui::Event::PointerMoved(point));
+ for pressed in [true, false] {
+ harness.event(egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
+ harness.run();
+ }
+ assert_eq!(*harness.state(), count);
+ harness.key_press(egui::Key::ArrowRight);
+ harness.run();
+ assert_eq!(*harness.state(), (count + 1).min(256));
+ }
+ let track = Rect::from_min_size(Pos2::ZERO, vec2(300.0, 3.0));
+ assert_eq!(at_pointer(track, position(track, 23)), 23);
+ assert_eq!(position(track, 129), track.center().x);
+ assert!(((position(track, 128) - position(track, 64)) - (position(track, 96) - position(track, 32))).abs() < 0.001);
+ }
+}
diff --git a/docs/development.md b/docs/development.md
index 3e163bc1d..2ac1d725c 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -352,6 +352,28 @@ How the web shell (`apps/photocraft-web/src/web.rs`) differs from desktop:
- Headless Chrome on macOS (`--headless=new --enable-unsafe-webgpu`) gets a real WebGPU adapter.
+## Indexed Color timings
+
+`cargo run --release -p photocraft-engine --example indexed_color_perf -- image.png` measures
+palette construction, Floyd–Steinberg diffusion, and the complete full-resolution CPU preview
+path (proxy copy, engine command, result composition; excludes GPU upload/presentation).
+It prints JSON lines for 8, 16, 32, 64, 128 and 256 colours, with one warmup and three measured
+runs per count, plus palette and pixel hashes for exact before/after comparisons. Input files
+stay local; do not publish personal images, palettes, or metadata with benchmark reports.
+
+The synthetic 24 MP lookup comparison is reproducible with
+`cargo test --release -p photocraft-algo indexed_diffusion_24mp_release_comparison -- --ignored --nocapture`.
+It alternates linear/accelerated lookup order and checks identical indices and pixels.
+For the 2026-10-09 local timings both binaries used `CARGO_PROFILE_RELEASE_LTO=false` and
+`CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16`; compare binaries built with the same settings.
+
+On native desktop sessions, Indexed Color live previews calculate and flatten on one worker.
+The last preview remains visible while dragging; intermediate settings are coalesced, and only
+a result matching the current document revision, active layer, dialog and parameters is uploaded.
+GPU upload/display conversion still run on the UI thread. Web and `PHOTOCRAFT_INLINE_JOBS=1`
+sessions retain synchronous previews. Closing the dialog invalidates its result; an already
+running calculation finishes without editing the session.
+
## Offscreen UI snapshots (no window)
Render the full UI headlessly with the real wgpu canvas, e.g. for design reviews or when the app
diff --git a/docs/roadmap.md b/docs/roadmap.md
index cf4300b63..8cae1974d 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -85,7 +85,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either
| Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. |
| Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. |
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
-| Performance | 14k+ px on the GPU at ~⅓ the memory; adjustment preview 285 ms → 4–9 ms; font-size edits 297 ms → 4.6 ms; 2026-10-07: 30 MP TIFF open (banded, parallel strip/tile decode) Deflate 345 → 32 ms, LZW 428 → 43 ms, BigTIFF and every IFD readable | medium-high on rasters | Complex layout documents still laggy (#125/#128); >16384 px GPU tiling in progress (#49). |
+| Performance | 14k+ px on the GPU at ~⅓ the memory; adjustment preview 285 ms → 4–9 ms; font-size edits 297 ms → 4.6 ms; 2026-10-07: 30 MP TIFF open (banded, parallel strip/tile decode) Deflate 345 → 32 ms, LZW 428 → 43 ms, BigTIFF and every IFD readable; 2026-10-09: 4.2 MP Indexed Color, 256 colours, full-resolution CPU preview p50 3018 → 1061 ms (Ryzen AI 7 350, three measured runs; GPU upload excluded) | medium-high on rasters | Complex layout documents still laggy (#125/#128); >16384 px GPU tiling in progress (#49). Native Indexed Color previews run on one background worker with stale-result rejection; large palettes can still take about a second to compute. Web previews remain synchronous. |
| Stability | Never-crash lint series, crash guard, `panic_hunt` fuzzing in the gate | medium-high | No field crash data yet. |
| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF | medium | CR3, RAF, Nikon "lossy after split" and calibrated colour for non-DNG cameras still open (#50). |
| AI / generative | none | ~0% | Deferred by decision (#41). |