Merge pull request #19155

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
This commit is contained in:
davidmann4andautocraft-bot[bot] authored and autocraft-bot[bot] committed 2026-12-02 22:19:56 +00:00
commit e037f5be59
2 files changed
+308

No files matched your search

@@ -0,0 +1,239 @@
//! #14258: dialog-only option defaults, per-document greying and retained underlying memory.
use super::*;
use craft::ui::runtime::memory::{SaveKey, set_saved_value};
use egui::accesskit::{Role, Toggled};
use egui_kittest::{
Harness,
kittest::{NodeT, Queryable},
};
use photocraft_engine::prefs::SavedPrefsExt;
type H = Harness<'static, Box<PhotocraftApp>>;
fn harness() -> H {
let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
let h = Harness::builder()
.with_size(egui::vec2(1200.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
fn document(h: &mut H, mode: &str, depth: u32, layers: usize) {
h.state_mut().run("file.new", json!({"width": 4, "height": 4, "depth": depth, "background": "#c81e1e"})).unwrap();
if mode == "duotone" {
h.state_mut().run("image.mode.grayscale", json!({})).unwrap();
}
if mode != "rgb" {
h.state_mut().run(&format!("image.mode.{mode}"), json!({})).unwrap();
}
for _ in 1..layers {
h.state_mut().run("layer.new.layer", json!({})).unwrap();
}
h.state_mut().sync_views();
}
fn open(h: &mut H) -> DialogId {
let id = super::open(h.state_mut(), CONVERT_PROFILE).unwrap();
h.run_steps(4);
id
}
fn raw(h: &H, id: DialogId, key: &str) -> Option<bool> {
h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().bool(key)
}
fn sent(h: &H, id: DialogId) -> Value {
command_params(CONVERT_PROFILE, h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields())
}
fn checkbox(h: &H, name: &str) -> (bool, bool) {
let control = h.get_by_role_and_label(Role::CheckBox, name);
let node = control.accesskit_node();
(!node.is_disabled(), node.toggled() == Some(Toggled::True))
}
fn set(h: &mut H, id: DialogId, key: &str, value: Value) {
let ctx = h.ctx.clone();
h.state_mut().framework.dialogs.set_json_field(&ctx, id, key, value).unwrap();
h.run_steps(2);
}
fn close(h: &mut H, id: DialogId, confirm: bool) {
let ctx = h.ctx.clone();
if confirm {
crate::dialogs::confirm(h.state_mut(), &ctx, id).unwrap();
} else {
crate::dialogs::cancel(h.state_mut(), &ctx, id).unwrap();
}
h.run_steps(4);
}
fn saved(h: &H, dither: bool, flatten: bool) {
let mut fields = DialogFields::new();
fields.set("dither", dither);
fields.set("flatten", flatten);
set_saved_value::<Option<DialogFields>>(&h.ctx, &SaveKey::named(crate::dialogs::params::memory_scope(CONVERT_PROFILE)), Some(fields));
}
#[test]
fn fresh_dither_is_on_with_the_measured_depth_and_mode_enabled_states() {
for (mode, depth, enabled) in [("rgb", 8, true), ("rgb", 16, false), ("rgb", 32, false), ("cmyk", 8, true), ("lab", 16, false), ("indexedColor", 8, false)]
{
let mut h = harness();
document(&mut h, mode, depth, 1);
let id = open(&mut h);
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap();
assert_eq!(form.fields().get(CONVERT_DITHER_ENABLED), Some(&FieldValue::Bool(enabled)), "typed enable flag for {mode} {depth}");
assert_eq!(form.fields().get(CONVERT_FLATTEN_ENABLED), Some(&FieldValue::Bool(false)));
assert_eq!(checkbox(&h, "Dither"), (enabled, true), "{mode} {depth}");
assert_eq!(checkbox(&h, "Flatten"), (false, false));
assert_eq!(sent(&h, id)["flatten"], false);
close(&mut h, id, false);
}
}
#[test]
fn greyed_flatten_shows_false_and_sends_false_while_keeping_its_raw_remembered_value() {
for (mode, depth) in [("rgb", 8), ("rgb", 32), ("indexedColor", 8)] {
let mut h = harness();
saved(&h, false, true);
document(&mut h, mode, depth, 1);
let id = open(&mut h);
assert_eq!(raw(&h, id, "flatten"), Some(true));
assert_eq!(checkbox(&h, "Flatten"), (false, false));
assert_eq!(sent(&h, id)["flatten"], false);
assert_eq!(raw(&h, id, "dither"), Some(false));
close(&mut h, id, false);
}
}
#[test]
fn a_disabled_ok_does_not_replace_the_options_seen_on_a_later_layered_eight_bit_document() {
let mut h = harness();
saved(&h, false, true);
document(&mut h, "rgb", 16, 1);
let id = open(&mut h);
assert_eq!(checkbox(&h, "Dither"), (false, false));
assert_eq!(checkbox(&h, "Flatten"), (false, false));
set(&mut h, id, "profile", json!("adobe-rgb-compat"));
close(&mut h, id, true);
document(&mut h, "rgb", 8, 2);
let id = open(&mut h);
assert_eq!(checkbox(&h, "Dither"), (true, false));
assert_eq!(checkbox(&h, "Flatten"), (true, true));
assert_eq!(sent(&h, id)["flatten"], true);
close(&mut h, id, false);
}
#[test]
fn layered_documents_keep_the_unmeasured_fresh_flatten_default_and_accept_both_choices() {
let mut h = harness();
document(&mut h, "rgb", 8, 2);
let id = open(&mut h);
assert_eq!(checkbox(&h, "Flatten"), (true, false));
set(&mut h, id, "flatten", json!(true));
set(&mut h, id, "dither", json!(false));
assert_eq!(sent(&h, id)["flatten"], true);
assert_eq!(sent(&h, id)["dither"], false);
close(&mut h, id, false);
}
#[test]
fn grayscale_duotone_and_multichannel_keep_their_previous_defaults_and_enabled_states() {
for (mode, depth) in [("grayscale", 16), ("duotone", 8), ("multichannel", 32)] {
let mut h = harness();
document(&mut h, mode, depth, 1);
let id = open(&mut h);
assert_eq!(checkbox(&h, "Dither"), (true, false), "{mode}");
assert_eq!(checkbox(&h, "Flatten"), (true, false), "{mode}");
close(&mut h, id, false);
}
}
#[test]
fn masking_is_limited_to_the_disabled_convert_form_and_command_defaults_are_unchanged() {
let spec = photocraft_engine::commands::find(CONVERT_PROFILE).unwrap();
assert!(Param::parse_list(spec.params).iter().any(|p| p.key == "dither" && matches!(p.kind, ParamKind::Bool { default: false, .. })));
let mut fields = DialogFields::new();
fields.set("flatten", true);
assert_eq!(command_params(CONVERT_PROFILE, &fields)["flatten"], true, "no form state means no override");
fields.set(CONVERT_FLATTEN_ENABLED, false);
assert_eq!(command_params(CONVERT_PROFILE, &fields)["flatten"], false);
assert_eq!(command_params("other.command", &fields)["flatten"], true);
}
#[test]
fn the_commit_memory_integration_preserves_presence_and_other_options_before_settings_are_saved() {
for before in [None, Some(json!(false)), Some(json!(true))] {
let mut h = harness();
document(&mut h, "rgb", 8, 1);
// #19141 writes the effective false after conversion. Only that suppressed UI choice is restored.
h.state_mut().session.edit_prefs(|prefs| {
prefs.dialogs.insert(CONVERT_PROFILE.into(), json!({"flatten": false, "intent": "saturation", "destinations": {"Rgb": "working-cmyk"}}));
});
restore_convert_flatten_memory(h.state_mut(), before.clone());
let stored = &h.state().session.prefs().dialogs[CONVERT_PROFILE];
assert_eq!(stored.get("flatten"), before.as_ref());
assert_eq!(stored["intent"], "saturation");
assert_eq!(stored["destinations"]["Rgb"], "working-cmyk");
let persisted: Value = serde_json::from_str(&h.state().session.prefs_to_json()).unwrap();
assert_eq!(persisted["dialogs"][CONVERT_PROFILE].get("flatten"), before.as_ref());
}
let mut h = harness();
restore_convert_flatten_memory(h.state_mut(), Some(json!(true)));
assert!(!h.state().session.prefs().dialogs.contains_key(CONVERT_PROFILE), "do not create a memory object on this branch's main");
}
#[test]
fn one_layer_ok_keeps_a_previously_saved_true_in_the_engine_memory_object() {
let mut h = harness();
document(&mut h, "rgb", 8, 1);
saved(&h, false, true);
h.state_mut().session.edit_prefs(|prefs| {
prefs.dialogs.insert(CONVERT_PROFILE.into(), json!({"flatten": true, "intent": "saturation"}));
});
let id = open(&mut h);
assert_eq!(checkbox(&h, "Flatten"), (false, false));
assert_eq!(raw(&h, id, "flatten"), Some(true));
assert_eq!(sent(&h, id)["flatten"], false);
set(&mut h, id, "profile", json!("adobe-rgb-compat"));
close(&mut h, id, true);
assert_eq!(h.state().session.prefs().dialogs[CONVERT_PROFILE]["flatten"], true);
}
#[test]
fn refused_and_same_profile_noop_conversions_leave_engine_memory_and_document_history_unchanged() {
fn refuse(_: &str, _: &Value) -> photocraft_engine::Result<()> {
Err(photocraft_engine::EngineError::Other("conversion refused for test".into()))
}
for refused in [false, true] {
let mut h = harness();
document(&mut h, "rgb", 8, 1);
h.state_mut().run("edit.assignProfile", json!({"profile": "srgb"})).unwrap();
saved(&h, false, true);
let memory = json!({"flatten": true, "intent": "saturation"});
h.state_mut().session.edit_prefs(|prefs| {
prefs.dialogs.insert(CONVERT_PROFILE.into(), memory.clone());
});
let history = h.state().session.active().unwrap().history.past_len();
let id = open(&mut h);
set(&mut h, id, "profile", json!("srgb"));
if refused {
h.state_mut().session.authorize = Some(refuse);
}
let ctx = h.ctx.clone();
let result = crate::dialogs::confirm(h.state_mut(), &ctx, id);
if refused {
assert!(result.is_err() || h.state().ui.status_error);
} else {
result.unwrap();
}
h.state_mut().session.authorize = None;
h.run_steps(4);
assert_eq!(h.state().session.prefs().dialogs[CONVERT_PROFILE], memory);
assert_eq!(h.state().session.active().unwrap().history.past_len(), history);
}
}
@@ -33,6 +33,9 @@ pub(crate) use rows::{REPLACE_COLOR, replace_color_sample};
const MATCH_COLOR: &str = "image.adjustments.matchColor";
const SCALE_EFFECTS: &str = "layer.layerStyle.scaleEffects";
const CONVERT_PROFILE: &str = "edit.convertToProfile";
const CONVERT_DITHER_ENABLED: &str = "__convertDitherEnabled";
const CONVERT_FLATTEN_ENABLED: &str = "__convertFlattenEnabled";
#[cfg(test)]
pub(crate) const MATCH_COLOR_DESTINATION: &str = "__matchColorDestination";
/// The key of the document id Lens Blur captures at open (see [`validate_lens_blur_document`]).
@@ -394,6 +397,18 @@ pub(crate) fn params(app: &mut PhotocraftApp, command: &str, spec: &str) -> Vec<
list.insert(0, custom_shape_preview_row(app, None));
}
rows::custom_rows(app, command, &mut list);
if command == CONVERT_PROFILE && convert_profile_option_state(app).is_some() {
for param in &mut list {
if param.key == "dither" {
if let ParamKind::Bool { default, .. } = &mut param.kind {
*default = true;
}
*param = param.clone().enabled_when(CONVERT_DITHER_ENABLED, true);
} else if param.key == "flatten" {
*param = param.clone().enabled_when(CONVERT_FLATTEN_ENABLED, true).disabled_value(false);
}
}
}
if command == color_settings_presets::COMMAND {
// The Settings menu: Custom, a greyed group label and the named setups in groups (#14229).
if let Some(p) = list.iter_mut().find(|p| p.key == "preset") {
@@ -480,6 +495,13 @@ fn scale_effects_row(p: Param) -> Param {
pub(crate) fn fields(app: &PhotocraftApp, command: &str, params: &[Param]) -> DialogFields {
let mut fields = DialogFields::new();
overlay(params, &command_defaults(app, command, params), &mut fields);
if command == CONVERT_PROFILE
&& let Some((dither, flatten)) = convert_profile_option_state(app)
{
// Enable conditions compare FieldValue variants, not their JSON equivalents.
fields.set(CONVERT_DITHER_ENABLED, FieldValue::Bool(dither));
fields.set(CONVERT_FLATTEN_ENABLED, FieldValue::Bool(flatten));
}
// Replace Color starts from the foreground colour.
if command == rows::REPLACE_COLOR {
let fg = app.session.tools.foreground;
@@ -542,6 +564,18 @@ fn command_defaults(app: &PhotocraftApp, command: &str, params: &[Param]) -> Map
map
}
/// Only the measured source modes get new UI defaults/greying. A group is not a flat layer.
fn convert_profile_option_state(app: &PhotocraftApp) -> Option<(bool, bool)> {
use photocraft_color::{ColorMode, SampleType};
let doc = &app.session.active()?.doc;
if !matches!(doc.mode, ColorMode::Rgb | ColorMode::Cmyk | ColorMode::Lab | ColorMode::Indexed) {
return None;
}
let dither = doc.depth == SampleType::U8 && doc.mode != ColorMode::Indexed;
let flat = doc.layers.len() == 1 && doc.layers.first().is_some_and(|layer| layer.children().is_none());
Some((dither, !flat))
}
/// The editing target the dialog captures when it opens, as the command's `target` parameter: the
/// targeted filter mask or layer mask, else the selected colour channels. A spec dialog (a plug-in,
/// a frame) takes a colour target only for several channels.
@@ -750,6 +784,10 @@ pub(crate) fn command_params(command: &str, fields: &DialogFields) -> Value {
map.insert(key.to_owned(), json!(crate::color_picker_ui::hex(*rgb)));
}
}
if command == CONVERT_PROFILE && fields.bool(CONVERT_FLATTEN_ENABLED) == Some(false) {
// The greyed checkbox is display-only: keep its remembered value but never flatten this document.
map.insert("flatten".into(), json!(false));
}
if let Some(spec) = photocraft_engine::commands::find(command) {
for key in document_keys(spec.params) {
if let Some(index) = map.get(&key).and_then(Value::as_str).and_then(|text| text.parse::<i64>().ok()) {
@@ -1166,7 +1204,14 @@ fn finish(
return Err(error);
}
};
let held_flatten = (cmd == CONVERT_PROFILE && result.fields.bool(CONVERT_FLATTEN_ENABLED) == Some(false))
.then(|| app.session.prefs().dialogs.get(CONVERT_PROFILE).and_then(|memory| memory.get("flatten")).cloned());
let outcome = crate::actions::run_step_dialog(app, result.id, &cmd, params.clone());
if outcome.is_ok()
&& let Some(before) = held_flatten
{
restore_convert_flatten_memory(app, before);
}
if let Ok(r) = &outcome {
report_file_errors(app, command, r);
}
@@ -1202,6 +1247,27 @@ fn finish(
outcome
}
/// A disabled form sends false, but #14260's committed-command memory must retain the held choice.
/// Restore before the frame can flush preferences; scripts/actions without this form keep their own policy.
fn restore_convert_flatten_memory(app: &mut PhotocraftApp, before: Option<Value>) {
let Some(memory) = app.session.prefs().dialogs.get(CONVERT_PROFILE).and_then(Value::as_object) else { return };
if memory.get("flatten") == before.as_ref() {
return;
}
app.session.edit_prefs(|prefs| {
if let Some(memory) = prefs.dialogs.get_mut(CONVERT_PROFILE).and_then(Value::as_object_mut) {
match before {
Some(value) => {
memory.insert("flatten".into(), value);
}
None => {
memory.remove("flatten");
}
}
}
});
}
/// Batch and the other folder runs (Image Processor, …) go on past a file that fails and list it
/// in their result's `errors`; the status bar and a notice say which files failed and why, so a run
/// that fails on every file isn't silent (#10682). Each file is named by its whole path: files of
@@ -1510,6 +1576,9 @@ pub struct FilterPreviewKey {
#[cfg(test)]
mod artboard_from_layers_size_range_tests;
#[cfg(test)]
#[path = "convert_profile_options_tests.rs"]
mod convert_profile_options_tests;
#[cfg(test)]
mod global_light_angle_range_tests;
#[cfg(test)]
mod tests;