Skip to content

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

Support .act color tables end to end (swatches + Color Table dialog)

Abdul Karim Miafef5e042bd26
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index a5c9d8a56..55738ccd9 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -15,11 +15,11 @@ use wasm_bindgen::JsCast as _;
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
-/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
+/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .act, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr",
"pbm", "pgm", "ppm", "pam", "pfm", "dds", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf",
- "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af", "afdesign", "afphoto", "afpub",
+ "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "act", "ase", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
const CANVAS_ID: &str = "photocraft_canvas";
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index d4a3869f3..d77358d61 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -17,12 +17,12 @@ use std::sync::Arc;
mod recovery_tests;
/// Everything File › Open reads: PhotoCraft, Photoshop, OpenRaster, Krita and Affinity documents, flat images, and
-/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets
+/// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .act, .ase) and keyboard shortcut sets
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "ora", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr",
"pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw",
- "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
+ "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
@@ -71,7 +71,7 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[
/// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog
/// never swaps their extension for a document format's.
-const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Swatch Exchange", &["ase"])];
+const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Color Table", &["act"]), ("Swatch Exchange", &["ase"])];
/// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd.
fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
diff --git a/crates/engine/src/swatch_cmds.rs b/crates/engine/src/swatch_cmds.rs
index 7844124bd..fa561df67 100644
--- a/crates/engine/src/swatch_cmds.rs
+++ b/crates/engine/src/swatch_cmds.rs
@@ -362,6 +362,7 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Aco,
+ Act,
Ase,
}
@@ -369,6 +370,7 @@ impl Format {
fn parse(s: &str) -> Option<Format> {
match s.trim_start_matches('.').to_ascii_lowercase().as_str() {
"aco" => Some(Format::Aco),
+ "act" => Some(Format::Act),
"ase" => Some(Format::Ase),
_ => None,
}
@@ -376,6 +378,7 @@ impl Format {
fn id(self) -> &'static str {
match self {
Format::Aco => "aco",
+ Format::Act => "act",
Format::Ase => "ase",
}
}
@@ -462,6 +465,21 @@ fn kind_to_ase(k: SwatchKind) -> AseKind {
}
}
+/// Colors in an `.act` color table (what the format holds).
+pub const ACT_COLORS: usize = photocraft_psd::act::COLOR_COUNT;
+
+/// `.act` bytes as `#rrggbb` colors plus the transparent index, for the Color Table dialog.
+pub fn act_table(bytes: &[u8]) -> std::result::Result<(Vec<String>, Option<u64>), String> {
+ let f = photocraft_psd::act::parse(bytes).map_err(|e| e.to_string())?;
+ let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
+ Ok((f.used().iter().map(hex).collect(), f.transparent_index().map(|i| i as u64)))
+}
+
+/// Encode colors as `.act` bytes (at most [`ACT_COLORS`]); the transparent index is kept.
+pub fn act_bytes(colors: &[[u8; 3]], transparent: Option<u16>) -> std::result::Result<Vec<u8>, String> {
+ photocraft_psd::act::write(colors, Some(colors.len().min(ACT_COLORS) as u16), transparent).map_err(|e| e.to_string())
+}
+
/// Parse a swatch file into groups (`group` names the group for ungrouped colours).
pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Result<(Vec<Group<Swatch>>, Vec<String>), String> {
let mut warnings = Vec::new();
@@ -484,6 +502,19 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu
.collect();
out.push(Group::new(group, items));
}
+ Format::Act => {
+ let f = photocraft_psd::act::parse(bytes).map_err(|e| format!("not a readable .act color table: {e}"))?;
+ if let Some(t) = f.transparent_index() {
+ warnings.push(format!("color {} is the table's transparent color; swatches have no transparency so it was kept opaque", t + 1));
+ }
+ let items = f
+ .used()
+ .iter()
+ .enumerate()
+ .map(|(i, c)| Swatch { name: format!("Swatch {}", i + 1), color: SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0)), kind: SwatchKind::Process })
+ .collect();
+ out.push(Group::new(group, items));
+ }
Format::Ase => {
let f = photocraft_psd::ase::parse(bytes).map_err(|e| format!("not a readable .ase swatch file: {e}"))?;
let mut skipped = 0;
@@ -541,6 +572,32 @@ pub fn write_file(groups: &[Group<Swatch>], format: Format) -> std::result::Resu
let bytes = photocraft_psd::aco::write(&swatches).map_err(|e| e.to_string())?;
Ok((bytes, n, warnings))
}
+ Format::Act => {
+ // `.act` holds RGB only: HSB rides along as RGB, anything else is left out.
+ let rgb8 = |v: [f32; 3]| v.map(|c| (unit(c) * 255.0).round() as u8);
+ let mut triplets = Vec::new();
+ let mut skipped = 0;
+ for s in groups.iter().flat_map(|g| g.items.iter()) {
+ match s.color {
+ SwatchColor::Rgb(v) => triplets.push(rgb8(v)),
+ SwatchColor::Hsb(v) => triplets.push(rgb8(hsb_to_rgb(v))),
+ _ => skipped += 1,
+ }
+ }
+ if groups.len() > 1 {
+ warnings.push(".act files have no groups; the swatches were saved as one list".into());
+ }
+ if skipped > 0 {
+ warnings.push(format!("{skipped} non-RGB swatches can't be stored in an .act file and were left out (save as .aco to keep them)"));
+ }
+ if triplets.len() > photocraft_psd::act::COLOR_COUNT {
+ warnings.push(format!("only the first {} swatches fit in an .act file", photocraft_psd::act::COLOR_COUNT));
+ triplets.truncate(photocraft_psd::act::COLOR_COUNT);
+ }
+ let n = triplets.len();
+ let bytes = photocraft_psd::act::write(&triplets, Some(n as u16), None).map_err(|e| e.to_string())?;
+ Ok((bytes, n, warnings))
+ }
Format::Ase => {
let mut books = 0;
let mut entries = Vec::with_capacity(groups.len());
@@ -571,12 +628,17 @@ pub fn write_file(groups: &[Group<Swatch>], format: Format) -> std::result::Resu
fn import(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "swatches.import";
- let (bytes, stem) = crate::preset_import_cmds::file_bytes(p, CMD, ".aco or .ase file")?;
+ let (bytes, stem) = crate::preset_import_cmds::file_bytes(p, CMD, ".aco, .act or .ase file")?;
let format = match str_param(p, "format") {
- Some(f) => Format::parse(f).ok_or_else(|| bad(CMD, format!("unknown format `{f}` (aco|ase)")))?,
+ Some(f) => Format::parse(f).ok_or_else(|| bad(CMD, format!("unknown format `{f}` (aco|act|ase)")))?,
+ None if ext_format(str_param(p, "path")) == Some(Format::Act) => Format::Act,
None if bytes.starts_with(photocraft_psd::ase::SIGNATURE) => Format::Ase,
None if matches!(bytes.get(..2), Some([0, 1] | [0, 2])) => Format::Aco,
- None => ext_format(str_param(p, "path")).ok_or_else(|| bad(CMD, "not an .aco or .ase swatch file"))?,
+ // `.act` has no magic: an exact 768/772 bytes that is neither .ase nor .aco.
+ None if bytes.len() == photocraft_psd::act::PALETTE_LEN || bytes.len() == photocraft_psd::act::PALETTE_LEN + photocraft_psd::act::TRAILER_LEN => {
+ Format::Act
+ }
+ None => ext_format(str_param(p, "path")).ok_or_else(|| bad(CMD, "not an .aco, .act or .ase swatch file"))?,
};
let mode = str_param(p, "mode").unwrap_or("append");
let replace = match mode {
@@ -634,7 +696,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "swatches.export";
let path = str_param(p, "path");
let format = match str_param(p, "format") {
- Some(f) => Format::parse(f).ok_or_else(|| bad(CMD, format!("unknown format `{f}` (aco|ase)")))?,
+ Some(f) => Format::parse(f).ok_or_else(|| bad(CMD, format!("unknown format `{f}` (aco|act|ase)")))?,
None => ext_format(path).unwrap_or(Format::Aco),
};
let mut groups: Vec<Group<Swatch>> = match name_param(p, "group", CMD)? {
@@ -790,7 +852,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Import Swatches…",
menu: &[],
shortcut: None,
- params: r##"{"path":".aco or .ase file"?,"data":base64 bytes?,"format":"aco|ase"? (detected),"mode":"append|replace"="append","group":str?=file name (the group for ungrouped colours)} → {format,mode,groups,count,warnings}"##,
+ params: r##"{"path":".aco, .act or .ase file"?,"data":base64 bytes?,"format":"aco|act|ase"? (detected),"mode":"append|replace"="append","group":str?=file name (the group for ungrouped colours)} → {format,mode,groups,count,warnings}"##,
enabled: always,
run: import,
journal: true,
@@ -800,7 +862,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Export Swatches…",
menu: &[],
shortcut: None,
- params: r##"{"format":"aco|ase"?=from path, else aco,"path":file? (else the bytes come back as base64 `data`),"group":name? (only that group),"swatches":[names]? (only these)} → {format,count,bytes,warnings,path|data}"##,
+ params: r##"{"format":"aco|act|ase"?=from path, else aco,"path":file? (else the bytes come back as base64 `data`),"group":name? (only that group),"swatches":[names]? (only these)} → {format,count,bytes,warnings,path|data}"##,
enabled: has_swatches,
run: export,
journal: true,
diff --git a/crates/engine/src/swatch_cmds/tests.rs b/crates/engine/src/swatch_cmds/tests.rs
index 2a3e8e7dd..4c121359f 100644
--- a/crates/engine/src/swatch_cmds/tests.rs
+++ b/crates/engine/src/swatch_cmds/tests.rs
@@ -146,6 +146,39 @@ fn aco_round_trip_keeps_16_bit_values_and_books() {
std::fs::remove_dir_all(&dir).ok();
}
+#[test]
+fn act_round_trip_loads_a_photoshop_color_table() {
+ // A Photoshop-saved table: 256 RGB colors plus the count/transparent trailer.
+ let mut colors = [[0u8; 3]; 256];
+ colors[0] = [255, 255, 255];
+ for (i, c) in colors.iter_mut().enumerate().skip(1) {
+ let v = i as u8;
+ *c = [v, 255 - v, 128];
+ }
+ let file = photocraft_psd::act::write(&colors, Some(256), Some(255)).unwrap();
+ assert_eq!(file.len(), 772);
+ let mut s = Session::new();
+ let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Table", "mode": "replace"})).unwrap();
+ assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("act"), Some(256)));
+ assert_eq!(r["warnings"].as_array().unwrap().len(), 1, "the transparent color is reported");
+ assert_eq!(s.presets.swatches[0].items[0].color, SwatchColor::Rgb([1.0, 1.0, 1.0]));
+ assert_eq!(s.presets.swatches[0].items[1].name, "Swatch 2");
+ // Sniffed by length without a format, and by extension from a path.
+ let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap();
+ assert_eq!(r["format"].as_str(), Some("act"));
+ // Export keeps the 256 RGB colors; the trailer comes back in canonical form
+ // (swatches have no transparency to preserve).
+ let canon = photocraft_psd::act::write(&colors, Some(256), None).unwrap();
+ assert_eq!(export_bytes(&mut s, json!({"format": "act"})), canon);
+ // A bigger library is capped at 256 with a warning; groups collapse to one list.
+ for i in 0..300 {
+ s.execute("swatches.add", json!({"name": format!("Extra {i}"), "color": {"model": "rgb", "values": [1, 0, 0]}})).unwrap();
+ }
+ let r = s.execute("swatches.export", json!({"format": "act"})).unwrap();
+ assert_eq!(r["count"], 256);
+ assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("first 256"))));
+}
+
#[test]
fn ase_round_trip_keeps_groups_floats_and_kinds() {
let src = AseFile {
diff --git a/crates/psd/src/act.rs b/crates/psd/src/act.rs
new file mode 100644
index 000000000..ab5fe4862
--- /dev/null
+++ b/crates/psd/src/act.rs
@@ -0,0 +1,143 @@
+//! Photoshop Color Table files (`.act`): raw 8-bit RGB palettes.
+//!
+//! Layout from Adobe's public "Photoshop File Formats Specification" (Color Table): 256 RGB
+//! triplets (768 bytes), optionally followed by a 4-byte trailer: a big-endian `u16` color
+//! count ("the number of colors to use") and a big-endian `u16` transparent color index.
+//! There are no names, no groups and no other color spaces. The trailer is kept verbatim so a
+//! read → write round trip never loses it; interpreting it is the caller's job.
+
+use crate::error::{PsdError, Result};
+use crate::io::{Reader, WriteExt};
+
+/// Colors in a `.act` palette.
+pub const COLOR_COUNT: usize = 256;
+/// Palette bytes: 256 RGB triplets.
+pub const PALETTE_LEN: usize = COLOR_COUNT * 3;
+/// Trailer bytes (color count + transparent index).
+pub const TRAILER_LEN: usize = 4;
+
+/// A parsed `.act` file: the full 256-color palette plus the optional trailer, kept verbatim.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ActFile {
+ /// All 256 palette colors as RGB triplets.
+ pub colors: [[u8; 3]; COLOR_COUNT],
+ /// Trailer color count ("the number of colors to use"), if the file has one.
+ pub count: Option<u16>,
+ /// Trailer transparent color index, if the file has one.
+ pub transparent: Option<u16>,
+}
+
+impl ActFile {
+ /// Colors to use: the trailer count clamped to the palette, else the whole palette.
+ pub fn used(&self) -> &[[u8; 3]] {
+ let n = self.count.map_or(COLOR_COUNT, |c| (c as usize).min(COLOR_COUNT));
+ &self.colors[..n]
+ }
+
+ /// The transparent color index, if the trailer names one inside the used colors.
+ pub fn transparent_index(&self) -> Option<usize> {
+ let t = usize::from(self.transparent?);
+ (t < self.used().len()).then_some(t)
+ }
+}
+
+/// Parse an `.act` file. Anything but 768 bytes (palette only) or 772 bytes (plus the
+/// trailer) is an error; never panics.
+pub fn parse(data: &[u8]) -> Result<ActFile> {
+ if data.len() != PALETTE_LEN && data.len() != PALETTE_LEN + TRAILER_LEN {
+ return Err(PsdError::invalid("an .act file is 768 bytes, or 772 with the count trailer"));
+ }
+ let mut r = Reader::new(data);
+ let raw = r.bytes(PALETTE_LEN)?;
+ let mut colors = [[0u8; 3]; COLOR_COUNT];
+ for (i, c) in colors.iter_mut().enumerate() {
+ let o = i * 3;
+ c.copy_from_slice(&raw[o..o + 3]);
+ }
+ let (count, transparent) = if r.remaining() >= TRAILER_LEN { (Some(r.u16()?), Some(r.u16()?)) } else { (None, None) };
+ Ok(ActFile { colors, count, transparent })
+}
+
+/// Write an `.act` file: the 256-color palette plus the trailer when `file` has one.
+/// Short palettes are padded with black; fails on a palette longer than 256 colors.
+pub fn write(colors: &[[u8; 3]], count: Option<u16>, transparent: Option<u16>) -> Result<Vec<u8>> {
+ if colors.len() > COLOR_COUNT {
+ return Err(PsdError::LimitExceeded("an .act file holds at most 256 colors"));
+ }
+ let mut out = Vec::with_capacity(PALETTE_LEN + TRAILER_LEN);
+ for c in colors {
+ out.extend_from_slice(c);
+ }
+ out.resize(PALETTE_LEN, 0);
+ if count.is_some() || transparent.is_some() {
+ out.put_u16(count.unwrap_or(COLOR_COUNT as u16));
+ out.put_u16(transparent.unwrap_or(0xFFFF));
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> [[u8; 3]; COLOR_COUNT] {
+ let mut colors = [[0u8; 3]; COLOR_COUNT];
+ for (i, c) in colors.iter_mut().enumerate() {
+ let v = i as u8;
+ *c = [v, v.wrapping_mul(7), v.wrapping_add(13)];
+ }
+ colors[0] = [255, 255, 255];
+ colors
+ }
+
+ #[test]
+ fn round_trips_with_and_without_the_trailer() {
+ let colors = sample();
+ let bare = write(&colors, None, None).unwrap();
+ assert_eq!(bare.len(), PALETTE_LEN);
+ let f = parse(&bare).unwrap();
+ assert_eq!((f.count, f.transparent), (None, None));
+ assert_eq!(f.used(), &colors);
+ assert_eq!(f.transparent_index(), None);
+ assert_eq!(write(&f.colors, f.count, f.transparent).unwrap(), bare, "byte-stable");
+
+ let trailer = write(&colors, Some(40), Some(7)).unwrap();
+ assert_eq!(trailer.len(), PALETTE_LEN + TRAILER_LEN);
+ let f = parse(&trailer).unwrap();
+ assert_eq!((f.count, f.transparent), (Some(40), Some(7)));
+ assert_eq!(f.used().len(), 40);
+ assert_eq!(f.transparent_index(), Some(7));
+ assert_eq!(write(&f.colors, f.count, f.transparent).unwrap(), trailer, "byte-stable");
+ }
+
+ #[test]
+ fn short_palettes_pad_and_long_ones_fail() {
+ let few = vec![[1u8, 2, 3]; 3];
+ let bytes = write(&few, None, None).unwrap();
+ assert_eq!(bytes.len(), PALETTE_LEN);
+ assert_eq!(&bytes[..9], &[1u8, 2, 3, 1, 2, 3, 1, 2, 3]);
+ assert_eq!(&bytes[9..12], &[0u8, 0, 0]);
+ let many = vec![[0u8; 3]; COLOR_COUNT + 1];
+ assert!(write(&many, None, None).is_err());
+ }
+
+ #[test]
+ fn hostile_lengths_are_errors_not_panics() {
+ let good = write(&sample(), Some(256), Some(255)).unwrap();
+ assert_eq!(good.len(), PALETTE_LEN + TRAILER_LEN);
+ for n in 0..good.len() {
+ // Only the two exact lengths parse (768 reads as a trailer-less palette).
+ if n == PALETTE_LEN {
+ assert!(parse(&good[..n]).is_ok(), "{n}");
+ } else {
+ assert!(parse(&good[..n]).is_err(), "{n}");
+ }
+ }
+ assert!(parse(&[]).is_err());
+ assert!(parse(&vec![0u8; PALETTE_LEN + TRAILER_LEN + 1]).is_err(), "trailing byte");
+ // A count past the palette clamps; a transparent index past it is none.
+ let f = parse(&write(&sample(), Some(1000), Some(999)).unwrap()).unwrap();
+ assert_eq!(f.used().len(), COLOR_COUNT);
+ assert_eq!(f.transparent_index(), None);
+ }
+}
diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs
index 00d73c400..4fd526f07 100644
--- a/crates/psd/src/lib.rs
+++ b/crates/psd/src/lib.rs
@@ -42,6 +42,7 @@
pub mod abr;
pub mod aco;
+pub mod act;
pub mod ase;
pub mod atn;
pub mod blend;
diff --git a/crates/ui-egui/src/color_table_ui.rs b/crates/ui-egui/src/color_table_ui.rs
new file mode 100644
index 000000000..0e6000794
--- /dev/null
+++ b/crates/ui-egui/src/color_table_ui.rs
@@ -0,0 +1,141 @@
+//! Image › Mode › Color Table…: Load… and Save… for `.act` color tables, as in Photoshop.
+//!
+//! The dialog itself is the schema one (`filter_dialog`); this module only adds the file row.
+//! Load fills the pending table from a picked `.act` (OK then applies it); Save writes the
+//! pending table — the dialog's colors, else its preset, else the document's table — to a
+//! picked `.act`. Parsing lives in the engine (`swatch_cmds`); this module only draws and
+//! dispatches.
+
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+
+pub fn owns(fields: &Map<String, Value>) -> bool {
+ fields.get("__command").and_then(Value::as_str) == Some("image.mode.colorTable")
+}
+
+fn unhex(s: &str) -> Option<[u8; 3]> {
+ let f = crate::color_picker_ui::parse_hex(s)?;
+ Some(f.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8))
+}
+
+/// The pending table: the dialog's colors, else its preset, else the document's table.
+fn pending(app: &PhotocraftApp, fields: &Map<String, Value>) -> Option<(Vec<[u8; 3]>, Option<u16>)> {
+ if let Some(a) = fields.get("colors").and_then(Value::as_array) {
+ let colors: Option<Vec<[u8; 3]>> = a.iter().filter_map(Value::as_str).map(unhex).collect();
+ let colors = colors.filter(|c| !c.is_empty() && c.len() <= photocraft_engine::swatch_cmds::ACT_COLORS)?;
+ let transparent = fields.get("transparent").and_then(Value::as_u64).and_then(|i| u16::try_from(i).ok());
+ return Some((colors, transparent));
+ }
+ if let Some(name) = fields.get("table").and_then(Value::as_str)
+ && let Some(colors) = photocraft_engine::mode_cmds::preset_table(name)
+ {
+ return Some((colors, None));
+ }
+ let t = app.session.active()?.doc.color_table.clone()?;
+ Some((t.colors, t.transparent.map(u16::from)))
+}
+
+/// Load…/Save… row for the Color Table dialog (`id` finds its fields after the file picker
+/// answers, as the picker is asynchronous).
+pub fn buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: u64, fields: &Map<String, Value>) {
+ ui.horizontal(|ui| {
+ if ui.button(tl!("Load…")).clicked()
+ && let Err(e) = app.pick_file_bytes_filtered(&["act"], move |app, name, bytes| {
+ let (colors, transparent) =
+ photocraft_engine::swatch_cmds::act_table(&bytes).map_err(|e| format!("{}: {e}", crate::file_open::display_name(&name)))?;
+ // The dialog may close while the picker is open; then there is nothing to fill.
+ let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) else { return Ok(Value::Null) };
+ d.fields.insert("table".into(), json!("custom"));
+ d.fields.insert("colors".into(), Value::Array(colors.into_iter().map(Value::String).collect()));
+ d.fields.insert("transparent".into(), transparent.map_or(Value::Null, |i| json!(i)));
+ Ok(Value::Null)
+ })
+ && e != crate::file_dialog::CANCELLED
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ if ui.button(tl!("Save…")).clicked() {
+ let Some((colors, transparent)) = pending(app, fields) else {
+ app.ui.status = tl!("There is no color table to save.").into();
+ app.ui.status_error = true;
+ return;
+ };
+ let bytes = match photocraft_engine::swatch_cmds::act_bytes(&colors, transparent) {
+ Ok(bytes) => bytes,
+ Err(e) => {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ return;
+ }
+ };
+ let n = colors.len() as u64;
+ if let Err(e) = app.pick_save("Table.act", move |app, path| {
+ let write = app.services.write.as_mut().ok_or("no writer configured")?;
+ write(&path, &bytes)?;
+ app.ui.status_error = false;
+ app.ui.status = crate::i18n::fmt(
+ &crate::i18n::trn(crate::i18n::current(), n, "Saved {n} color to {file}", "Saved {n} colors to {file}"),
+ &[("file", &crate::file_open::display_name(&path))],
+ );
+ Ok(json!({"path": path}))
+ }) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn app() -> PhotocraftApp {
+ PhotocraftApp::new(photocraft_engine::Session::new(), Default::default())
+ }
+
+ #[test]
+ fn owns_only_the_color_table_dialog() {
+ assert!(owns(&Map::from_iter([("__command".to_string(), json!("image.mode.colorTable"))])));
+ assert!(!owns(&Map::from_iter([("__command".to_string(), json!("image.mode.indexedColor"))])));
+ assert!(!owns(&Map::new()));
+ }
+
+ #[test]
+ fn pending_prefers_dialog_colors_then_preset() {
+ let app = app();
+ // The dialog's own colors win, with its transparent entry.
+ let fields = Map::from_iter([
+ ("table".to_string(), json!("blackBody")),
+ ("colors".to_string(), json!(["#ff0000", "#00ff00"])),
+ ("transparent".to_string(), json!(1)),
+ ]);
+ assert_eq!(pending(&app, &fields), Some((vec![[255, 0, 0], [0, 255, 0]], Some(1))));
+ // Else the preset (256 entries, no transparency).
+ let fields = Map::from_iter([("table".to_string(), json!("blackBody"))]);
+ let (colors, transparent) = pending(&app, &fields).unwrap();
+ assert_eq!((colors.len(), transparent), (256, None));
+ assert_eq!(colors[0], [0, 0, 0]);
+ // Nothing pending without colors, preset or document table.
+ assert_eq!(pending(&app, &Map::from_iter([("table".to_string(), json!("custom"))])), None);
+ }
+
+ #[test]
+ fn loaded_act_bytes_fill_the_dialog_fields() {
+ let table: Vec<[u8; 3]> = (0..256).map(|i| [i as u8, 0, 255]).collect();
+ let bytes = photocraft_engine::swatch_cmds::act_bytes(&table, Some(3)).unwrap();
+ let (colors, transparent) = photocraft_engine::swatch_cmds::act_table(&bytes).unwrap();
+ assert_eq!((colors.len(), transparent), (256, Some(3)));
+ // What OK would apply: the table's colors and transparent entry.
+ let fields = Map::from_iter([
+ ("table".to_string(), json!("custom")),
+ ("colors".to_string(), Value::Array(colors.into_iter().map(Value::String).collect())),
+ ("transparent".to_string(), json!(3)),
+ ]);
+ let app = app();
+ assert_eq!(pending(&app, &fields), Some((table, Some(3))));
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 0530031f9..40318fa2a 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -344,6 +344,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
outcome = Some(true);
}
} else {
+ // The Color Table dialog loads and saves `.act` files, as in Photoshop.
+ if matches!(d.kind, DialogKind::Command) && crate::color_table_ui::owns(&fields) {
+ crate::color_table_ui::buttons(app, ui, d.id, &fields);
+ }
ui.add_space(8.0);
// Align::Min, not Center: a centred row fills the height left over from last frame's
// (larger) size, so a dialog whose body gets shorter would never shrink back.
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 38118955c..923363328 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -56,6 +56,7 @@ pub mod cjk_fonts;
pub mod clip_line_ui;
pub mod color_picker_ui;
pub mod color_range_ui;
+pub mod color_table_ui;
pub mod comps_ui;
pub mod control;
pub mod credits;
diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs
index 6138c0884..8d516e4b6 100644
--- a/crates/ui-egui/src/preset_files_ui.rs
+++ b/crates/ui-egui/src/preset_files_ui.rs
@@ -1,7 +1,7 @@
//! Preset files opened like documents (File › Open, drag-and-drop, the Brushes panel's
//! Import Brushes…, the Preset Manager's Load…): Photoshop brushes (`.abr`) go to the brush
//! library through `brush.presets.importAbr`, gradients (`.grd`) to the Gradients panel through
-//! `gradient.presets.importGrd`, swatches (`.aco`, `.ase`) to the Swatches panel through
+//! `gradient.presets.importGrd`, swatches (`.aco`, `.act`, `.ase`) to the Swatches panel through
//! `swatches.import`, patterns (`.pat`) to the Patterns panel through `pattern.import`, keyboard
//! shortcut sets (`.kys`) to Edit › Keyboard Shortcuts through
//! [`crate::kys_import`], instead of opening as documents.
@@ -10,11 +10,11 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
-/// Extensions handled here rather than by the document importer (`.aco`/`.ase` swatches go to
+/// Extensions handled here rather than by the document importer (`.aco`/`.act`/`.ase` swatches go to
/// the Swatches panel through [`crate::swatches_ui::import_bytes`]).
/// `.psp` is Photoshop's live `Keyboard Shortcuts.psp` (the same XML as a `.kys`); other `.psp`
/// settings files are refused with a clear message.
-pub const PRESET_EXTS: &[&str] = &["abr", "grd", "pat", "aco", "ase", "kys", "psp"];
+pub const PRESET_EXTS: &[&str] = &["abr", "grd", "pat", "aco", "act", "ase", "kys", "psp"];
fn ext(name: &str) -> String {
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default()
@@ -58,7 +58,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option<Result<
"abr" => ("brush.presets.importAbr", "brushes"),
"grd" => ("gradient.presets.importGrd", "gradients"),
"pat" => ("pattern.import", "patterns"),
- "aco" | "ase" => return Some(crate::swatches_ui::import_bytes(app, name, bytes, false).map(|_| ())),
+ "aco" | "act" | "ase" => return Some(crate::swatches_ui::import_bytes(app, name, bytes, false).map(|_| ())),
"kys" | "psp" => return Some(crate::kys_import::open_bytes(app, name, bytes).map(|_| ())),
_ => return None,
};
diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/swatches_ui.rs
index 749ab4a05..b6d75f8c2 100644
--- a/crates/ui-egui/src/swatches_ui.rs
+++ b/crates/ui-egui/src/swatches_ui.rs
@@ -5,7 +5,8 @@
//! As in Photoshop, clicking a swatch sets the foreground colour (and recolours selected type);
//! Alt- or Ctrl/Cmd-clicking sets the background colour; double-clicking renames it. The
//! panel menu (the group's "…" button) adds New Swatch, New Group, Import/Replace (`.aco`,
-//! `.ase`), Export (`.aco`) and Export for Exchange (`.ase`) and Reset. Every action is a
+//! `.act`, `.ase`), Export (`.aco`), Export as Color Table (`.act`) and Export for Exchange
+//! (`.ase`) and Reset. Every action is a
//! `swatches.*` engine command; this module only draws and dispatches. Colours are shown in the
//! RGB working space through `photocraft-cms` (cached per library revision and colour settings).
@@ -149,7 +150,7 @@ fn source(name: &str, bytes: &[u8]) -> Value {
json!({"data": photocraft_engine::paint::tile::b64_encode(bytes)})
}
-/// Import an `.aco`/`.ase` file's bytes (File › Open, drag and drop, the panel menu).
+/// Import an `.aco`/`.act`/`.ase` file's bytes (File › Open, drag and drop, the panel menu).
pub fn import_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8], replace: bool) -> Result<Value, String> {
let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.trim().is_empty());
let mut p = source(name, bytes);
@@ -220,6 +221,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
if ui.add_enabled(!empty, egui::Button::new(tl!("Export Swatches for Exchange…"))).clicked() {
act = Some("ase");
}
+ if ui.add_enabled(!empty, egui::Button::new(tl!("Export Swatches as Color Table…"))).clicked() {
+ act = Some("act");
+ }
ui.separator();
if ui.button(tl!("Reset Swatches")).clicked() {
act = Some("reset");
@@ -237,7 +241,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
"import" => import_dialog(app, false),
"replace" => import_dialog(app, true),
- "aco" | "ase" => export_dialog(app, a),
+ "aco" | "ase" | "act" => export_dialog(app, a),
_ => app.run("swatches.reset", json!({})),
};
if let Err(e) = r