Color Table: keep each pixel's index where it is known

Indexed Color documents store RGB pixels, so Color Table found each
pixel's index again as the nearest entry, and entries of one colour
lost their own pixels (#14342). The document now keeps each pixel's
index (Document::color_indices) where it is known: recorded when a
palette PNG is opened, by Image > Mode > Indexed Color and by Color
Table itself. Color Table uses it while the layer still has exactly the
recorded tiles; after any other change it maps by nearest colour as
before. A known index past a shrunk table stays black until the table
grows back over it.

The native format saves the indices only while they hold for the layer
as saved, and pairs them with the loaded layer on open.
This commit is contained in:
Sven Lafebre committed 2026-11-15 10:50:12 +01:00
1 parent cb7f9770f5
commit e2cb5a0cf5
13 files changed
+410 -18

No files matched your search

Generated
+2
View File
@@ -5599,6 +5599,7 @@ dependencies = [
"photocraft-testkit",
"photocraft-text",
"photocraft-vector",
"png 0.18.1",
"rayon",
"same-file",
"semver",
@@ -5703,6 +5704,7 @@ dependencies = [
"photocraft-testkit",
"photocraft-text",
"photocraft-vector",
"png 0.18.1",
"proptest",
"serde_json",
"thiserror 2.0.21",
+12 -3
View File
@@ -38,7 +38,7 @@ pub use effects::{
GradientStyle, Satin, Shadow, StrokeFx, StrokePosition,
};
pub use frame::Frame;
pub use mode::{ColorTable, Duotone, DuotoneInk, StackMode};
pub use mode::{ColorIndices, ColorTable, Duotone, DuotoneInk, StackMode};
pub use pattern::Pattern;
pub use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
pub use photocraft_geom::{Affine, Rect, Size};
@@ -930,6 +930,10 @@ pub struct Document {
pub patterns: Vec<Pattern>,
/// Indexed Color palette (Image › Mode › Color Table). Set while `mode` is Indexed.
pub color_table: Option<ColorTable>,
/// Each pixel's Color Table index where it is known (recorded by opening a palette PNG, the
/// Indexed Color conversion and Color Table), so entries of one colour keep their own pixels
/// (#14342).
pub color_indices: Option<ColorIndices>,
/// Duotone inks. Set while `mode` is Duotone.
pub duotone: Option<Duotone>,
/// Window › Layer Comps, top to bottom as listed in the panel.
@@ -1018,6 +1022,7 @@ impl Document {
quick_mask_unselected: false,
patterns: Vec::new(),
color_table: None,
color_indices: None,
duotone: None,
layer_comps: Vec::new(),
last_applied_comp: None,
@@ -1088,8 +1093,8 @@ impl Document {
}
/// Every pixel surface the document holds: layer pixels and caches, masks, smart filter
/// masks, video frames (including the originals), channels, the quick mask, patterns and
/// the selection. History snapshots and saves cover exactly these tiles.
/// masks, video frames (including the originals), channels, the quick mask, the Color Table
/// indices, patterns and the selection. History snapshots and saves cover exactly these tiles.
pub fn for_each_surface(&self, mut visit: impl FnMut(&Surface)) {
for (_, _, layer) in self.walk() {
if let Some(surface) = layer.surface() {
@@ -1115,6 +1120,10 @@ impl Document {
for channel in self.channels.iter().chain(&self.quick_mask) {
visit(&channel.surface);
}
if let Some(c) = &self.color_indices {
visit(&c.pixels);
visit(&c.indices);
}
for pattern in &self.patterns {
visit(&pattern.surface);
}
+55 -1
View File
@@ -1,10 +1,16 @@
//! Colour-mode side data: the Indexed Color table, Duotone inks, and smart-object stack modes.
//! Colour-mode side data: the Indexed Color table and pixel indices, Duotone inks, and smart-object stack modes.
//!
//! Indexed, Bitmap and Duotone documents keep their pixels expanded (RGB / Gray, see
//! [`crate::Document::pixel_format`]); these structs carry what the mode adds on top.
use std::sync::Arc;
use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use serde::{Deserialize, Serialize};
use crate::LayerId;
use crate::adjust::CurvePoint;
/// Image › Mode › Color Table: the palette of an Indexed Color document (at most 256 entries).
@@ -36,6 +42,54 @@ impl ColorTable {
}
}
/// The Color Table index of each pixel of an Indexed Color layer, where it is known (#14342).
/// The layer's pixels are RGB, so two entries of one colour can't be told apart by colour.
///
/// The indices hold while the layer still has the very tiles recorded with them, at the same
/// places. One tile can't prove where its pixels came from: a move shares tiles, and a solid tile
/// can stand in for another solid tile of the same colour. A move or a paint stroke changes the
/// tiles at the layer's edges or under the stroke, though, so after any change but Color Table's
/// the indices are unknown and Color Table falls back to the nearest entry. Recording costs no
/// pixel copy while the layer is unchanged. A save keeps the indices only while they hold, and an
/// open pairs them with the layer it loads: identical tiles load as one, so loaded pixels can't
/// prove they are unchanged.
#[derive(Clone, Debug, PartialEq)]
pub struct ColorIndices {
/// The layer the indices are for.
pub layer: LayerId,
/// The layer's pixels when the indices were recorded.
pub pixels: Surface,
/// One gray 8-bit sample per pixel: its index.
pub indices: Surface,
}
impl ColorIndices {
/// Records `indices`, one byte per pixel row by row over `r`, for `layer`, whose pixels are
/// `pixels`. `None` when they don't cover `r` or there's no memory for them.
pub fn new(layer: LayerId, pixels: &Surface, r: Rect, indices: &[u8]) -> Option<Self> {
let mut map = Surface::new(PixelFormat::GRAY8);
map.try_write_interleaved(r, indices).ok()?;
Some(ColorIndices { layer, pixels: pixels.clone(), indices: map })
}
/// Whether the indices hold for `layer`, whose pixels are now `pixels`: it is the recorded
/// layer and has the very tiles recorded, at the same places. A damaged file can name another
/// format for the indices: they don't hold then, rather than give wrong ones.
pub fn holds(&self, layer: LayerId, pixels: &Surface) -> bool {
layer == self.layer
&& self.indices.format() == PixelFormat::GRAY8
&& pixels.format() == self.pixels.format()
&& pixels.tile_count() == self.pixels.tile_count()
&& pixels.tiles().zip(self.pixels.tiles()).all(|((a, x), (b, y))| a == b && Arc::ptr_eq(x, y))
}
/// The recorded indices over `r`, one byte per pixel row by row, while they
/// [hold](Self::holds).
pub fn known(&self, layer: LayerId, pixels: &Surface, r: Rect) -> Option<Vec<u8>> {
self.holds(layer, pixels).then(|| self.indices.to_interleaved(r))
}
}
/// One Duotone ink: its display colour and the curve mapping gray density to ink density.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DuotoneInk {
+4
View File
@@ -72,3 +72,7 @@ exr = { version = "1.73", default-features = false }
# WebAssembly text -> binary for plug-in test modules (Apache-2.0 WITH LLVM-exception).
wat = "1.228"
# Synthetic multi-part EXR fixtures for the parts-commands tests.
# Palette PNGs at 1, 2 and 4 bits and with an eXIf chunk for the Color Table index tests
# (the png 0.18 already in the tree).
png = "0.18"
@@ -241,6 +241,8 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
// Compared by `patterns_pixels_equal`.
patterns: _,
color_table,
// Not composited: Color Table reads it, and recolours the layer pixels it changes.
color_indices: _,
duotone,
layer_comps: _,
last_applied_comp: _,
@@ -389,6 +391,8 @@ pub fn selection_only_change(a: &Document, b: &Document) -> bool {
quick_mask_unselected,
patterns: _,
color_table: _,
// Changes only with the layer pixels or the colour table, compared there.
color_indices: _,
duotone: _,
layer_comps,
last_applied_comp,
+27 -5
View File
@@ -12,7 +12,7 @@ use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShap
use photocraft_algo::transform::{Homography, Interp};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size};
use photocraft_doc::{ColorIndices, ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size};
use photocraft_geom::{Affine, Rect};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -244,6 +244,7 @@ fn single_layer_surface(doc: &mut Document, active: &mut Option<LayerId>, mode:
}
doc.quick_mask = None;
doc.color_table = None;
doc.color_indices = None;
doc.duotone = None;
}
@@ -363,9 +364,12 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
None
};
let w = doc.size.width as usize;
quantize::quantize(&mut px, w, &pal, dither, amount, transparent);
let indices = quantize::quantize(&mut px, w, &pal, dither, amount, transparent);
single_layer(doc, active, ColorMode::Indexed, &px, if transparent.is_some() { "Index" } else { "Background" }, transparent.is_none());
doc.color_table = Some(ColorTable { colors: pal.clone(), transparent: transparent.map(|t| t as u8) });
// Each pixel's index is known here: keep it for Color Table (#14342).
let bounds = doc.bounds();
doc.color_indices = doc.layers.first().and_then(|l| ColorIndices::new(l.id, l.surface()?, bounds, &indices));
Ok((pal.len(), transparent))
})?;
Ok(json!({"colors": pal_len, "transparentIndex": transparent}))
@@ -461,7 +465,15 @@ fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
let out = report(&table);
s.edit("Color Table", |doc, _| {
let old = cur.clone();
for surf in doc.layers.iter_mut().filter_map(Layer::surface_mut) {
// A pixel keeps its index where it is known, so entries of one colour keep their own
// pixels; elsewhere it takes the nearest entry (#14342). The indices written here are
// known afterwards, for the recorded layer (Indexed documents have one).
let known = doc.color_indices.take();
let has_pixels = |id: LayerId| doc.layers.iter().any(|l| l.id == id && l.surface().is_some());
let record = known.as_ref().map(|k| k.layer).filter(|&id| has_pixels(id)).or_else(|| doc.layers.iter().find(|l| l.surface().is_some()).map(|l| l.id));
for l in doc.layers.iter_mut() {
let id = l.id;
let Some(surf) = l.surface_mut() else { continue };
let r = surf.content_bounds();
if r.is_empty() {
continue;
@@ -469,7 +481,9 @@ fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
let fmt = surf.format();
let n = fmt.channels();
let mut data = surf.read_region(r);
for q in data.chunks_exact_mut(n) {
let indices = known.as_ref().and_then(|k| k.known(id, surf, r)).unwrap_or_default();
let mut written = vec![0u8; if record == Some(id) { data.len() / n } else { 0 }];
for (k, q) in data.chunks_exact_mut(n).enumerate() {
let c = photocraft_raster::to_rgba(&fmt, q);
let rgb = [c[0], c[1], c[2]];
let i = if c[3] <= 0.0 {
@@ -479,8 +493,13 @@ fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
}
i
} else {
old.nearest(rgb)
// A known index past the table stays: its pixel shows black until the table
// grows back over it.
indices.get(k).map_or_else(|| old.nearest(rgb), |&i| usize::from(i))
};
if let Some(w) = written.get_mut(k) {
*w = i as u8;
}
let alpha = if table.transparent == Some(i as u8) {
0.0
} else if c[3] <= 0.0 {
@@ -496,6 +515,9 @@ fn color_table(s: &mut Session, p: &Value) -> Result<Value> {
}
surf.write_region(r, &data);
surf.prune();
if record == Some(id) {
doc.color_indices = ColorIndices::new(id, surf, r, &written);
}
}
doc.color_table = Some(table.clone());
Ok(())
@@ -1,5 +1,5 @@
//! Image › Mode › Color Table: pixels past a shrunk table turn black, and a table without
//! duplicates recolours as before (#14342).
//! Image › Mode › Color Table recolours each pixel by its index where it is known, so entries of
//! one colour keep their own pixels; pixels past a shrunk table turn black (#14342).
use super::*;
@@ -71,3 +71,209 @@ fn editing_one_entry_recolours_only_its_pixels() {
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bar_colours(&s), before);
}
const WHITE: [f32; 4] = [1.0; 4];
/// The issue's palette PNG: a 6 × 2 image over the table red, white, white, two columns per
/// index, opened as a document.
fn red_white_white() -> Session {
let row = [0u8, 0, 1, 1, 2, 2];
let indices: Vec<u8> = row.iter().chain(&row).copied().collect();
let png = photocraft_codecs::encode_png_indexed(6, 2, &indices, &[[255, 0, 0], [255, 255, 255], [255, 255, 255]], None, None, None).unwrap();
let opened = photocraft_io::import("red-white-white.png", &png).unwrap();
let mut s = Session::new();
s.add_document(opened.document, None);
s
}
/// One pixel per column pair (index 0, 1 and 2 in the file).
fn pairs(s: &Session) -> [[f32; 4]; 3] {
let surf = s.active().unwrap().doc.layers[0].surface().unwrap();
[0, 2, 4].map(|x| surf.rgba(x, 1))
}
#[test]
fn an_entry_shared_with_another_keeps_its_own_pixels() {
let mut s = red_white_white();
assert_eq!(table(&s).colors, vec![[255, 0, 0], [255, 255, 255], [255, 255, 255]]);
let before = (table(&s), pairs(&s));
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
assert_eq!(pairs(&s), [RED, WHITE, GREEN], "the index-2 pixels turn green, the index-1 pixels stay white");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!((table(&s), pairs(&s)), before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(pairs(&s), [RED, WHITE, GREEN]);
}
#[test]
fn indices_survive_one_colour_table_edit_after_another() {
let mut s = red_white_white();
s.execute("image.mode.colorTable", json!({"entries": {"1": "#0000ff"}})).unwrap();
assert_eq!(pairs(&s), [RED, BLUE, WHITE]);
s.execute("image.mode.colorTable", json!({"entries": {"1": "#ffffff", "2": "#ffff00"}})).unwrap();
assert_eq!(pairs(&s), [RED, WHITE, YELLOW]);
}
#[test]
fn indices_from_the_indexed_color_conversion_tell_equal_entries_apart() {
// Turn the green entry blue, then green again: the green bar's pixels kept their index
// while the table had two blue entries.
let mut s = bars();
let (red, green, blue) = (index_of(&table(&s), RED), index_of(&table(&s), GREEN), index_of(&table(&s), BLUE));
s.execute("image.mode.colorTable", json!({"entries": {green.to_string(): "#0000ff"}})).unwrap();
assert_eq!(bar_colours(&s), [RED, BLUE, BLUE, YELLOW]);
s.execute("image.mode.colorTable", json!({"entries": {green.to_string(): "#00ff00"}})).unwrap();
assert_eq!(bar_colours(&s), [RED, GREEN, BLUE, YELLOW]);
s.execute("image.mode.colorTable", json!({"entries": {red.to_string(): "#0000ff", blue.to_string(): "#ff00ff"}})).unwrap();
assert_eq!(bar_colours(&s), [BLUE, GREEN, [1.0, 0.0, 1.0, 1.0], YELLOW]);
}
#[test]
fn a_saved_document_keeps_its_indices() {
let s = red_white_white();
let saved = photocraft_io::export(&s.active().unwrap().doc, "pcraft", &Default::default()).unwrap();
let reopened = photocraft_io::import("red-white-white.pcraft", &saved.bytes).unwrap();
assert!(reopened.document.color_indices.is_some());
let mut s = Session::new();
s.add_document(reopened.document, None);
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
assert_eq!(pairs(&s), [RED, WHITE, GREEN]);
}
#[test]
fn painted_pixels_fall_back_to_the_nearest_entry() {
// After a paint stroke the indices are unknown: as before, each pixel's colour picks the
// first matching entry.
let mut s = red_white_white();
s.edit("paint", |doc, _| {
let surf = doc.layers[0].surface_mut().unwrap();
let fmt = surf.format();
surf.write_region(Rect::from_xywh(5, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, WHITE));
Ok(())
})
.unwrap();
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
assert_eq!(pairs(&s), [RED, WHITE, WHITE]);
}
#[test]
fn a_known_index_past_a_shrunk_table_stays_black_until_the_table_grows_back() {
let mut s = bars();
let t = table(&s);
let yellow = index_of(&t, YELLOW);
assert_eq!(yellow, 3, "the test needs a bar at index 3");
s.execute("image.mode.colorTable", json!({"colors": ["#00ffff", "#ff00ff", "#ffffff"]})).unwrap();
assert_eq!(bar_colours(&s)[3], [0.0, 0.0, 0.0, 1.0]);
// Black is as near cyan as magenta: by colour it would take entry 0 and turn red here.
s.execute("image.mode.colorTable", json!({"entries": {"0": "#ff0000"}})).unwrap();
assert_eq!(bar_colours(&s)[3], [0.0, 0.0, 0.0, 1.0]);
s.execute("image.mode.colorTable", json!({"colors": ["#ff0000", "#ff00ff", "#ffffff", "#00ff00"]})).unwrap();
assert_eq!(bar_colours(&s)[3], GREEN, "index 3 takes the new entry 3");
}
#[test]
fn moved_pixels_fall_back_to_the_nearest_entry() {
// Solid tiles of one colour but different indices: index 0 red, then index 2 white, then
// index 1 white, 256 columns each. Canvas Size anchored right moves the pixels 100 columns
// left; a moved tile can share storage with the one recorded at its place, so the indices
// must not be trusted after a move. The pixels of index 1 must not turn green.
let indices: Vec<u8> = (0..256).flat_map(|_| (0..768).map(|x| [0u8, 2, 1][x / 256])).collect();
let png = photocraft_codecs::encode_png_indexed(768, 256, &indices, &[[255, 0, 0], [255, 255, 255], [255, 255, 255]], None, None, None).unwrap();
let mut s = Session::new();
s.add_document(photocraft_io::import("solid.png", &png).unwrap().document, None);
s.execute("image.canvasSize", json!({"width": 668, "height": 256, "anchor": "right"})).unwrap();
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
let surf = s.active().unwrap().doc.layers[0].surface().unwrap();
for x in [412, 500, 667] {
assert_eq!(surf.rgba(x, 10), WHITE, "x {x} came from index 1");
}
}
/// A palette PNG of `indices` (row by row, `w` wide) at `depth` bits over `palette`, with an
/// optional eXIf block.
fn palette_png(w: u32, indices: &[u8], depth: png::BitDepth, palette: &[[u8; 3]], exif: Option<&[u8]>) -> Vec<u8> {
let bits = depth as usize;
let rows: Vec<u8> = indices
.chunks(w as usize)
.flat_map(|row| {
let mut packed = vec![0u8; (row.len() * bits).div_ceil(8)];
for (x, &i) in row.iter().enumerate() {
packed[x * bits / 8] |= i << (8 - bits - x * bits % 8);
}
packed
})
.collect();
let mut out = Vec::new();
let mut e = png::Encoder::new(&mut out, w, (indices.len() / w as usize) as u32);
e.set_color(png::ColorType::Indexed);
e.set_depth(depth);
e.set_palette(palette.concat());
let mut wr = e.write_header().unwrap();
if let Some(exif) = exif {
wr.write_chunk(png::chunk::eXIf, exif).unwrap();
}
wr.write_image_data(&rows).unwrap();
drop(wr);
out
}
#[test]
fn palette_pngs_of_every_bit_depth_keep_their_indices() {
// Odd widths, so rows end in a partly used byte.
for (depth, w) in [(png::BitDepth::One, 11), (png::BitDepth::Two, 7), (png::BitDepth::Four, 5), (png::BitDepth::Eight, 3)] {
let max = (1u16 << depth as u8) - 1;
let row: Vec<u8> = (0..w).map(|x| (x as u16 % (max + 1)).min(max) as u8).collect();
let indices: Vec<u8> = row.iter().chain(&row).copied().collect();
let palette: Vec<[u8; 3]> = (0..=max).map(|_| [255, 255, 255]).collect();
let png = palette_png(w, &indices, depth, &palette, None);
let doc = photocraft_io::import("p.png", &png).unwrap().document;
let layer = &doc.layers[0];
let known = doc.color_indices.as_ref().unwrap().known(layer.id, layer.surface().unwrap(), doc.bounds());
assert_eq!(known.as_deref(), Some(&indices[..]), "{depth:?}");
}
}
#[test]
fn a_transparent_entry_keeps_its_index() {
let png = photocraft_codecs::encode_png_indexed(3, 1, &[0, 1, 2], &[[0, 0, 0], [255, 255, 255], [255, 255, 255]], Some(0), None, None).unwrap();
let mut s = Session::new();
s.add_document(photocraft_io::import("t.png", &png).unwrap().document, None);
assert!(s.active().unwrap().doc.color_indices.is_some());
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
let surf = s.active().unwrap().doc.layers[0].surface().unwrap();
assert_eq!([0, 1, 2].map(|x| surf.rgba(x, 0)), [[0.0; 4], WHITE, GREEN]);
}
#[test]
fn a_turned_palette_png_records_no_indices() {
// EXIF orientation 2 (mirrored): the file's indices aren't where its pixels open, and with
// two white entries the colours can't show it.
let exif = b"MM\x00\x2a\x00\x00\x00\x08\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00\x00\x00\x00\x00";
let png = palette_png(4, &[0, 0, 1, 1], png::BitDepth::Eight, &[[255, 255, 255], [255, 255, 255]], Some(exif));
let opened = photocraft_io::import("turned.png", &png).unwrap();
assert_eq!(opened.document.color_table.as_ref().map(|t| t.colors.len()), Some(2), "opens as Indexed Color");
assert!(opened.document.color_indices.is_none());
// Control: the same file without the eXIf block keeps them.
let png = palette_png(4, &[0, 0, 1, 1], png::BitDepth::Eight, &[[255, 255, 255], [255, 255, 255]], None);
assert!(photocraft_io::import("upright.png", &png).unwrap().document.color_indices.is_some());
}
#[test]
fn a_flip_saved_and_reopened_leaves_the_indices_unknown() {
// White, red, white: mirror-symmetric colours, so the flipped tiles have the same bytes as
// the recorded ones, and a reopened file loads identical tiles as one. The save must not
// carry the indices from before the flip.
let row = [0u8, 0, 1, 1, 2, 2];
let indices: Vec<u8> = row.iter().chain(&row).copied().collect();
let png = photocraft_codecs::encode_png_indexed(6, 2, &indices, &[[255, 255, 255], [255, 0, 0], [255, 255, 255]], None, None, None).unwrap();
let mut s = Session::new();
s.add_document(photocraft_io::import("wrw.png", &png).unwrap().document, None);
s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
let saved = photocraft_io::export(&s.active().unwrap().doc, "pcraft", &Default::default()).unwrap();
let reopened = photocraft_io::import("wrw.pcraft", &saved.bytes).unwrap();
assert!(reopened.document.color_indices.is_none());
let mut s = Session::new();
s.add_document(reopened.document, None);
s.execute("image.mode.colorTable", json!({"entries": {"2": "#00ff00"}})).unwrap();
assert_eq!(pairs(&s), [WHITE, RED, WHITE], "the right columns came from index 0");
}
+23 -6
View File
@@ -5,15 +5,15 @@ use std::sync::Arc;
use photocraft_color::{PixelFormat, SampleType};
use photocraft_doc::{
AlphaChannel, CompAppearance, CompLayerState, DocId, Document, Effects, FillCache, Group, Layer, LayerComp, LayerContent, LayerId, LayerMask, Metadata,
NamedPath, Pattern, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,
AlphaChannel, ColorIndices, CompAppearance, CompLayerState, DocId, Document, Effects, FillCache, Group, Layer, LayerComp, LayerContent, LayerId, LayerMask,
Metadata, NamedPath, Pattern, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,
};
use photocraft_geom::{TILE_SIZE, TileCoord};
use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};
use crate::manifest::{
ChannelM, CompAppearanceM, CompStateM, ContentM, DocM, EffectsM, FillCacheM, Hash, LayerCompM, LayerM, MaskM, MetadataM, NamedPathM, PatternM,
SmartSourceM, SurfaceM, TileRef, VectorPreviewM,
ChannelM, ColorIndicesM, CompAppearanceM, CompStateM, ContentM, DocM, EffectsM, FillCacheM, Hash, LayerCompM, LayerM, MaskM, MetadataM, NamedPathM,
PatternM, SmartSourceM, SurfaceM, TileRef, VectorPreviewM,
};
use crate::{FormatError, Result};
@@ -278,6 +278,13 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> Result<DocM> {
.map(|p| PatternM { id: p.id.clone(), name: p.name.clone(), width: p.width, height: p.height, surface: surface_m(&p.surface, sink) })
.collect(),
color_table: d.color_table.clone(),
// Only while they hold for the layer saved here (and the document is Indexed Color): on
// open, identical tiles load as one, so loaded pixels can't show a change made since.
color_indices: d
.color_indices
.as_ref()
.filter(|c| d.color_table.is_some() && d.layer(c.layer).and_then(Layer::surface).is_some_and(|p| c.holds(c.layer, p)))
.map(|c| ColorIndicesM { layer: c.layer.0, indices: surface_m(&c.indices, sink) }),
duotone: d.duotone.clone(),
variables: d.variables.clone(),
timeline: d.timeline.clone(),
@@ -690,7 +697,7 @@ impl Loader<'_> {
}
}
let id = if self.preserve_ids { DocId(m.id) } else { DocId::fresh() };
Ok(Document {
let mut doc = Document {
id,
name: m.name.clone(),
size: m.size,
@@ -712,6 +719,7 @@ impl Loader<'_> {
quick_mask_unselected: m.quick_mask_unselected,
patterns,
color_table: m.color_table.clone(),
color_indices: None,
duotone: m.duotone.clone(),
variables,
timeline: m.timeline.clone(),
@@ -723,7 +731,16 @@ impl Loader<'_> {
notes: m.notes.clone(),
text_styles: m.text_styles.clone(),
slices,
})
};
// Saved only while they held for the layer as saved, so they pair with its pixels as
// loaded. Optional side data: indices of a layer the file doesn't hold, or damaged ones,
// are dropped (Color Table then maps by nearest colour) rather than failing the open.
doc.color_indices = m.color_indices.as_ref().and_then(|c| {
let layer = *self.id_map.get(&c.layer)?;
let pixels = doc.layer(layer)?.surface()?.clone();
Some(ColorIndices { layer, pixels, indices: self.surface(&c.indices).ok()? })
});
Ok(doc)
}
fn channel(&mut self, c: &ChannelM) -> Result<AlphaChannel> {
+11
View File
@@ -60,6 +60,9 @@ pub struct DocM {
/// Indexed Color palette.
#[serde(default)]
pub color_table: Option<photocraft_doc::ColorTable>,
/// Indexed Color pixel indices, where known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color_indices: Option<ColorIndicesM>,
/// Duotone inks.
#[serde(default)]
pub duotone: Option<photocraft_doc::Duotone>,
@@ -143,6 +146,14 @@ pub struct NamedPathM {
pub psd_raw: Option<Hash>,
}
/// [`photocraft_doc::ColorIndices`]: the layer (by id) and its pixels' indices. Saved only while
/// they hold for the layer as saved, so the layer's own pixels are the recorded ones on open.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ColorIndicesM {
pub layer: u64,
pub indices: SurfaceM,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SurfaceM {
pub format: PixelFormat,
+3
View File
@@ -53,6 +53,9 @@ serde_json = { workspace = true }
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
# pdn.rs inflates Paint.NET's gzip pixel chunks.
flate2 = { workspace = true }
# flat.rs reads a palette PNG's pixel indices (Color Table, #14342). The png 0.18 that
# craft-image-codecs already links; naming it adds no crate to the graph.
png = "0.18"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
ttf-parser = { version = "0.25", default-features = false }
+55 -1
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CSample};
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent};
use photocraft_doc::{AlphaChannel, ColorIndices, Document, Layer, LayerContent};
use photocraft_geom::{Rect, Size, TILE_SIZE};
use photocraft_raster::{AllocationError, Interrupt, PruneCursor, RowWriteError, Surface};
@@ -258,6 +258,57 @@ impl FlatBuilder {
}
}
/// Each pixel's palette index in the palette PNG `bytes`, opened as `doc`, so Color Table can
/// tell entries of one colour apart (#14342). `None`, and Color Table falls back to the nearest
/// entry, when the document's one layer doesn't show each pixel's entry at the file's place for
/// it (an EXIF orientation turned the pixels, which colours alone can't show when entries repeat,
/// or a colour conversion changed them), or when the file is interlaced (not read here). One row at a time:
/// next to the layer, only the indices themselves (a byte per pixel) are held.
fn png_color_indices(bytes: &[u8], doc: &Document) -> Option<ColorIndices> {
let table = doc.color_table.as_ref()?;
let [layer] = doc.layers.as_slice() else { return None };
let surface = layer.surface()?;
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::IDENTITY);
decoder.set_ignore_text_chunk(true);
let mut reader = decoder.read_info().ok()?;
let info = reader.info();
let (w, h, bits) = (info.width, info.height, info.bit_depth as usize);
if info.color_type != png::ColorType::Indexed || info.interlaced || !matches!(bits, 1 | 2 | 4 | 8) || (w, h) != (doc.size.width, doc.size.height) {
return None;
}
let width = usize::try_from(w).ok()?;
let count = width.checked_mul(usize::try_from(h).ok()?)?;
let mut indices = Vec::new();
indices.try_reserve_exact(count).ok()?;
let mut shown = vec![[0u8; 4]; width];
let mut y = 0;
while let Some(row) = reader.next_row().ok()? {
if indices.len() >= count {
return None;
}
surface.read_rgba8_into(Rect::from_xywh(0, y, w, 1), &mut shown);
for (x, px) in shown.iter().enumerate() {
let bit = x * bits;
let byte = *row.data().get(bit / 8)?;
let i = (byte >> (8 - bits - bit % 8)) & (0xff >> (8 - bits));
let entry = table.colors.get(usize::from(i))?;
let ok = if px[3] == 0 { table.transparent == Some(i) } else { px[..3] == entry[..] };
if !ok {
return None;
}
indices.push(i);
}
y += 1;
}
// An eXIf after the pixels counts too.
reader.finish().ok()?;
if reader.info().exif_metadata.as_deref().is_some_and(|e| codecs::exif_orientation(e) != 1) || indices.len() != count {
return None;
}
ColorIndices::new(layer.id, surface, doc.bounds(), &indices)
}
/// What every flat format does to the document of its pixels: the palette mode, the save
/// settings, a Targa's alpha channel and the profile an untagged image needs. `img` is the
/// decoded image, when the document was built from one (a streamed PNG has none).
@@ -275,6 +326,9 @@ pub(crate) fn apply_flat_format(r: &mut ImportResult, bytes: &[u8], format: Opti
{
r.document.mode = ColorMode::Indexed;
r.document.color_table = Some(photocraft_doc::ColorTable { colors, transparent });
if format == Some(Format::Png) {
r.document.color_indices = png_color_indices(bytes, &r.document);
}
}
// The decoder's count of frames or pages left out (set above) stays alongside the encoding.
let encoding = file_encoding_as(format, bytes);
+3
View File
@@ -159,6 +159,9 @@ fn assert_same(a: &ImportResult, b: &ImportResult, what: &str) {
let mut db = db.clone();
db.id = da.id;
db.layers.iter_mut().zip(&da.layers).for_each(|(l, k)| l.id = k.id);
if let (Some(c), Some(k)) = (db.color_indices.as_mut(), &da.color_indices) {
c.layer = k.layer;
}
assert!(da == &db, "{what}: documents differ");
}
+3
View File
@@ -45,6 +45,9 @@ fn assert_same(a: &Document, b: &Document, what: &str) {
for (x, y) in a.layers.iter_mut().zip(&mut b.layers) {
y.id = x.id;
}
if let (Some(x), Some(y)) = (&a.color_indices, b.color_indices.as_mut()) {
y.layer = x.layer;
}
assert!(a == b, "{what}: the documents differ");
}