Merge pull request #10597 from yoriswind/codex/data-set-apply

Fix Apply in the Variables Data Sets dialog
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-11 00:22:29 -07:00
commit 197aa44fb0
2 files changed
+348 -17

No files matched your search

+58 -17
View File
@@ -51,6 +51,7 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<
"image.applyDataSet" if !has_params => {
// No data set named: open the dialog on the Data Sets page to pick one.
let mut f = Map::new();
f.insert("__command".into(), json!(id));
let state = app.session.active().map(|st| crate::variables_ui::to_state(&st.doc.variables)).unwrap_or_else(|| json!({"defs": [], "dataSets": []}));
f.insert("__variablesOrig".into(), state.clone());
f.insert("__variables".into(), state);
@@ -119,7 +120,7 @@ fn _a(a: &photocraft_doc::PixelAlign) -> &'static str {
const TYPES: &[(&str, &str)] = &[("visibility", "Visibility"), ("textReplacement", "Text Replacement"), ("pixelReplacement", "Pixel Replacement")];
const METHODS: &[(&str, &str)] = &[("fit", "Fit"), ("fill", "Fill"), ("conform", "Conform"), ("asIs", "As Is")];
/// Render the dialog. Mutates `fields["__variables"]` and `fields["__page"]`.
/// Render the dialog and apply a clicked data set using the edited working fields.
pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {
let t = Tokens::get(ui.ctx());
let layers = layer_options(app);
@@ -138,16 +139,33 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
});
ui.separator();
if layers.is_empty() {
let apply = if layers.is_empty() {
ui.weak(tl!("Open a document to define variables."));
false
} else if page == "define" {
define_page(ui, &t, &layers, &mut state);
false
} else {
data_sets_page(ui, &t, &mut state, fields);
}
data_sets_page(ui, &t, &mut state, fields)
};
fields.insert("__variables".into(), state);
fields.insert("__page".into(), json!(page));
if apply {
fields.remove("__appliedAt");
let result = confirm(app, fields);
fields.remove("__apply");
if result.is_ok()
&& fields.get("__command").and_then(Value::as_str) == Some("image.applyDataSet")
&& let Some(st) = app.session.active()
{
fields.insert("__variables".into(), to_state(&st.doc.variables));
fields.insert("__appliedAt".into(), json!([st.doc.id.0, st.revision]));
}
if let Err(error) = result {
app.ui.status = error;
}
}
}
/// The dialog state with only object entries in `defs`, `dataSets` and each set's `values`.
@@ -233,7 +251,8 @@ fn data_set_index(fields: &Map<String, Value>, len: usize) -> usize {
fields.get("__cur").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).filter(|&i| i < len).unwrap_or(0)
}
fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mut Map<String, Value>) {
/// Edit one data set and report whether its Apply button was clicked.
fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mut Map<String, Value>) -> bool {
let def_meta: Vec<(String, String)> = state
.get("defs")
.and_then(Value::as_array)
@@ -247,9 +266,9 @@ fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mu
.unwrap_or_default();
if def_meta.is_empty() {
ui.weak(tl!("Define at least one variable first."));
return;
return false;
}
let Some(sets) = state.get_mut("dataSets").and_then(Value::as_array_mut) else { return };
let Some(sets) = state.get_mut("dataSets").and_then(Value::as_array_mut) else { return false };
let mut cur = data_set_index(fields, sets.len());
ui.horizontal(|ui| {
@@ -287,6 +306,7 @@ fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mu
});
ui.separator();
let mut apply = false;
if let Some(set) = sets.get_mut(cur) {
// name
let mut sname = set.get("name").and_then(Value::as_str).unwrap_or("").to_string();
@@ -297,7 +317,7 @@ fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mu
}
});
ui.add_space(4.0);
let Some(values) = set.get_mut("values").and_then(Value::as_array_mut) else { return };
let Some(values) = set.get_mut("values").and_then(Value::as_array_mut) else { return false };
for (vname, vty) in &def_meta {
// find or create a value entry for this variable
let idx = values.iter().position(|v| v.get("variable").and_then(Value::as_str) == Some(vname));
@@ -339,24 +359,45 @@ fn data_sets_page(ui: &mut egui::Ui, _t: &Tokens, state: &mut Value, fields: &mu
}
ui.add_space(6.0);
if crate::widgets::secondary_button(ui, tl!("Apply"), 84.0).clicked() {
fields.insert("__apply".into(), json!(sname));
fields.insert("__apply".into(), json!(cur));
apply = true;
}
}
fields.insert("__cur".into(), json!(cur));
apply
}
/// OK: save the definitions and data sets, and apply one if the Apply button set `__apply`.
/// Save the edited definitions and data sets. Apply Data Set OK also applies the selected row.
pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Value, String> {
let state = fields.get("__variables").cloned().unwrap_or_else(|| json!({}));
let defs = state.get("defs").cloned().unwrap_or_else(|| json!([]));
let sets = state.get("dataSets").cloned().unwrap_or_else(|| json!([]));
// Only define when there is at least one named variable (empty define clears).
let empty = json!([]);
let state = fields.get("__variables").unwrap_or(&Value::Null);
let defs = state.get("defs").unwrap_or(&empty);
let sets = state.get("dataSets").unwrap_or(&empty);
let selected = if fields.get("__command").and_then(Value::as_str) == Some("image.applyDataSet") && !fields.contains_key("__apply") {
sets.as_array().filter(|rows| !rows.is_empty()).map(|rows| data_set_index(fields, rows.len()))
} else {
None
};
// An unchanged OK after Apply closes without another application or history entry.
if let Some(index) = selected
&& let Some(st) = app.session.active()
&& fields.get("__appliedAt") == Some(&json!([st.doc.id.0, st.revision]))
&& st.doc.variables.active == Some(index)
&& state == &to_state(&st.doc.variables)
{
return Ok(json!({"defined": true}));
}
app.run("image.variables.define", json!({"defs": defs}))?;
app.run("image.variables.dataSets", json!({"dataSets": sets}))?;
if let Some(name) = fields.get("__apply").and_then(Value::as_str) {
return app.run("image.applyDataSet", json!({"name": name}));
let request = match fields.get("__apply") {
Some(Value::String(name)) => Some(json!({"name": name})),
Some(value) => value.as_u64().map(|index| json!({"index": index})),
None => selected.map(|index| json!({"index": index})),
};
match request {
Some(params) => app.run("image.applyDataSet", params),
None => Ok(json!({"defined": true})),
}
Ok(json!({"defined": true}))
}
#[cfg(test)]
@@ -56,6 +56,296 @@ fn out_of_range_data_set_index_is_clamped_before_delete() {
h.run_steps(2);
}
/// A real image file and unsaved dialog edits exercise the same path as manual entry.
fn pixel_replacement_harness() -> (tempfile::TempDir, Harness<'static, PhotocraftApp>) {
let dir = tempfile::tempdir().unwrap();
for (name, color) in [("blue.png", "#0000ff"), ("red.png", "#ff0000")] {
let mut source = photocraft_engine::Session::new();
source.execute("file.new", json!({"width": 8, "height": 8, "background": color})).unwrap();
let png = photocraft_io::export(&source.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes;
std::fs::write(dir.path().join(name), png).unwrap();
}
let path = dir.path().join("blue.png");
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());
app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
let layer = app.session.active().unwrap().active_layer.unwrap();
photocraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "image.variables.dataSets", json!({})).unwrap();
let dialog = app.ui.dialogs.last_mut().unwrap();
dialog.fields.insert(
"__variables".into(),
json!({
"defs": [{"name": "photo", "layer": layer.0, "type": "pixelReplacement", "method": "conform"}],
"dataSets": [{"name": "Blue", "values": [{"variable": "photo", "kind": "pixels", "value": path}]}]
}),
);
(dir, harness(app))
}
fn save_draft_and_open_apply_menu(h: &mut Harness<'static, PhotocraftApp>) {
h.get_by_label("OK").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
let ctx = h.ctx.clone();
photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.applyDataSet", json!({})).unwrap();
h.run_steps(3);
}
fn read_pixel(h: &mut Harness<'static, PhotocraftApp>) -> serde_json::Value {
h.state_mut().run("document.pixel", json!({"x": 4, "y": 4})).unwrap()
}
/// CSV chosen through the import menu supplies the row that Apply renders and OK preserves.
#[test]
fn imported_csv_replaces_pixels_through_the_apply_dialog() {
use photocraft_ui_egui::file_dialog::{FileDialogAnswer, FileDialogRequest};
for contents in [false, true] {
let (dir, mut h) = pixel_replacement_harness();
h.get_by_label("OK").click();
h.run_steps(3);
h.state_mut().run("image.variables.dataSets", json!({"dataSets": []})).unwrap();
let csv = format!("DataSet,photo\nImported,\"{}\"\n", dir.path().join("blue.png").display());
let path = dir.path().join("sets.csv");
std::fs::write(&path, &csv).unwrap();
let answer = if contents {
FileDialogAnswer::Contents("sets.csv".into(), csv.into_bytes())
} else {
FileDialogAnswer::Paths(vec![path.to_string_lossy().into_owned()])
};
h.state_mut().services.file_dialog = Some(Box::new(move |request, _, reply| {
assert!(matches!(request, FileDialogRequest::Open { multiple: false, .. }));
reply.send(Some(answer.clone()));
}));
let ctx = h.ctx.clone();
photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.import.variableDataSets", json!({})).unwrap();
h.state_mut().poll_file_dialog(&ctx, None);
assert!(!h.state().file_dialog_open());
let rows = &h.state().session.active().unwrap().doc.variables.data_sets;
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].name, "Imported");
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]), "import alone does not apply a row");
photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "image.applyDataSet", json!({})).unwrap();
h.run_steps(3);
h.get_by_label("Apply").click();
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]));
assert_eq!(h.state().ui.dialogs.len(), 1);
let revision = h.state().session.active().unwrap().revision;
h.get_by_label("OK").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert_eq!(h.state().session.active().unwrap().revision, revision);
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
}
#[test]
fn apply_menu_ok_requires_a_row_but_not_variable_definitions() {
for (rows, explicit, expected) in [(json!([]), false, None), (json!([{"name": "Empty", "values": []}]), false, Some(0)), (json!([]), true, None)] {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());
app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
app.run("image.variables.dataSets", json!({"dataSets": rows})).unwrap();
photocraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "image.applyDataSet", json!({})).unwrap();
if explicit {
app.ui.dialogs.last_mut().unwrap().fields.insert("__apply".into(), json!(0));
}
let mut h = harness(app);
h.state_mut().ui.status.clear();
h.get_by_label("OK").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert_eq!(h.state().session.active().unwrap().doc.variables.active, expected);
if explicit {
assert!(h.state().ui.status.contains("no data set at index 0"));
} else {
assert!(h.state().ui.status.is_empty(), "{}", h.state().ui.status);
}
}
}
/// Apply updates the canvas immediately; OK must not apply the same request again.
#[test]
fn apply_replaces_pixels_before_ok_and_keeps_the_dialog_open() {
let (_dir, mut h) = pixel_replacement_harness();
let id = h.state().ui.dialogs.last().unwrap().id;
h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("__apply".into(), json!("Blue"));
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]), "editing fields alone is not Apply");
h.get_by_label("Apply").click();
h.run_steps(3);
assert_eq!(h.state().ui.dialogs.last().unwrap().id, id, "Apply leaves the editor open");
assert!(!h.state().ui.dialogs.last().unwrap().fields.contains_key("__apply"));
let pixel = read_pixel(&mut h);
h.get_by_label("OK").click();
h.run_steps(3);
let confirmed = read_pixel(&mut h);
assert_eq!(confirmed, json!([0.0, 0.0, 1.0, 1.0]), "the same replacement works through OK");
assert_eq!(pixel, confirmed, "Apply uses the edited definitions and image path immediately");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
/// Duplicate labels must not change which row Apply or OK sends to the engine.
#[test]
fn duplicate_names_apply_the_selected_row_for_apply_and_ok() {
for button in ["Apply", "OK"] {
let (_dir, mut h) = pixel_replacement_harness();
let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields;
let selected = fields["__variables"]["dataSets"][0].clone();
fields["__variables"]["dataSets"] = json!([{"name": "Blue", "values": []}, selected]);
save_draft_and_open_apply_menu(&mut h);
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]), "editing data sets only saves them");
h.get_by_label("▶").click();
h.run_steps(2);
let fields = &h.state().ui.dialogs.last().unwrap().fields;
assert_eq!(fields["__cur"], 1);
assert!(!fields.contains_key("__apply"));
h.get_by_label(button).click();
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]), "{button}");
assert_eq!(h.state().session.active().unwrap().doc.variables.active, Some(1), "{button}");
}
}
#[test]
fn apply_menu_apply_then_ok_keeps_one_history_entry() {
let (_dir, mut h) = pixel_replacement_harness();
save_draft_and_open_apply_menu(&mut h);
h.get_by_label("Apply").click();
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]));
let revision = h.state().session.active().unwrap().revision;
h.get_by_label("OK").click();
h.run_steps(3);
assert_eq!(h.state().session.active().unwrap().revision, revision);
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
#[test]
fn apply_menu_ok_honors_changes_after_apply() {
for change in ["row", "value", "document"] {
let (dir, mut h) = pixel_replacement_harness();
let red = json!(dir.path().join("red.png"));
if change == "row" {
let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields;
let mut row = fields["__variables"]["dataSets"][0].clone();
row["values"][0]["value"] = red.clone();
fields["__variables"]["dataSets"].as_array_mut().unwrap().push(row);
}
save_draft_and_open_apply_menu(&mut h);
h.get_by_label("Apply").click();
h.run_steps(3);
if change == "row" {
h.get_by_label("▶").click();
} else if change == "value" {
h.state_mut().ui.dialogs.last_mut().unwrap().fields["__variables"]["dataSets"][0]["values"][0]["value"] = red;
} else {
h.state_mut().run("image.adjustments.invert", json!({})).unwrap();
}
h.run_steps(3);
let before = if change == "document" { json!([1.0, 1.0, 0.0, 1.0]) } else { json!([0.0, 0.0, 1.0, 1.0]) };
assert_eq!(read_pixel(&mut h), before, "{change}: only document edits change pixels before OK");
h.get_by_label("OK").click();
h.run_steps(3);
let after = if change == "document" { json!([0.0, 0.0, 1.0, 1.0]) } else { json!([1.0, 0.0, 0.0, 1.0]) };
assert_eq!(read_pixel(&mut h), after, "{change}");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(read_pixel(&mut h), before);
}
}
#[test]
fn apply_menu_cancel_does_not_apply_the_selected_row() {
let (_dir, mut h) = pixel_replacement_harness();
save_draft_and_open_apply_menu(&mut h);
h.get_by_label("Cancel").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
#[test]
fn apply_menu_ok_after_deleting_the_last_row_only_saves() {
let (_dir, mut h) = pixel_replacement_harness();
save_draft_and_open_apply_menu(&mut h);
h.get_by_label("Delete").click();
h.run_steps(2);
h.state_mut().ui.status.clear();
h.get_by_label("OK").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert!(h.state().ui.status.is_empty(), "{}", h.state().ui.status);
assert!(h.state().session.active().unwrap().doc.variables.data_sets.is_empty());
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
#[test]
fn legacy_named_request_stays_draft_until_ok() {
let (_dir, mut h) = pixel_replacement_harness();
h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("__apply".into(), json!("Blue"));
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
h.get_by_label("OK").click();
h.run_steps(3);
assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]));
}
#[test]
fn variables_editor_ok_only_saves_configuration() {
for menu in ["image.variables.define", "image.variables.dataSets"] {
let (_dir, mut h) = pixel_replacement_harness();
let state = h.state().ui.dialogs.last().unwrap().fields["__variables"].clone();
h.get_by_label("Cancel").click();
h.run_steps(3);
let ctx = h.ctx.clone();
photocraft_ui_egui::menus::invoke(h.state_mut(), &ctx, menu, json!({})).unwrap();
h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("__variables".into(), state);
h.run_steps(3);
h.get_by_label("OK").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert_eq!(h.state().session.active().unwrap().doc.variables.data_sets.len(), 1, "{menu}");
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]), "{menu}");
}
}
/// A failed request reports once; correcting it can be applied and kept when Cancel closes.
#[test]
fn failed_apply_can_be_corrected_without_retries_or_cancel_rollback() {
for apply_mode in [false, true] {
let (dir, mut h) = pixel_replacement_harness();
if apply_mode {
save_draft_and_open_apply_menu(&mut h);
}
let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields;
fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("missing.png"));
h.get_by_label("Apply").click();
h.run_steps(3);
assert!(h.state().ui.status.contains("missing.png"), "{}", h.state().ui.status);
assert!(!h.state().ui.dialogs.last().unwrap().fields.contains_key("__apply"));
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
h.state_mut().ui.status.clear();
h.run_steps(3);
assert!(h.state().ui.status.is_empty(), "a failed Apply must not retry each frame");
let fields = &mut h.state_mut().ui.dialogs.last_mut().unwrap().fields;
fields["__variables"]["dataSets"][0]["values"][0]["value"] = json!(dir.path().join("blue.png"));
h.get_by_label("Apply").click();
h.run_steps(3);
h.get_by_label("Cancel").click();
h.run_steps(3);
assert!(h.state().ui.dialogs.is_empty());
assert_eq!(read_pixel(&mut h), json!([0.0, 0.0, 1.0, 1.0]));
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
}
}
/// `ui.dialog.set` can store any JSON in `__variables`; the editors write into its entries.
fn app_with_malformed_variables(page: &str) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default());