PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Integration: Color Table presets after Load, .act by file name (#5407)
David Mann567a34229657
diff --git a/crates/ui-egui/src/color_table_ui.rs b/crates/ui-egui/src/color_table_ui.rsindex 0e6000794..8903a0621 100644--- a/crates/ui-egui/src/color_table_ui.rs+++ b/crates/ui-egui/src/color_table_ui.rs@@ -2,8 +2,9 @@//!//! 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+//! pending table — the loaded colors while the Table menu is on Custom, else its preset, else+//! the document's table — to a picked `.act`. Picking a preset after Load… drops the loaded+//! colors. Parsing lives in the engine (`swatch_cmds`); this module only draws and//! dispatches.use serde_json::{Map, Value, json};@@ -19,9 +20,25 @@ fn unhex(s: &str) -> Option<[u8; 3]> {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.+/// Whether the Table menu is on Custom (or unset), the only state where loaded colors apply.+fn custom(fields: &Map<String, Value>) -> bool {+ fields.get("table").and_then(Value::as_str).is_none_or(|t| t == "custom")+}++/// A preset picked after Load… replaces the loaded table: forget its colors and transparent entry.+fn drop_loaded_unless_custom(fields: &mut Map<String, Value>) {+ if !custom(fields) {+ fields.remove("colors");+ fields.remove("transparent");+ }+}++/// The pending table: the dialog's loaded colors (while the Table menu is on Custom), 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) {+ if custom(fields)+ && 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());@@ -38,7 +55,11 @@ fn pending(app: &PhotocraftApp, fields: &Map<String, Value>) -> Option<(Vec<[u8;/// 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>) {+pub fn buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: u64, fields: &mut Map<String, Value>) {+ // `fields` is the frame's copy that the dialog writes back and OK sends: drop the loaded+ // table there once a preset is picked, so OK applies what the Table menu shows.+ drop_loaded_unless_custom(fields);+ let fields = &*fields;ui.horizontal(|ui| {if ui.button(tl!("Load…")).clicked()&& let Err(e) = app.pick_file_bytes_filtered(&["act"], move |app, name, bytes| {@@ -107,13 +128,14 @@ mod tests {#[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))));+ // Loaded colors win while the Table menu is on Custom, with their transparent entry.+ let loaded = |table: &str| {+ Map::from_iter([("table".to_string(), json!(table)), ("colors".to_string(), json!(["#ff0000", "#00ff00"])), ("transparent".to_string(), json!(1))])+ };+ assert_eq!(pending(&app, &loaded("custom")), Some((vec![[255, 0, 0], [0, 255, 0]], Some(1))));+ // A preset picked after Load… is what Save… writes, not the loaded colors.+ let (colors, transparent) = pending(&app, &loaded("blackBody")).unwrap();+ assert_eq!((colors.len(), transparent), (256, None));// Else the preset (256 entries, no transparency).let fields = Map::from_iter([("table".to_string(), json!("blackBody"))]);let (colors, transparent) = pending(&app, &fields).unwrap();@@ -123,6 +145,27 @@ mod tests {assert_eq!(pending(&app, &Map::from_iter([("table".to_string(), json!("custom"))])), None);}+ /// What OK sends is the dialog's fields: after a preset is picked they hold no loaded colors+ /// (which `image.mode.colorTable` would apply over the preset), and Custom keeps them.+ #[test]+ fn a_preset_picked_after_load_drops_the_loaded_colors() {+ let loaded = |table: &str| {+ Map::from_iter([+ ("__command".to_string(), json!("image.mode.colorTable")),+ ("table".to_string(), json!(table)),+ ("colors".to_string(), json!(["#ff0000"])),+ ("transparent".to_string(), json!(0)),+ ])+ };+ let mut fields = loaded("grayscale");+ drop_loaded_unless_custom(&mut fields);+ assert!(!fields.contains_key("colors") && !fields.contains_key("transparent"), "{fields:?}");+ assert_eq!(fields.get("table"), Some(&json!("grayscale")));+ let mut fields = loaded("custom");+ drop_loaded_unless_custom(&mut fields);+ assert_eq!(fields, loaded("custom"));+ }+#[test]fn loaded_act_bytes_fill_the_dialog_fields() {let table: Vec<[u8; 3]> = (0..256).map(|i| [i as u8, 0, 255]).collect();diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 3e55e82ae..8a9a20ec1 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -391,7 +391,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {} 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);+ crate::color_table_ui::buttons(app, ui, d.id, &mut fields);}ui.add_space(8.0);// Align::Min, not Center: a centred row fills the height left over from last frame'sdiff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 7d6786ed3..5ecadb323 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -3858,6 +3858,5 @@ navigator Zoom ZvětšeníGenerate Mipmaps Generovat mipmapy# Color Table (.act) dialog- Export Swatches as Color Table… Exportovat vzorníky jako tabulku barev…There is no color table to save. Neexistuje žádná tabulka barev k uložení.@plural Saved {n} color to {file}|Saved {n} colors to {file} Uložena {n} barva do {file}|Uloženy {n} barvy do {file}|Uloženo {n} barev do {file}diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 2e79adb6c..6fc367621 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -3252,6 +3252,5 @@ curves Smooth GlättenGenerate Mipmaps Mipmaps erzeugen# Color Table (.act) dialog- Export Swatches as Color Table… Farbfelder als Farbtabelle exportieren…There is no color table to save. Es gibt keine Farbtabelle zum Speichern.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} Farbe in {file} gespeichert|{n} Farben in {file} gespeichertdiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex d72c3842c..22d58807b 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3950,6 +3950,5 @@ curves Smooth ΕξομάλυνσηGenerate Mipmaps Δημιουργία mipmap# Color Table (.act) dialog- Export Swatches as Color Table… Εξαγωγή δειγμάτων ως πίνακα χρωμάτων…There is no color table to save. Δεν υπάρχει πίνακας χρωμάτων για αποθήκευση.@plural Saved {n} color to {file}|Saved {n} colors to {file} Αποθηκεύτηκε {n} χρώμα στο {file}|Αποθηκεύτηκαν {n} χρώματα στο {file}diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex e241f4002..ee60eb6ab 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -4212,6 +4212,5 @@ navigator Zoom ZoomGenerate Mipmaps Generar mipmaps# Color Table (.act) dialog- Export Swatches as Color Table… Exportar muestras como tabla de colores…There is no color table to save. No hay ninguna tabla de colores para guardar.@plural Saved {n} color to {file}|Saved {n} colors to {file} Se guardó {n} color en {file}|Se guardaron {n} colores en {file}diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex d685acda5..65748f01f 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -3259,6 +3259,5 @@ curves Smooth LisserGenerate Mipmaps Générer les mipmaps# Color Table (.act) dialog- Export Swatches as Color Table… Exporter les nuances comme table de couleurs…There is no color table to save. Il n’y a aucune table de couleurs à enregistrer.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} couleur enregistrée dans {file}|{n} couleurs enregistrées dans {file}diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex 9484005b7..3f9edf373 100644--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@ -4169,6 +4169,5 @@ cameraRaw Yellow SárgaGenerate Mipmaps Mipmapek létrehozása# Color Table (.act) dialog- Export Swatches as Color Table… Színtárak exportálása színtáblaként…There is no color table to save. Nincs menthető színtábla.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} szín mentve ide: {file}diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex b23dcd171..312d77e90 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -3246,6 +3246,5 @@ curves Smooth HaluskanGenerate Mipmaps Buat mipmap# Color Table (.act) dialog- Export Swatches as Color Table… Ekspor swatch sebagai Tabel Warna…There is no color table to save. Tidak ada tabel warna untuk disimpan.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} warna disimpan ke {file}diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex 11c9480b5..cc12fe0ca 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -4367,6 +4367,5 @@ shape Appearance AspettoGenerate Mipmaps Genera mipmap# Color Table (.act) dialog- Export Swatches as Color Table… Esporta campioni come tabella colori…There is no color table to save. Non c'è alcuna tabella colori da salvare.@plural Saved {n} color to {file}|Saved {n} colors to {file} Salvato {n} colore in {file}|Salvati {n} colori in {file}diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex b4795b615..0a62bdf76 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3928,6 +3928,5 @@ curves Smooth スムーズGenerate Mipmaps ミップマップを生成# Color Table (.act) dialog- Export Swatches as Color Table… スウォッチをカラーテーブルとして書き出し…There is no color table to save. 保存するカラーテーブルがありません。@plural Saved {n} color to {file}|Saved {n} colors to {file} {file} に {n} 色を保存しましたdiff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 0bf5bce5c..cb8435f38 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3433,6 +3433,5 @@ curves Smooth 매끄럽게Generate Mipmaps 밉맵 생성# Color Table (.act) dialog- Export Swatches as Color Table… 색상표로 견본 내보내기…There is no color table to save. 저장할 색상표가 없습니다.@plural Saved {n} color to {file}|Saved {n} colors to {file} {file}에 색상 {n}개 저장diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex a15ff8991..4b0693d4e 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -4010,6 +4010,5 @@ curves Smooth Vloeiend makenGenerate Mipmaps Mipmaps genereren# Color Table (.act) dialog- Export Swatches as Color Table… Stalen exporteren als kleurtabel…There is no color table to save. Er is geen kleurtabel om op te slaan.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} kleur opgeslagen in {file}|{n} kleuren opgeslagen in {file}diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 37c32b8be..788ca315d 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3850,6 +3850,5 @@ curves Smooth WygładźGenerate Mipmaps Generuj mipmapy# Color Table (.act) dialog- Export Swatches as Color Table… Eksportuj próbki jako tabelę kolorów…There is no color table to save. Brak tabeli kolorów do zapisania.@plural Saved {n} color to {file}|Saved {n} colors to {file} Zapisano {n} kolor do {file}|Zapisano {n} kolory do {file}|Zapisano {n} kolorów do {file}diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 59928c07b..1853e22d2 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -4040,6 +4040,5 @@ layerLabel No Color Sem corGenerate Mipmaps Gerar mipmaps# Color Table (.act) dialog- Export Swatches as Color Table… Exportar amostras como tabela de cores…There is no color table to save. Não há tabela de cores para salvar.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} cor salva em {file}|{n} cores salvas em {file}diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 30fda073f..2034930ee 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -3225,6 +3225,5 @@ curves Smooth СгладитьGenerate Mipmaps Создать MIP-карты# Color Table (.act) dialog- Export Swatches as Color Table… Экспортировать образцы как таблицу цветов…There is no color table to save. Нет таблицы цветов для сохранения.@plural Saved {n} color to {file}|Saved {n} colors to {file} Сохранён {n} цвет в {file}|Сохранены {n} цвета в {file}|Сохранено {n} цветов в {file}diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsvindex 846458fed..69bdcc5be 100644--- a/crates/ui-egui/src/i18n/sr.tsv+++ b/crates/ui-egui/src/i18n/sr.tsv@@ -4323,6 +4323,5 @@ shape Appearance IzgledGenerate Mipmaps Generiši mipmape# Color Table (.act) dialog- Export Swatches as Color Table… Извези узорке као табелу боја…There is no color table to save. Нема табеле боја за чување.@plural Saved {n} color to {file}|Saved {n} colors to {file} Сачувана је {n} боја у {file}|Сачуване су {n} боје у {file}|Сачувано је {n} боја у {file}diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex 6be20e109..dee83f9bb 100644--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@ -3980,6 +3980,5 @@ cameraData Lens LensGenerate Mipmaps Mipmap oluştur# Color Table (.act) dialog- Export Swatches as Color Table… Renk örneklerini Renk Tablosu olarak dışa aktar…There is no color table to save. Kaydedilecek renk tablosu yok.@plural Saved {n} color to {file}|Saved {n} colors to {file} {n} renk {file} konumuna kaydedildidiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 5163ed5dc..330f37773 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3959,6 +3959,5 @@ curves Smooth ЗгладитиGenerate Mipmaps Створити MIP-карти# Color Table (.act) dialog- Export Swatches as Color Table… Експортувати зразки як таблицю кольорів…There is no color table to save. Немає таблиці кольорів для збереження.@plural Saved {n} color to {file}|Saved {n} colors to {file} Збережено {n} колір у {file}|Збережено {n} кольори у {file}|Збережено {n} кольорів у {file}diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsvindex 7f9e495b4..c9a1051f7 100644--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@ -3738,6 +3738,5 @@ curves Smooth Làm mượtGenerate Mipmaps Tạo mipmap# Color Table (.act) dialog- Export Swatches as Color Table… Xuất mẫu màu thành Bảng màu…There is no color table to save. Không có bảng màu nào để lưu.@plural Saved {n} color to {file}|Saved {n} colors to {file} Đã lưu {n} màu vào {file}diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 77f4b9027..d988ab80b 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2875,6 +2875,5 @@ curves Smooth 平滑Generate Mipmaps 生成 Mipmap# Color Table (.act) dialog- Export Swatches as Color Table… 将色板导出为色表…There is no color table to save. 没有可保存的色表。@plural Saved {n} color to {file}|Saved {n} colors to {file} 已将 {n} 种颜色保存到 {file}diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex e913f57c6..2ee91856f 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2860,6 +2860,5 @@ curves Smooth 平滑Generate Mipmaps 產生 Mipmap# Color Table (.act) dialog- Export Swatches as Color Table… 將色票匯出為色表…There is no color table to save. 沒有可儲存的色表。@plural Saved {n} color to {file}|Saved {n} colors to {file} 已將 {n} 種顏色儲存至 {file}diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/swatches_ui.rsindex 6cf6d835b..c0bf9b3b0 100644--- a/crates/ui-egui/src/swatches_ui.rs+++ b/crates/ui-egui/src/swatches_ui.rs@@ -5,8 +5,7 @@//! 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`,-//! `.act`, `.ase`), Export (`.aco`), Export as Color Table (`.act`) and Export for Exchange-//! (`.ase`) and Reset. Every action is a+//! `.act`, `.ase`), Export (`.aco`) 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).@@ -154,6 +153,11 @@ pub fn import_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8], replace: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);p["mode"] = json!(if replace { "replace" } else { "append" });+ // Bytes without a path (the browser, drag and drop) are sniffed by content, and `.act` has+ // no signature: one starting 00 01 or 00 02 reads as `.aco`. Its file name decides.+ if std::path::Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("act")) {+ p["format"] = json!("act");+ }if let Some(stem) = stem {p["group"] = json!(stem);}@@ -220,9 +224,6 @@ 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");@@ -240,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" | "act" => export_dialog(app, a),+ "aco" | "ase" => export_dialog(app, a),_ => app.run("swatches.reset", json!({})),};if let Err(e) = r@@ -277,6 +278,18 @@ mod tests {use egui::{Modifiers, vec2};use egui_kittest::Harness;+ /// Bytes without a path (the browser) go by the file name: an `.act` whose first color is+ /// 00 01 xx looks like an `.aco` header by content.+ #[test]+ fn an_act_from_bytes_imports_by_its_file_name() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let mut colors = vec![[10u8, 20, 30]; 256];+ colors[0] = [0, 1, 5];+ let bytes = photocraft_psd::act::write(&colors, None, None).unwrap();+ let r = import_bytes(&mut app, "Palette.act", &bytes, true).unwrap();+ assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("act"), Some(256)));+ }+fn click(h: &mut Harness<'_, PhotocraftApp>, p: egui::Pos2, modifiers: Modifiers) {h.hover_at(p);// Held modifiers, as when the user holds Alt while clicking.