diff --git a/crates/algo/src/stack.rs b/crates/algo/src/stack.rs index 52e67a3b71..b6037e1c24 100644 --- a/crates/algo/src/stack.rs +++ b/crates/algo/src/stack.rs @@ -2,7 +2,7 @@ //! statistic across N aligned images, e.g. median to remove passers-by or mean to reduce noise. //! //! Inputs are straight RGBA buffers of equal size. Only samples with alpha > 0 contribute; the -//! output alpha is the largest input alpha. Moments use the population definitions; skewness and +//! output is opaque wherever one does. Moments use the population definitions; skewness and //! kurtosis are standardised (kurtosis is excess-free, a normal sample gives ≈ 3), scaled into //! 0..=1 for display; entropy is the Shannon entropy (bits) of the 8-bit values over log2(N). @@ -239,7 +239,6 @@ fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScr for (j, o) in outs.iter_mut().enumerate() { let i = base + j; let mut k = 0; - let mut alpha = 0.0f32; for l in layers { if let Some(p) = l.get(i) && p[3] > 0.0 @@ -248,16 +247,15 @@ fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScr samples[c][k] = p[c]; } k += 1; - alpha = alpha.max(p[3]); } } - if alpha <= 0.0 { + if k == 0 { continue; } for c in 0..3 { o[c] = f(&mut samples[c][..k], &mut scratch); } - o[3] = alpha; + o[3] = 1.0; } }); out @@ -265,3 +263,7 @@ fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScr #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "stack_result_alpha_tests.rs"] +mod stack_result_alpha_tests; diff --git a/crates/algo/src/stack/tests.rs b/crates/algo/src/stack/tests.rs index d9f041124d..d8a9373d57 100644 --- a/crates/algo/src/stack/tests.rs +++ b/crates/algo/src/stack/tests.rs @@ -135,7 +135,7 @@ fn deep_median_stack_uses_only_visible_samples_per_channel() { let mut samples: Vec = layers.iter().filter(|l| l[0][3] > 0.0).map(|l| l[0][channel]).collect(); assert_eq!(actual[0][channel].to_bits(), sorted_median(&mut samples).to_bits()); } - assert_eq!(actual[0][3], 0.5); + assert_eq!(actual[0][3], 1.0); assert_eq!(actual[1], [0.0; 4]); } } @@ -169,7 +169,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x00000000, 0x00000000, 0x00000000, 0x3f800000], [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], ] .to_vec(), @@ -181,7 +181,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f800000], [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], ] .to_vec(), @@ -193,7 +193,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f800000], [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], ] .to_vec(), @@ -205,7 +205,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f800000], [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], ] .to_vec(), @@ -217,7 +217,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f800000], [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], ] .to_vec(), @@ -229,7 +229,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x00000000, 0x00000000, 0x00000000, 0x3f800000], [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], ] .to_vec(), @@ -241,7 +241,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], - [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], ] .to_vec(), @@ -253,7 +253,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x00000000, 0x00000000, 0x00000000, 0x3f800000], [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], ] .to_vec(), @@ -265,7 +265,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f800000], [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], ] .to_vec(), @@ -277,7 +277,7 @@ fn statistics_are_bit_identical_to_the_serial_implementation() { [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], [0x00000000, 0x00000000, 0x00000000, 0x00000000], [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x00000000, 0x00000000, 0x00000000, 0x3f800000], [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], ] .to_vec(), @@ -303,7 +303,7 @@ fn entropy_matches_hand_computed_values() { // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); // Pixel 4: a single contributing sample has no entropy. - assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); + assert_eq!(out[4], [0.0, 0.0, 0.0, 1.0]); // Pixel 5: three samples share a bin, one is alone, in every channel. for (c, v) in out[5].iter().take(3).enumerate() { assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); diff --git a/crates/algo/src/stack_result_alpha_tests.rs b/crates/algo/src/stack_result_alpha_tests.rs new file mode 100644 index 0000000000..d4edd1aecf --- /dev/null +++ b/crates/algo/src/stack_result_alpha_tests.rs @@ -0,0 +1,48 @@ +//! The stack result's alpha (#18296): opaque wherever at least one layer has a pixel, +//! transparent where none has. + +use super::*; + +const MODES: [Stat; 11] = [ + Stat::Entropy, + Stat::Kurtosis, + Stat::Maximum, + Stat::Mean, + Stat::Median, + Stat::Minimum, + Stat::Range, + Stat::Skewness, + Stat::StandardDeviation, + Stat::Summation, + Stat::Variance, +]; + +/// Five layers over two pixels: the first is grey 200 at `alpha` on every layer, the second +/// is empty on every layer. +fn five_layers(alpha: f32) -> Vec> { + let grey = 200.0 / 255.0; + (0..5).map(|_| vec![[grey, grey, grey, alpha], [0.0; 4]]).collect() +} + +#[test] +fn half_transparent_samples_give_an_opaque_result_with_the_opaque_colour() { + let half = five_layers(128.0 / 255.0); + let opaque = five_layers(1.0); + for mode in MODES { + let out = combine(&half, mode); + assert_eq!(out[0][3], 1.0, "{mode:?}"); + // Partly transparent samples count at full weight: the colour is what the same + // samples give when opaque. + assert_eq!(out[0], combine(&opaque, mode)[0], "{mode:?}"); + assert_eq!(out[1], [0.0; 4], "{mode:?}: a pixel empty on every layer stays transparent"); + } +} + +#[test] +fn one_faint_sample_among_empty_layers_is_enough_for_an_opaque_result() { + let layers = vec![vec![[0.0; 4]], vec![[0.25, 0.5, 0.75, 0.1]], vec![]]; + for mode in MODES { + assert_eq!(combine(&layers, mode)[0][3], 1.0, "{mode:?}"); + } + assert_eq!(combine(&layers, Stat::Mean)[0], [0.25, 0.5, 0.75, 1.0]); +} diff --git a/crates/automation/tests/it/openraster.rs b/crates/automation/tests/it/openraster.rs index 428ecfffb9..ae8d643063 100644 --- a/crates/automation/tests/it/openraster.rs +++ b/crates/automation/tests/it/openraster.rs @@ -26,6 +26,8 @@ fn layered_documents_save_reopen_and_save_in_place_as_openraster() { let path_str = path.to_str().unwrap(); let mut h = Headless::trusted_local(); h.handle("doc.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + // This lossless OpenRaster fixture deliberately has no metadata to drop. + std::sync::Arc::make_mut(h.session.active_mut().unwrap().doc_mut()).metadata.xmp = None; exec(&mut h, "layer.new.layer", json!({})); exec(&mut h, "paint.stroke", json!({"points": [[4, 4], [30, 20]], "size": 6, "hardness": 1.0, "color": "#ff0000"})); let top = h.session.active().unwrap().doc.layers.last().unwrap().id.0; @@ -77,6 +79,8 @@ fn an_openraster_file_never_overwrites_what_it_cannot_hold() { let path_str = path.to_str().unwrap(); let mut h = Headless::trusted_local(); h.handle("doc.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + // This lossless OpenRaster fixture deliberately has no metadata to drop. + std::sync::Arc::make_mut(h.session.active_mut().unwrap().doc_mut()).metadata.xmp = None; exec(&mut h, "layer.new.layer", json!({})); exec(&mut h, "paint.stroke", json!({"points": [[4, 4], [30, 20]], "size": 6, "hardness": 1.0, "color": "#ff0000"})); h.handle("doc.save", json!({"path": path_str})).unwrap(); diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index 0a0fd507f6..221aaa6867 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/Cargo.toml @@ -28,7 +28,8 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } -chrono = { workspace = true } +# New-document XMP dates use the actual local clock on native and web. +chrono = { workspace = true, features = ["clock"] } web-time = { workspace = true } photocraft-paint = { workspace = true } photocraft-algo = { workspace = true } @@ -54,11 +55,12 @@ craft = { workspace = true, features = ["automation", "color-ui", "keymap", "pla # Release tags use the same semantic versions as Cargo. semver = "1" +# Chrono reads the browser clock and time-zone offset through its existing JS bindings. +[target.'cfg(target_arch = "wasm32")'.dependencies] +chrono = { workspace = true, features = ["wasmbind"] } + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tempfile = "3" -# `clock`: the local time that names History Options' snapshot on save (#2966); already in the -# tree through rmcp. The web build has no local clock here and names it "Snapshot N". -chrono = { workspace = true, features = ["clock"] } # `file_cmds::same_file` on Windows: the volume serial number and file index, so a hard link to a # file is that file (std's `MetadataExt::file_index` is unstable). diff --git a/crates/engine-core/src/cmd/analysis_cmds.rs b/crates/engine-core/src/cmd/analysis_cmds.rs index 5a729e5a0b..6e65c4f0a0 100644 --- a/crates/engine-core/src/cmd/analysis_cmds.rs +++ b/crates/engine-core/src/cmd/analysis_cmds.rs @@ -57,7 +57,7 @@ pub const COLUMNS: &[(&str, &str)] = &[ ("angle", "Angle"), ]; -pub use crate::state::{AnalysisState, DataPoints, LogRow, available}; +pub use crate::state::{AnalysisState, DATA_POINT_GROUPS, DataPoints, LogRow, available}; // ------------------------------------------------------------------ helpers @@ -314,48 +314,61 @@ fn scale_json(sc: &MeasurementScale) -> Value { fn select_data_points(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.analysis.selectDataPoints"; let mut next = if p.get("reset").and_then(Value::as_bool) == Some(true) { DataPoints::default() } else { s.analysis.data_points.clone() }; + // Full lists replace their source-specific choices. Shared choices from all supplied lists are + // combined, then explicit on/off updates apply in source order. + let mut shared = None::>; + let mut changes = Vec::new(); for source in ["selection", "ruler", "count"] { + let Some(value) = p.get(source) else { continue }; let avail = available(source); - let Some(v) = p.get(source) else { continue }; - let list = next.of_mut(source); - match v { - // A full list of keys… - Value::Array(a) => { - let mut keys = Vec::new(); - for k in a { - let k = k.as_str().ok_or_else(|| bad(CMD, format!("`{source}` entries must be strings")))?; - if !avail.contains(&k) { - return Err(bad(CMD, format!("`{k}` is not a {source} data point ({})", avail.join("|")))); + let validate = |key: &str| { + if avail.contains(&key) { Ok(()) } else { Err(bad(CMD, format!("`{key}` is not a {source} data point ({})", avail.join("|")))) } + }; + match value { + Value::Array(keys) => { + let shared = shared.get_or_insert_with(Vec::new); + next.selected.retain(|key| DataPoints::is_shared(key) || !avail.contains(&key.as_str())); + for key in keys { + let key = key.as_str().ok_or_else(|| bad(CMD, format!("`{source}` entries must be strings")))?; + validate(key)?; + if DataPoints::is_shared(key) { + shared.push(key); + } else { + next.set(key, true); } - keys.push(k.to_string()); } - *list = keys; } - // …or {key: on/off} changes. - Value::Object(o) => { - for (k, on) in o { - if !avail.contains(&k.as_str()) { - return Err(bad(CMD, format!("`{k}` is not a {source} data point ({})", avail.join("|")))); - } - let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`{source}.{k}` must be a bool")))?; - list.retain(|x| x != k); - if on { - list.push(k.clone()); - } + Value::Object(values) => { + for (key, on) in values { + validate(key)?; + let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`{source}.{key}` must be a bool")))?; + changes.push((key, on)); } } _ => return Err(bad(CMD, format!("`{source}` must be a list of keys or an object of bools"))), } - // Keep the column order. - list.sort_by_key(|k| COLUMNS.iter().position(|c| c.0 == k)); } - if next.selection.is_empty() && next.ruler.is_empty() && next.count.is_empty() { + if let Some(shared) = shared { + next.selected.retain(|key| !DataPoints::is_shared(key)); + for key in shared { + next.set(key, true); + } + } + for (key, on) in changes { + next.set(key, on); + } + if next.selected.is_empty() { return Err(bad(CMD, "select at least one data point")); } + next.selected.sort_by_key(|key| COLUMNS.iter().position(|c| c.0 == key)); + let reply = json!({ + "selected": next.selected, + "dataPoints": {"selection": next.of("selection"), "ruler": next.of("ruler"), "count": next.of("count")}, + "available": {"selection": available("selection"), "ruler": available("ruler"), "count": available("count")}, + "columns": COLUMNS.iter().map(|&(key, name)| json!({"key": key, "name": name})).collect::>(), + }); s.analysis.data_points = next; - Ok( - json!({"dataPoints": s.analysis.data_points, "available": {"selection": available("selection"), "ruler": available("ruler"), "count": available("count")}, "columns": COLUMNS.iter().map(|c| json!({"key": c.0, "name": c.1})).collect::>()}), - ) + Ok(reply) } // ------------------------------------------------------------------ selection measurements @@ -1109,7 +1122,7 @@ fn record(s: &mut Session, p: &Value) -> Result { let needs_gray = s .analysis .data_points - .selection + .selected .iter() .any(|key| matches!(key.as_str(), "grayMin" | "grayMax" | "grayMean" | "grayMedian" | "integratedDensity" | "histogram")); let (sum, feats) = selection_rows(&d, needs_gray)?; @@ -1140,14 +1153,16 @@ fn record(s: &mut Session, p: &Value) -> Result { } // No data point enabled for the source: the reference application's alert, and nothing is recorded (no // empty row, no label number used up, #17407). - if s.analysis.data_points.of(source).is_empty() { + let keep = s.analysis.data_points.of(source); + for row in &mut rows { + row.retain(|key, _| keep.contains(&key.as_str())); + } + if rows.iter().all(Map::is_empty) { return Err(EngineError::Other(no_data_points(source))); } s.analysis.next_measurement += 1; - let keep = s.analysis.data_points.of(source).to_vec(); let mut ids = Vec::new(); - for mut m in rows { - m.retain(|k, _| keep.iter().any(|x| x == k)); + for m in rows { s.analysis.next_row += 1; ids.push(s.analysis.next_row); s.analysis.log.push(LogRow { id: s.analysis.next_row, values: m }); @@ -1439,6 +1454,9 @@ mod analysis_straighten_enabled_tests; mod analysis_straighten_selection_tests; #[cfg(test)] mod data_points_empty_set_tests; + +#[cfg(test)] +mod data_points_one_list_tests; #[cfg(test)] mod record_no_data_points_tests; #[cfg(test)] diff --git a/crates/engine-core/src/cmd/analysis_cmds/data_points_one_list_tests.rs b/crates/engine-core/src/cmd/analysis_cmds/data_points_one_list_tests.rs new file mode 100644 index 0000000000..06e8416958 --- /dev/null +++ b/crates/engine-core/src/cmd/analysis_cmds/data_points_one_list_tests.rs @@ -0,0 +1,48 @@ +use super::*; + +const POINTS: &str = "image.analysis.selectDataPoints"; +const RECORD: &str = "image.analysis.recordMeasurements"; + +#[test] +fn data_points_defaults_select_each_key_once_in_measurement_log_order() { + let reply = crate::session().execute(POINTS, json!({})).unwrap(); + let expected = COLUMNS.iter().map(|&(key, _)| key).collect::>(); + assert_eq!(reply["selected"], json!(expected)); + for source in ["selection", "ruler", "count"] { + assert_eq!(reply["dataPoints"][source], reply["available"][source]); + assert!(reply["dataPoints"][source].as_array().unwrap().contains(&json!("count"))); + } +} + +#[test] +fn data_points_legacy_lists_combine_shared_keys_and_patches_toggle_them_globally() { + let mut s = crate::session(); + let applied = s.execute(POINTS, json!({"selection": ["label", "area"], "ruler": ["length"], "count": ["count"]})).unwrap(); + assert_eq!(applied["selected"], json!(["label", "count", "area", "length"])); + assert_eq!(applied["dataPoints"]["selection"], json!(["label", "count", "area"])); + assert_eq!(applied["dataPoints"]["ruler"], json!(["label", "count", "length"])); + assert_eq!(applied["dataPoints"]["count"], json!(["label", "count"])); + + let changed = s.execute(POINTS, json!({"count": {"count": false}, "ruler": {"label": false}})).unwrap(); + assert_eq!(changed["selected"], json!(["area", "length"])); + assert!(s.execute(POINTS, json!({"selection": {"area": false}, "ruler": ["area"]})).is_err()); + assert_eq!(s.execute(POINTS, json!({})).unwrap(), changed, "an invalid source update leaves the set intact"); +} + +#[test] +fn record_measurements_uses_the_same_common_choices_for_every_source() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap(); + s.execute("count.add", json!({"x": 20, "y": 20})).unwrap(); + s.execute(POINTS, json!({"selection": ["label", "area"], "ruler": ["length"], "count": ["count"]})).unwrap(); + + for (source, measurement) in [("selection", "area"), ("ruler", "length"), ("count", "count")] { + let result = s.execute(RECORD, json!({"source": source})).unwrap(); + let values = &result["rows"][0]["values"]; + assert!(values["label"].is_string(), "{source}: {values}"); + assert!(values[measurement].is_number(), "{source}: {values}"); + assert!(values["document"].is_null(), "{source}: unchecked Common fields are omitted"); + } +} diff --git a/crates/engine-core/src/cmd/edit_cmds.rs b/crates/engine-core/src/cmd/edit_cmds.rs index 5849b59bfd..29f6423ee9 100644 --- a/crates/engine-core/src/cmd/edit_cmds.rs +++ b/crates/engine-core/src/cmd/edit_cmds.rs @@ -685,6 +685,7 @@ fn new_from_clipboard(s: &mut Session) -> Result { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = if moved.format() == target { moved } else { moved.convert(target) }; doc.layers.push(l); + doc.metadata.xmp = Some(crate::file_cmds::starting_xmp(&doc).into()); let i = s.add_document(doc, None); // Clipboard content has never been saved; closing this tab must ask before discarding it. if let Some(st) = s.active_mut() { diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index 278d0de5c4..a07d6fc4c5 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -45,7 +45,7 @@ pub(crate) use batch_run::{batch_action, batch_inputs, batch_keeps_step, batch_s pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with, layers_to_files_needs_more_layers}; use export::{color_lookup_tables, layers_to_files, push_unique}; use info::file_info; -pub use info::{CAMERA_FIELDS, camera_data, copyright_marked, read_file_info, write_file_info}; +pub use info::{CAMERA_FIELDS, camera_data, copyright_marked, read_file_info, starting_xmp, write_file_info}; #[cfg(test)] use info::{exposure_text, find_element}; pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults}; @@ -465,6 +465,10 @@ pub fn specs() -> Vec { #[path = "file_cmds/place_selection_centre_tests.rs"] mod place_selection_centre_tests; +#[cfg(test)] +#[path = "file_cmds/new_document_xmp_tests.rs"] +mod new_document_xmp_tests; + #[cfg(test)] #[path = "file_cmds/tests.rs"] mod tests; diff --git a/crates/engine-core/src/cmd/file_cmds/info.rs b/crates/engine-core/src/cmd/file_cmds/info.rs index b7e9ab5f9a..dbe704f090 100644 --- a/crates/engine-core/src/cmd/file_cmds/info.rs +++ b/crates/engine-core/src/cmd/file_cmds/info.rs @@ -16,6 +16,28 @@ fn xml_escape(s: &str) -> String { s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) } +/// A new document's initial packet. Opening files and later File Info edits never call this. +pub fn starting_xmp(doc: &photocraft_doc::Document) -> String { + let now = chrono::Local::now().format("%Y-%m-%dT%H:%M:%S%:z").to_string(); + let tool = xml_escape(&format!("PhotoCraft {}", env!("CARGO_PKG_VERSION"))); + let mut properties = format!( + "{tool}{now}\ + {now}{now}\ + image/vnd.adobe.photoshop" + ); + // Other modes and an untagged document are unmeasured; do not invent values or tag it. + if doc.mode == photocraft_color::ColorMode::Rgb { + properties.push_str("3"); + } + if doc.icc_profile.is_some() { + let profile = xml_escape(&crate::color_cmds::document_profile(doc).description); + properties.push_str(&format!("{profile}")); + } + format!( + r#"{properties}"# + ) +} + fn xml_unescape(s: &str) -> String { let mut out = String::with_capacity(s.len()); let mut rest = s; diff --git a/crates/engine-core/src/cmd/file_cmds/new_document_xmp_tests.rs b/crates/engine-core/src/cmd/file_cmds/new_document_xmp_tests.rs new file mode 100644 index 0000000000..7c65db664a --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/new_document_xmp_tests.rs @@ -0,0 +1,182 @@ +//! Starting XMP belongs to newly created documents, never to an opened file. +use super::*; +use chrono::{DateTime, Local}; +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_geom::Size; + +const PROPERTIES: [&str; 7] = + ["xmp:CreatorTool", "xmp:CreateDate", "xmp:ModifyDate", "xmp:MetadataDate", "dc:format", "photoshop:ColorMode", "photoshop:ICCProfile"]; + +fn packet(s: &Session) -> &str { + s.active().unwrap().doc.metadata.xmp.as_deref().expect("a newly created document has starting XMP") +} + +fn property<'a>(xmp: &'a str, name: &str) -> Option<&'a str> { + super::info::find_element(xmp, name).map(|(_, _, value)| value) +} + +fn assert_starting_packet(s: &Session, before: i64, after: i64, rgb: bool, profile: Option<&str>) { + let xmp = packet(s); + let namespaces = [ + ("x", "adobe:ns:meta/"), + ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), + ("xmp", "http://ns.adobe.com/xap/1.0/"), + ("dc", "http://purl.org/dc/elements/1.1/"), + ("photoshop", "http://ns.adobe.com/photoshop/1.0/"), + ]; + let canonical = craft_xml::Canonical::new(&namespaces); + let xml = craft_xml::Options::canonical(&canonical).strict().parse(xmp.as_bytes()).expect("starting XMP is well-formed namespace-aware XML"); + assert_eq!(property(xmp, "xmp:CreatorTool"), Some(format!("PhotoCraft {}", env!("CARGO_PKG_VERSION")).as_str())); + assert_eq!(property(xmp, "dc:format"), Some("image/vnd.adobe.photoshop")); + assert_eq!(property(xmp, "photoshop:ColorMode"), rgb.then_some("3")); + assert_eq!(property(xmp, "photoshop:ICCProfile"), profile); + let created = property(xmp, "xmp:CreateDate").unwrap(); + assert_eq!(property(xmp, "xmp:ModifyDate"), Some(created)); + assert_eq!(property(xmp, "xmp:MetadataDate"), Some(created)); + let date = DateTime::parse_from_rfc3339(created).expect("the starting date is ISO 8601"); + assert!((before..=after).contains(&date.timestamp()), "the date is the creation time: {created}, {before}..={after}"); + assert_eq!(date.offset().local_minus_utc(), date.with_timezone(&Local).offset().local_minus_utc(), "local offset, not a forced UTC date"); + assert!(created.ends_with(&date.format("%:z").to_string()), "the ISO date includes its numeric local offset: {created}"); + let mut count = 0; + for name in PROPERTIES { + let occurrences = xml.descendants().filter(|element| element.name == name).count(); + assert_eq!(occurrences, usize::from(property(xmp, name).is_some()), "each property occurs at most once: {name}"); + count += occurrences; + } + assert_eq!(count, 5 + usize::from(rgb) + usize::from(profile.is_some())); +} + +#[test] +fn new_rgb_documents_start_with_basic_xmp_without_tagging_untagged_content() { + for depth in [8, 16, 32] { + for params in [ + json!({"width": 3, "height": 2, "depth": depth, "background": "white"}), + json!({"width": 3, "height": 2, "depth": depth, "background": "transparent"}), + json!({"width": 3, "height": 2, "depth": depth, "artboard": true}), + ] { + let mut s = crate::session(); + let before = Local::now().timestamp(); + s.execute("file.new", params).unwrap(); + let after = Local::now().timestamp(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Rgb); + assert!(s.active().unwrap().doc.icc_profile.is_none(), "starting metadata must not tag an untagged document"); + assert_starting_packet(&s, before, after, true, None); + } + } +} + +#[test] +fn tagged_new_and_preset_documents_write_all_seven_properties_from_their_profile() { + for (profile, description) in [("srgb", "sRGB IEC61966-2.1"), ("display-p3", "Display P3")] { + for preset in [false, true] { + let mut s = crate::session(); + let settings = json!({"width": 3, "height": 2, "mode": "rgb", "depth": 16, "background": "white", "profile": profile}); + let params = if preset { + s.execute("document.presets.save", json!({"name": "Metadata profile", "settings": settings})).unwrap(); + s.execute("document.presets.get", json!({"name": "Metadata profile"})).unwrap()["params"].clone() + } else { + settings + }; + let before = Local::now().timestamp(); + s.execute("file.new", params).unwrap(); + let after = Local::now().timestamp(); + let doc = &s.active().unwrap().doc; + assert!(doc.icc_profile.is_some()); + assert_eq!(crate::color_cmds::document_profile(doc).description, description); + assert_starting_packet(&s, before, after, true, Some(description)); + } + } +} + +#[test] +fn clipboard_and_paste_without_a_document_get_fresh_xmp_without_inheriting_metadata_or_tagging() { + for depth in [8, 16, 32] { + for paste_without_document in [false, true] { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 3, "height": 2, "depth": depth, "profile": "display-p3"})).unwrap(); + Arc::make_mut(s.active_mut().unwrap().doc_mut()).metadata.xmp = Some("".into()); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + if paste_without_document { + s.execute("file.close", json!({})).unwrap(); + assert!(s.documents().is_empty()); + } + let before = Local::now().timestamp(); + s.execute(if paste_without_document { "edit.paste" } else { "file.newFromClipboard" }, json!({})).unwrap(); + let after = Local::now().timestamp(); + let doc = &s.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height), (3, 2)); + assert_eq!(doc.mode, ColorMode::Rgb); + assert!(doc.icc_profile.is_none(), "the existing clipboard profile behavior stays untagged"); + assert!(!packet(&s).contains("source-only-metadata")); + assert_starting_packet(&s, before, after, true, None); + } + } +} + +#[test] +fn unmeasured_modes_omit_color_mode_and_untagged_profile_properties() { + for (mode, depth, expected) in + [("gray", 8, ColorMode::Grayscale), ("cmyk", 8, ColorMode::Cmyk), ("lab", 8, ColorMode::Lab), ("bitmap", 1, ColorMode::Bitmap)] + { + let mut s = crate::session(); + let before = Local::now().timestamp(); + s.execute("file.new", json!({"width": 3, "height": 2, "mode": mode, "depth": depth})).unwrap(); + let after = Local::now().timestamp(); + assert_eq!(s.active().unwrap().doc.mode, expected); + assert!(s.active().unwrap().doc.icc_profile.is_none()); + assert_starting_packet(&s, before, after, false, None); + } +} + +#[test] +fn file_info_ok_and_editing_descriptive_fields_preserve_the_starting_dates() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 3, "height": 2, "profile": "display-p3"})).unwrap(); + let original = packet(&s).to_string(); + let submitted = s.execute("file.fileInfo", json!({})).unwrap(); + s.execute("file.fileInfo", submitted).unwrap(); + assert_eq!(packet(&s), original, "OK without changes keeps the complete starting packet"); + s.execute("file.fileInfo", json!({"title": "Before dawn"})).unwrap(); + for name in PROPERTIES { + assert_eq!(property(packet(&s), name), property(&original, name), "File Info does not rewrite {name}"); + } + assert_eq!(s.execute("file.fileInfo", json!({})).unwrap()["title"], "Before dawn"); +} + +#[test] +fn opening_files_keeps_their_own_packet_or_absence_of_a_packet() { + const IMPORTED: &str = r#"Imported Tool 1.22001-02-03T04:05:06+05:452002-03-04T05:06:07-04:002003-04-05T06:07:08+00:00image/custom3Imported Profile"#; + for xmp in [None, Some(IMPORTED)] { + let mut doc = Document::with_background("Imported", Size::new(3, 2), ColorMode::Rgb, SampleType::U8, Color::WHITE); + doc.metadata.xmp = xmp.map(Into::into); + let bytes = encode(&doc, "imported.psd", None).unwrap().0; + // Export legitimately synchronizes resolution metadata. Open must retain the packet + // actually in the file, including those fields, rather than regenerate starting XMP. + let encoded = import("imported.psd", &bytes).unwrap(); + if let Some(original) = xmp { + for name in PROPERTIES { + assert_eq!(property(encoded.metadata.xmp.as_deref().unwrap(), name), property(original, name)); + } + } else { + assert!(encoded.metadata.xmp.is_none()); + } + let mut s = crate::session(); + open_bytes_as(&mut s, "imported.psd", &bytes, None, Some("imported.psd".into())).unwrap(); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().doc.metadata.xmp, encoded.metadata.xmp, "opening must not seed or rewrite metadata"); + } +} + +#[test] +fn starting_xmp_remains_a_real_openraster_metadata_loss() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 3, "height": 2})).unwrap(); + assert!(s.active().unwrap().doc.metadata.xmp.is_some()); + assert!(!holds_at(&s.active().unwrap().doc, "new.ora")); + assert!(losses_at(&s.active().unwrap().doc, "new.ora").iter().any(|loss| loss.to_lowercase().contains("metadata"))); + // This is why the explicit metadata-free OpenRaster fixtures clear the starting packet. + Arc::make_mut(s.active_mut().unwrap().doc_mut()).metadata.xmp = None; + assert!(holds_at(&s.active().unwrap().doc, "new.ora")); + assert!(losses_at(&s.active().unwrap().doc, "new.ora").is_empty()); +} diff --git a/crates/engine-core/src/cmd/file_cmds/tests.rs b/crates/engine-core/src/cmd/file_cmds/tests.rs index 2f6cb00e47..c29887f4cd 100644 --- a/crates/engine-core/src/cmd/file_cmds/tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/tests.rs @@ -3411,6 +3411,8 @@ fn only_layered_files_save_in_place() { #[test] fn openraster_holds_a_document_only_when_it_drops_nothing() { let mut s = session(16, 16, 8); + // This lossless fixture deliberately has no metadata for OpenRaster to drop. + Arc::make_mut(s.active_mut().unwrap().doc_mut()).metadata.xmp = None; s.execute("layer.new.layer", json!({})).unwrap(); let plain = doc(&s).clone(); for p in ["a.psd", "a.psb", "a.pcraft", "a.ora", "A.ORA"] { diff --git a/crates/engine-core/src/cmd/layer_menu_cmds.rs b/crates/engine-core/src/cmd/layer_menu_cmds.rs index 0beb4ccd56..5126723d52 100644 --- a/crates/engine-core/src/cmd/layer_menu_cmds.rs +++ b/crates/engine-core/src/cmd/layer_menu_cmds.rs @@ -393,8 +393,9 @@ fn color_decontaminate(s: &mut Session, p: &Value) -> Result { fn stack_mode(s: &mut Session, p: &Value, mode: Option) -> Result { let id = layer_param(s, p)?; - let label = mode.map_or("None", StackMode::label); - s.edit(&format!("Stack Mode: {label}"), |doc, _| { + // The History state of a mode is named after the rendering, with the entry's label; None keeps its own (#18295). + let name = mode.map_or_else(|| "Stack Mode: None".to_string(), |mode| format!("Rendering Image Stack {}", mode.label())); + s.edit(&name, |doc, _| { let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let LayerContent::Smart(sm) = &mut l.content else { return Err(other("the active layer is not a smart object")); @@ -1158,4 +1159,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod global_light_background_only_tests; #[cfg(test)] +mod stack_mode_history_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/layer_menu_cmds/stack_mode_history_tests.rs b/crates/engine-core/src/cmd/layer_menu_cmds/stack_mode_history_tests.rs new file mode 100644 index 0000000000..5aa091e92b --- /dev/null +++ b/crates/engine-core/src/cmd/layer_menu_cmds/stack_mode_history_tests.rs @@ -0,0 +1,71 @@ +//! #18295: each Layer › Smart Objects › Stack Mode entry adds one History state named "Rendering Image Stack ", +//! as the reference application names it, instead of "Stack Mode: ". None keeps "Stack Mode: None". + +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// The command's last id segment and the History state the reference application records for it. +const NAMES: [(&str, &str); 11] = [ + ("entropy", "Rendering Image Stack Entropy"), + ("kurtosis", "Rendering Image Stack Kurtosis"), + ("maximum", "Rendering Image Stack Maximum"), + ("mean", "Rendering Image Stack Mean"), + ("median", "Rendering Image Stack Median"), + ("minimum", "Rendering Image Stack Minimum"), + ("range", "Rendering Image Stack Range"), + ("skewness", "Rendering Image Stack Skewness"), + ("standardDeviation", "Rendering Image Stack Standard Deviation"), + ("summation", "Rendering Image Stack Summation"), + ("variance", "Rendering Image Stack Variance"), +]; + +/// A document whose active layer is a smart object. +fn smart_object() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 8), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +#[test] +fn each_mode_adds_one_state_named_rendering_image_stack_and_its_entry() { + let mut s = smart_object(); + for (kind, name) in NAMES { + let states = history(&s).0; + s.execute(&format!("layer.smartObjects.stackMode.{kind}"), json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some(name.to_string())), "{kind}"); + } +} + +/// The name follows the entry as the menu shows it. +#[test] +fn the_name_ends_with_the_entrys_menu_label() { + let _session = crate::session(); + for (kind, name) in NAMES { + let label = crate::commands::find(&format!("layer.smartObjects.stackMode.{kind}")).unwrap().label; + assert_eq!(name.strip_prefix("Rendering Image Stack "), Some(label), "{kind}"); + } +} + +#[test] +fn none_keeps_its_name() { + let mut s = smart_object(); + s.execute("layer.smartObjects.stackMode.median", json!({})).unwrap(); + let states = history(&s).0; + s.execute("layer.smartObjects.stackMode.none", json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some("Stack Mode: None".to_string()))); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index d3835c136a..7c19de2481 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -67,13 +67,21 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { if items.is_empty() { return Err(EngineError::Other("the selected layers have no content to align".into())); } + // The selection, when the layers align to it. + let mut reference = None; let target = match to.as_str() { "canvas" => doc.bounds(), - "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?, + "selection" => { + reference = doc.selection.as_ref(); + reference.map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))? + } "auto" | "layers" => match (&doc.selection, sel.len()) { // Photoshop: with an active selection, the layers align to its bounds (Layer › Align // Layers to Selection), however many are selected. - (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => m.content_bounds(), + (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => { + reference = Some(m); + m.content_bounds() + } // One layer with no selection aligns to the canvas (otherwise it would align to // itself), or to the artboard it sits in, as in Photoshop (#7945). (None, 1) if to == "auto" => items.first().map_or_else(|| doc.bounds(), |(id, _)| board_or_canvas(doc, *id)), @@ -85,10 +93,14 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { return Err(EngineError::Other("nothing to align to".into())); } let t2 = edge.value2(&target); + // A centre can fall on a half pixel, which rounds towards +x / +y (#18282). A selection that is not a plain + // rectangle was not measured as the reference and keeps rounding the other way. + let half_pixel = items.iter().any(|(_, r)| (t2 - edge.value2(r)) % 2 != 0); + let round_up = !(half_pixel && reference.is_some_and(|m| !plain_rectangle(m, target))); let moves: Vec<(LayerId, i32, i32)> = items .iter() .flat_map(|(id, r)| { - let d = (t2 - edge.value2(r)).div_euclid(2) as i32; + let d = (t2 - edge.value2(r) + i64::from(round_up)).div_euclid(2) as i32; let (dx, dy) = edge.delta(d); // Linked layers travel with the layer they are linked to. with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy)) @@ -101,6 +113,15 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { Ok(json!({"moved": moved})) } +/// Whether a selection selects every pixel of its bounds fully: a rectangle with hard edges. +fn plain_rectangle(mask: &photocraft_raster::Surface, bounds: Rect) -> bool { + let mut row = vec![0.0; bounds.width() as usize]; + (bounds.y0..bounds.y1).all(|y| { + mask.sample_row_strided(y, bounds.x0, 1, 0, &mut row); + row.iter().all(|v| *v >= 1.0) + }) +} + /// The bounds a lone layer aligns to: the artboard holding it, else the canvas. An artboard /// itself aligns to the canvas. fn board_or_canvas(doc: &Document, id: LayerId) -> Rect { @@ -173,3 +194,7 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { #[cfg(test)] #[path = "align_history_names_tests.rs"] mod align_history_names_tests; + +#[cfg(test)] +#[path = "align_half_pixel_tests.rs"] +mod align_half_pixel_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_half_pixel_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_half_pixel_tests.rs new file mode 100644 index 0000000000..33f5d588d3 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_half_pixel_tests.rs @@ -0,0 +1,130 @@ +//! #18282: Layer › Align › Vertical Centers and Horizontal Centers put a layer at the reference's centre minus half the +//! layer's size, and a half pixel rounds towards the right and down, as measured in the reference application. It +//! rounded towards the left and up, which left the layer one pixel off. A selection that is not a plain rectangle +//! was not measured as the reference and keeps the rounding it had. + +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// The two layers of the measurement: A is 40 x 40, B is 61 x 31. +const A: Rect = Rect::new(20, 30, 60, 70); +const B: Rect = Rect::new(150, 100, 211, 131); + +fn session(width: u32, height: u32, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": width, "height": height, "depth": depth})).unwrap(); + s +} + +/// A new pixel layer with an opaque rectangle. +fn rect_layer(s: &mut Session, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +/// A document with the layers A and B, both selected. +fn a_and_b(width: u32, height: u32, depth: u32) -> (Session, LayerId, LayerId) { + let mut s = session(width, height, depth); + let (a, b) = (rect_layer(&mut s, A), rect_layer(&mut s, B)); + select(&mut s, &[a, b]); + (s, a, b) +} + +fn bounds(s: &Session, id: LayerId) -> Rect { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds() +} + +fn selection_bounds(s: &Session) -> Rect { + s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds() +} + +#[test] +fn centres_round_a_half_pixel_towards_the_right_and_down() { + for depth in [8, 16, 32] { + // The union is y 30..131, centre 80.5: A, 40 tall, belongs at 60.5 and B, 31 tall, at 65. + let (mut s, a, b) = a_and_b(400, 300, depth); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], [Rect::new(20, 61, 60, 101), Rect::new(150, 65, 211, 96)], "{depth}-bit"); + // The union is x 20..211, centre 115.5: A, 40 wide, belongs at 95.5 and B, 61 wide, at 85. + let (mut s, a, b) = a_and_b(400, 300, depth); + s.execute("layer.align.horizontalCenters", json!({})).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], [Rect::new(96, 30, 136, 70), Rect::new(85, 100, 146, 131)], "{depth}-bit"); + } +} + +/// The half pixel rounds down the canvas whether the layer comes from above or from below. +#[test] +fn a_layer_lands_on_the_same_row_from_above_and_from_below() { + // The union is y 30..70, centre 50: a layer 31 tall belongs at 34.5. + for top in [32, 38] { + let mut s = session(400, 300, 8); + let layers = [rect_layer(&mut s, A), rect_layer(&mut s, Rect::new(150, top, 211, top + 31))]; + select(&mut s, &layers); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!([bounds(&s, layers[0]), bounds(&s, layers[1])], [A, Rect::new(150, 35, 211, 66)], "from top {top}"); + } +} + +#[test] +fn centres_round_the_same_way_against_a_rectangular_selection() { + // (100,50)-(301,251): centre y 150.5, so A belongs at 130.5 and B at 135. + for depth in [8, 16, 32] { + let (mut s, a, b) = a_and_b(400, 300, depth); + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 201, "height": 201})).unwrap(); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], [Rect::new(20, 131, 60, 171), Rect::new(150, 135, 211, 166)], "{depth}-bit"); + } +} + +#[test] +fn the_rounding_is_the_same_for_each_named_reference() { + // `layers`: the selection is there, but the layers align to each other. + let (mut s, a, _) = a_and_b(400, 300, 8); + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 201, "height": 201})).unwrap(); + s.execute("layer.align.verticalCenters", json!({"to": "layers"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(20, 61, 60, 101)); + // `selection`. + let (mut s, a, _) = a_and_b(400, 300, 8); + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 201, "height": 201})).unwrap(); + s.execute("layer.align.verticalCenters", json!({"to": "selection"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(20, 131, 60, 171)); + // `canvas`: 401 x 301 has its centre at (200.5, 150.5), so A belongs at (180.5, 130.5). + let (mut s, a, _) = a_and_b(401, 301, 8); + s.execute("layer.align.verticalCenters", json!({"to": "canvas"})).unwrap(); + s.execute("layer.align.horizontalCenters", json!({"to": "canvas"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(181, 131, 221, 171)); +} + +/// Not measured as the reference, so these keep the rounding they had: A's top is 130, where the rectangle with the +/// same bounds gives 131. +#[test] +fn a_selection_that_is_not_a_plain_rectangle_keeps_rounding_towards_the_top() { + let two_rectangles = [json!({"x": 100, "y": 50, "width": 50, "height": 50}), json!({"x": 251, "y": 201, "width": 50, "height": 50, "mode": "add"})]; + let ellipse = [json!({"x": 100, "y": 50, "width": 201, "height": 201, "ellipse": true})]; + for (name, steps) in [("two rectangles", &two_rectangles[..]), ("an ellipse", &ellipse[..])] { + for params in [json!({}), json!({"to": "selection"})] { + let (mut s, a, b) = a_and_b(400, 300, 8); + for step in steps { + s.execute("select.rect", step.clone()).unwrap(); + } + assert_eq!(selection_bounds(&s), Rect::new(100, 50, 301, 251), "{name}"); + s.execute("layer.align.verticalCenters", params.clone()).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], [Rect::new(20, 130, 60, 170), Rect::new(150, 135, 211, 166)], "{name}, {params}"); + } + } +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_keeps_layer_tags_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_keeps_layer_tags_tests.rs new file mode 100644 index 0000000000..e19cb94f40 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/group_from_layers_keeps_layer_tags_tests.rs @@ -0,0 +1,72 @@ +//! Group from Layers with a colour tags the new group only; the layers moved into it keep their +//! own colour tags, also inside nested groups (#18279). + +use super::*; + +const GROUP_FROM_LAYERS: &str = "layer.new.groupFromLayers"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s +} + +fn create(s: &mut Session, command: &str, name: &str) -> LayerId { + LayerId(s.execute(command, json!({"name": name})).unwrap()["layer"].as_u64().unwrap()) +} + +fn create_with(s: &mut Session, p: Value) -> LayerId { + LayerId(s.execute(GROUP_FROM_LAYERS, p).unwrap()["layer"].as_u64().unwrap()) +} + +fn tag(s: &mut Session, id: LayerId, color: &str) { + s.execute("layer.setLabelColor", json!({"layer": id.0, "color": color})).unwrap(); +} + +/// The tag `document.inspect` reports for `id`, wherever it sits in the tree. +fn tag_of(s: &mut Session, id: LayerId) -> String { + fn find(layers: &Value, id: LayerId) -> Option<&Value> { + layers.as_array()?.iter().find_map(|l| if l["id"] == id.0 { Some(l) } else { find(&l["children"], id) }) + } + let state = s.execute("document.inspect", json!({})).unwrap(); + find(&state["layers"], id).expect("layer is in the tree")["labelColor"].as_str().unwrap().to_string() +} + +#[test] +fn the_colour_tags_the_new_group_and_the_moved_layers_keep_their_tags() { + let mut s = session(); + let blue = create(&mut s, "layer.new.layer", "Blue"); + let red = create(&mut s, "layer.new.layer", "Red"); + tag(&mut s, blue, "green"); + s.execute("layer.select", json!({"layers": [blue.0, red.0]})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let group = create_with(&mut s, json!({"color": "red"})); + assert_eq!(tag_of(&mut s, group), "red"); + assert_eq!(tag_of(&mut s, blue), "green", "a tagged layer keeps its tag"); + assert_eq!(tag_of(&mut s, red), "none", "an untagged layer stays untagged"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history step"); + + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(group).is_none()); + assert_eq!((tag_of(&mut s, blue), tag_of(&mut s, red)), ("green".into(), "none".into())); +} + +#[test] +fn layers_inside_a_moved_group_keep_their_tags() { + let mut s = session(); + let inner = create(&mut s, "layer.new.layer", "In"); + let group3 = create(&mut s, "layer.new.group", "Group 3"); + s.execute("layer.moveTo", json!({"layer": inner.0, "target": group3.0, "position": "into"})).unwrap(); + let green = create(&mut s, "layer.new.layer", "Green"); + tag(&mut s, inner, "blue"); + s.execute("layer.select", json!({"layers": [group3.0, green.0]})).unwrap(); + let group = create_with(&mut s, json!({"color": "violet"})); + assert_eq!(tag_of(&mut s, group), "violet"); + assert_eq!(tag_of(&mut s, inner), "blue"); + assert_eq!((tag_of(&mut s, group3), tag_of(&mut s, green)), ("none".into(), "none".into())); + assert_eq!(s.active().unwrap().doc.layers.index().parent(inner), Some(group3), "the tree is as grouped"); + + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.index().parent(group3), None); + assert_eq!((tag_of(&mut s, inner), tag_of(&mut s, group3), tag_of(&mut s, green)), ("blue".into(), "none".into(), "none".into())); +} diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs index ab63541aaa..2a1f8213e0 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/structure.rs @@ -132,7 +132,7 @@ pub(super) fn group_from_layers(s: &mut Session, p: &Value) -> Result { if ids.iter().any(|id| doc.is_background(*id)) { return Err(EngineError::Other("the Background layer can't go into a group".into())); } - group_layers_with(s, p, &ids, ids.len() == 1) + group_layers_with(s, p, &ids, ids.len() == 1, false) } /// Group Layers (⌘G) moves the explicit layer or the selection into a new, collapsed group. @@ -141,12 +141,12 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result { Some(id) => vec![id], None => selected(s), }; - group_layers_with(s, p, &ids, false) + group_layers_with(s, p, &ids, false, true) } /// Creates the group at the topmost target, preserving layer order and applying the dialog's -/// options in the same history step. -fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool) -> Result { +/// options in the same history step. `tag_layers` passes a colour on to the layers inside. +fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool, tag_layers: bool) -> Result { if ids.is_empty() { return Err(EngineError::Other("no layer selected".into())); } @@ -186,7 +186,7 @@ fn group_layers_with(s: &mut Session, p: &Value, ids: &[LayerId], expanded: bool } let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?; *group.children_mut().ok_or(EngineError::NoLayer(gid))? = children; - opts.apply(group); + opts.apply(group, tag_layers); check_group_depth(doc, "Group Layers")?; *active = Some(gid); Ok(gid) @@ -422,3 +422,7 @@ pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { })?; Ok(Value::Null) } + +#[cfg(test)] +#[path = "group_from_layers_keeps_layer_tags_tests.rs"] +mod group_from_layers_keeps_layer_tags_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs index 9b9093557b..0f43ef6378 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs @@ -665,8 +665,8 @@ fn align_each_edge() { let cases: [(&str, [Rect; 2]); 6] = [ ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]), ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]), - // Union 5..30: centre 17.5; half-pixel offsets round towards the top. - ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]), + // Union 5..30: centre 17.5; half-pixel offsets round towards the bottom (#18282). + ("verticalCenters", [Rect::new(10, 13, 20, 23), Rect::new(40, 8, 50, 28)]), ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]), ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]), ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]), diff --git a/crates/engine-core/src/cmd/smart_cmds/placing.rs b/crates/engine-core/src/cmd/smart_cmds/placing.rs index f08d35a7b7..e207e9f8a3 100644 --- a/crates/engine-core/src/cmd/smart_cmds/placing.rs +++ b/crates/engine-core/src/cmd/smart_cmds/placing.rs @@ -103,7 +103,8 @@ pub(super) fn reset_transform(s: &mut Session, p: &Value) -> Result { if ![dx, dy, cx, cy].iter().all(|v| v.is_finite()) || !rel.0.iter().all(|v| v.is_finite()) { return Err(other("the smart object's placement is not a usable transform")); } - s.edit("Reset Transform", |doc, _| { + // The History state is plural, the entry is not (#18285). + s.edit("Reset Transforms", |doc, _| { // The Warp is part of what the reference takes back, so the re-render below starts from the // unwarped contents. How far a painted Smart Filter mask should follow a cleared warp is // unmeasured: here it follows the placement, as it does under Free Transform. @@ -342,3 +343,7 @@ pub(super) fn via_copy(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": new_id.0})) }) } + +#[cfg(test)] +#[path = "reset_transform_history_name_tests.rs"] +mod reset_transform_history_name_tests; diff --git a/crates/engine-core/src/cmd/smart_cmds/reset_transform_history_name_tests.rs b/crates/engine-core/src/cmd/smart_cmds/reset_transform_history_name_tests.rs new file mode 100644 index 0000000000..5a16e9d15c --- /dev/null +++ b/crates/engine-core/src/cmd/smart_cmds/reset_transform_history_name_tests.rs @@ -0,0 +1,46 @@ +//! #18285: Layer › Smart Objects › Reset Transform records its History state as "Reset Transforms", as the reference +//! application does. The entry itself keeps its name, "Reset Transform". + +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +const RESET: &str = "layer.smartObjects.resetTransform"; + +/// A document whose active layer is a smart object, scaled to 50 % / 30 % and rotated 30°. +fn transformed_smart_object() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 8, 40, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let id = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("edit.transform", json!({"layer": id, "scaleX": 50, "scaleY": 30, "rotate": 30})).unwrap(); + s +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +#[test] +fn reset_transform_adds_one_history_state_named_reset_transforms() { + let mut s = transformed_smart_object(); + let states = history(&s).0; + s.execute(RESET, json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some("Reset Transforms".to_string()))); +} + +/// Only the History name is plural: the menus still show the entry as "Reset Transform". +#[test] +fn the_entry_keeps_its_name() { + // A session installs the commands. + let _session = crate::session(); + assert_eq!(crate::commands::find(RESET).unwrap().label, "Reset Transform"); +} diff --git a/crates/engine-core/src/cmd/table/model/layer_menu.rs b/crates/engine-core/src/cmd/table/model/layer_menu.rs index ac56389226..bd9a48769f 100644 --- a/crates/engine-core/src/cmd/table/model/layer_menu.rs +++ b/crates/engine-core/src/cmd/table/model/layer_menu.rs @@ -41,7 +41,7 @@ fn creation() -> Vec { let id = s.edit("New Group", |doc, active| { let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group")); let mut group = Layer::group(name, vec![]); - opts.apply(&mut group); + opts.apply(&mut group, false); let bg = crate::background_cmds::background_id(doc); let id = crate::layer_place::insert_new(doc, *active, group, place); crate::background_cmds::keep_background_at_bottom(bg, doc)?; diff --git a/crates/engine-core/src/cmd/table/store/file_menu.rs b/crates/engine-core/src/cmd/table/store/file_menu.rs index d446f61041..e3a04e3d90 100644 --- a/crates/engine-core/src/cmd/table/store/file_menu.rs +++ b/crates/engine-core/src/cmd/table/store/file_menu.rs @@ -65,6 +65,7 @@ pub fn specs() -> Vec { } doc.icc_profile = Some(prof.to_bytes()); } + doc.metadata.xmp = Some(crate::file_cmds::starting_xmp(&doc).into()); let i = s.add_document(doc, None); // A new document's first History state is "New"; opened files keep "Open" (#14029). if let Some(st) = s.active_mut() { diff --git a/crates/engine-core/src/cmd/type_extra_cmds.rs b/crates/engine-core/src/cmd/type_extra_cmds.rs index c3ce98effe..b62936078a 100644 --- a/crates/engine-core/src/cmd/type_extra_cmds.rs +++ b/crates/engine-core/src/cmd/type_extra_cmds.rs @@ -925,8 +925,14 @@ fn replace_fonts(s: &mut Session, map: &serde_json::Map, all: boo if missing.is_empty() { return Ok(json!({"missing": [], "replaced": 0})); } + // A map that names none of the missing families replaces nothing, and that adds no History state (#18324). + if !missing.iter().any(|f| pick(f).is_some()) { + return Ok(json!({"missing": missing, "replaced": 0})); + } + // The state is named after what ran: the fonts of a map, or all of them (#18324). + let name = if all { "Replace All Missing Fonts" } else { "Replace Fonts" }; let mut n = 0; - s.edit("Replace Missing Fonts", |doc, _| { + s.edit(name, |doc, _| { let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); for id in &ids { if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(*id) { @@ -1141,3 +1147,7 @@ mod tests; #[cfg(test)] #[path = "type_anti_alias_history_tests.rs"] mod anti_alias_history_tests; + +#[cfg(test)] +#[path = "type_missing_fonts_history_tests.rs"] +mod missing_fonts_history_tests; diff --git a/crates/engine-core/src/cmd/type_missing_fonts_history_tests.rs b/crates/engine-core/src/cmd/type_missing_fonts_history_tests.rs new file mode 100644 index 0000000000..9212a2d7eb --- /dev/null +++ b/crates/engine-core/src/cmd/type_missing_fonts_history_tests.rs @@ -0,0 +1,65 @@ +//! #18324: replacing missing fonts one by one adds a History state named "Replace Fonts", and replacing all of them +//! adds one named "Replace All Missing Fonts", as the reference application names them, instead of "Replace Missing +//! Fonts" for both. A run that replaces nothing adds no state. + +use serde_json::{Value, json}; + +use crate::Session; + +const MISSING: &str = "No Such Font Family"; + +/// A document with one type layer set in `font`. +fn session(font: &str) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 300, "height": 120})).unwrap(); + s.execute("type.create", json!({"x": 20, "y": 70, "text": "Ab", "size": 36})).unwrap(); + s.execute("type.setStyle", json!({"font": font})).unwrap(); + s +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +/// Runs `cmd` on a document whose type layer uses a missing font, and returns the states it added with the name of +/// the newest and the command's `replaced` count. +fn run(cmd: &str, params: Value) -> (usize, Option, Value) { + let mut s = session(MISSING); + let states = history(&s).0; + let replaced = s.execute(cmd, params).unwrap()["replaced"].clone(); + let (now, name) = history(&s); + (now - states, name, replaced) +} + +#[test] +fn replacing_a_font_from_the_map_adds_one_state_named_replace_fonts() { + let (added, name, replaced) = run("type.resolveMissingFonts", json!({"map": {MISSING: "JetBrains Mono"}})); + assert_eq!((added, name.as_deref(), replaced), (1, Some("Replace Fonts"), json!(1))); +} + +#[test] +fn replacing_all_adds_one_state_named_replace_all_missing_fonts() { + let (added, name, replaced) = run("type.replaceAllMissingFonts", json!({})); + assert_eq!((added, name.as_deref(), replaced), (1, Some("Replace All Missing Fonts"), json!(1))); +} + +#[test] +fn a_run_that_replaces_nothing_adds_no_state() { + // No font is missing. + for (cmd, params) in [("type.replaceAllMissingFonts", json!({})), ("type.resolveMissingFonts", json!({"map": {MISSING: "JetBrains Mono"}}))] { + let mut s = session("JetBrains Mono"); + let before = history(&s); + assert_eq!(s.execute(cmd, params).unwrap()["replaced"], 0, "{cmd}"); + assert_eq!(history(&s), before, "{cmd}"); + } + // A font is missing, but the map does not replace it. + for map in [json!({}), json!({"Some Other Family": "JetBrains Mono"})] { + let mut s = session(MISSING); + let before = history(&s); + let r = s.execute("type.resolveMissingFonts", json!({"map": map})).unwrap(); + assert_eq!((&r["missing"], &r["replaced"]), (&json!([MISSING]), &json!(0)), "{map}"); + assert_eq!(history(&s), before, "{map}"); + } +} diff --git a/crates/engine-core/src/cmd/web_cmds/tests.rs b/crates/engine-core/src/cmd/web_cmds/tests.rs index 0dcf8438b7..f0f698a35c 100644 --- a/crates/engine-core/src/cmd/web_cmds/tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/tests.rs @@ -1300,6 +1300,8 @@ fn save_for_web_all_writes_the_photos_exif() { fn save_for_web_webp_all_keeps_an_exif_only_photos_exif() { let dir = tmp("webp_exif"); let mut s = session(8); + // The source photo is EXIF-only, not a new document carrying its starting XMP. + std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()).metadata.xmp = None; s.edit("exif", |doc, _| { doc.metadata.exif = Some(std::sync::Arc::new(camera_exif())); Ok(()) diff --git a/crates/engine-core/src/group_options.rs b/crates/engine-core/src/group_options.rs index 4c72b2f078..a3f673d07d 100644 --- a/crates/engine-core/src/group_options.rs +++ b/crates/engine-core/src/group_options.rs @@ -50,9 +50,11 @@ impl GroupOptions { Ok(Self { name, color, blend, opacity }) } - /// Sets the mode, opacity and colour of a new `group`. A colour also reaches every layer inside - /// it, as Layer › Layer Color does on a group; "No Color" leaves the layers' own colours alone. - pub(crate) fn apply(&self, group: &mut Layer) { + /// Sets the mode, opacity and colour of a new `group`. With `tag_layers` a colour also reaches + /// every layer inside it, as Layer › Layer Color does on a group; without it only the group takes + /// the colour and the layers keep their own tags, as Group from Layers does (#18279). "No Color" + /// leaves the layers' own colours alone. + pub(crate) fn apply(&self, group: &mut Layer, tag_layers: bool) { if let Some(blend) = self.blend { group.blend = blend; } @@ -61,6 +63,7 @@ impl GroupOptions { } match self.color { Some(LabelColor::None) | None => {} + Some(color) if !tag_layers => group.label = color, Some(color) => { // Explicit stack: documents can nest groups deeply. let mut stack = vec![group]; diff --git a/crates/engine-core/src/pixel_fill.rs b/crates/engine-core/src/pixel_fill.rs index d18dbfd888..2e9e51b319 100644 --- a/crates/engine-core/src/pixel_fill.rs +++ b/crates/engine-core/src/pixel_fill.rs @@ -99,13 +99,13 @@ pub fn read_rgba(src: &Surface, area: Rect, purpose: &str) -> Result) -> Result<()> { let source = Source::Pixels(area, read_rgba(src, area, "pasting pixels")?); - blend_into(surf, area, &source, limit, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) + blend_into(surf, area, &source, limit, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false, threshold: false }) } /// `area` of `surf` filled with an opaque `color` (Normal, 100 %), weighted by `sel` when given: /// Clear on a targeted alpha channel or the Quick Mask (#2734). pub fn fill_color(surf: &mut Surface, area: Rect, color: [f32; 4], sel: Option<&Surface>) -> Result<()> { - blend_into(surf, area, &Source::Color(color), sel, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false }) + blend_into(surf, area, &Source::Color(color), sel, Blend { mode: BlendMode::Normal, opacity: 1.0, keep_alpha: false, restore: false, threshold: false }) } /// Reuse Edit › Fill's compositing for Edit › Stroke. The stroke's rasterized band @@ -126,7 +126,7 @@ pub fn blend_color_mask( Some(cmyk) if color[3] >= 1.0 => Source::Cmyk { rgba: color, cmyk }, _ => Source::Color(color), }; - blend_into(surf, area, &source, Some(coverage), Blend { mode, opacity, keep_alpha: preserve_transparency, restore: false }) + blend_into(surf, area, &source, Some(coverage), Blend { mode, opacity, keep_alpha: preserve_transparency, restore: false, threshold: false }) } /// How the source goes onto the target. @@ -138,6 +138,9 @@ pub struct Blend { pub keep_alpha: bool, /// Normal mode replaces the pixels, transparency included (History: back to that state). pub restore: bool, + /// Each pixel is either fully painted or left as it is, at a coverage of one half (an Indexed + /// Color document's fill, which never blends towards a colour outside the table). + pub threshold: bool, } /// `d` moved towards `c` by `k`, in premultiplied space (straight RGBA in and out). @@ -200,6 +203,59 @@ pub fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<& Ok(()) } +/// Map the pixels of `r` that differ from `pre` to their nearest entry of `table`, with no dither, +/// so a fill in an Indexed Color document never leaves the colour table. One tile at a time. With +/// `keep_alpha` (Preserve Transparency, locked transparency) each pixel keeps its alpha and only its +/// colour snaps, as if opaque; otherwise the table's transparent entry may take a mostly clear pixel. +pub fn keep_in_color_table(table: &photocraft_doc::ColorTable, pre: &Surface, surf: &mut Surface, r: Rect, keep_alpha: bool) { + use photocraft_algo::quantize::{Dither, quantize}; + if table.colors.is_empty() { + return; + } + let fmt = surf.format(); + let n = fmt.channels(); + let mut enc = [0.0f32; 8]; + for tc in r.tiles() { + let t = tc.rect().intersect(&r); + if t.is_empty() || !surf.has_tiles_in(t) { + continue; + } + let (before, mut data) = (pre.read_region(t), surf.read_region(t)); + let (mut changed, mut px) = (Vec::new(), Vec::new()); + for (i, (q, b)) in data.chunks_exact(n).zip(before.chunks_exact(n)).enumerate() { + if q != b { + changed.push(i); + px.push(to_rgba(&fmt, q)); + } + } + if px.is_empty() { + continue; + } + let w = px.len(); + let alphas: Vec = if keep_alpha { px.iter_mut().map(|c| std::mem::replace(&mut c[3], 1.0)).collect() } else { Vec::new() }; + quantize(&mut px, w, &table.colors, Dither::None, 0.0, table.transparent.map(usize::from)); + if keep_alpha { + px.iter_mut().zip(&alphas).for_each(|(c, a)| c[3] = *a); + } + let mut mapped = changed.into_iter().zip(px).peekable(); + let mut moved = false; + for (i, q) in data.chunks_exact_mut(n).enumerate() { + if let Some((_, c)) = mapped.next_if(|(j, _)| *j == i) { + let m = from_rgba_into(&fmt, c, &mut enc); + for (d, v) in q.iter_mut().zip(enc.iter().take(m)) { + moved |= (*d - *v).abs() > 1e-6; + *d = *v; + } + } + } + // Already table colours (a snapped fill colour's shared solid tiles): writing them back + // would copy every shared tile for nothing. + if moved { + surf.write_region(t, &data); + } + } +} + /// Snap every pixel of `area` that `sel` covers (all of them without one) to black below 50 % grey and to white from /// it, on the first sample: a Bitmap document's 1-bit pixels after a fill (#17475). Alpha is left as it is. pub fn snap_black_white(surf: &mut Surface, area: Rect, sel: Option<&Surface>) -> Result<()> { @@ -295,7 +351,7 @@ impl<'a> Mask<'a> { /// Blend into one tile's encoded pixels (`bytes`, the tile at `origin`) over `tr`. pub fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rect, tr: Rect, source: &Source, mask: Option<&Mask>, b: Blend) { - let Blend { mode, opacity, keep_alpha, restore } = b; + let Blend { mode, opacity, keep_alpha, restore, threshold } = b; let n = fmt.channels(); let bpp = fmt.bytes_per_pixel(); let blend = if mode == BlendMode::Dissolve { BlendMode::Normal } else { mode }; @@ -317,6 +373,9 @@ pub fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: let row = (y - origin.y0) as usize * TILE_SIZE as usize; for x in tr.x0..tr.x1 { let mut k = mask.map_or(1.0, |m| m.at(x, y)) * opacity; + if threshold { + k = if k >= 0.5 { 1.0 } else { 0.0 }; + } if k <= 0.0 { continue; } diff --git a/crates/engine-core/src/state.rs b/crates/engine-core/src/state.rs index 24674e6eff..7fd88e9322 100644 --- a/crates/engine-core/src/state.rs +++ b/crates/engine-core/src/state.rs @@ -153,49 +153,58 @@ pub struct EditState { // Image › Analysis (`analysis_cmds`) const COMMON: &[&str] = &["label", "dateTime", "document", "source", "scale", "scaleUnits", "scaleFactor"]; -const SELECTION_ONLY: &[&str] = +const SELECTION: &[&str] = &["count", "area", "perimeter", "circularity", "height", "width", "grayMin", "grayMax", "grayMean", "grayMedian", "integratedDensity", "histogram"]; -const RULER_ONLY: &[&str] = &["length", "angle"]; -const COUNT_ONLY: &[&str] = &["count"]; +const RULER: &[&str] = &["count", "length", "angle"]; +const COUNT: &[&str] = &["count"]; -/// Data points a measurement source can record. +/// The groups and their keys in the Select Data Points dialog. Count appears in all three source groups. +pub const DATA_POINT_GROUPS: [&[&str]; 4] = [COMMON, SELECTION, RULER, COUNT]; + +/// Data points a measurement source can offer. pub fn available(source: &str) -> Vec<&'static str> { let extra = match source { - "selection" => SELECTION_ONLY, - "ruler" => RULER_ONLY, - _ => COUNT_ONLY, + "selection" => SELECTION, + "ruler" => RULER, + _ => COUNT, }; COMMON.iter().chain(extra).copied().collect() } -/// Image › Analysis › Select Data Points: what Record Measurements writes per source. +/// Image › Analysis › Select Data Points: one session-wide set, in Measurement Log column order. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataPoints { - pub selection: Vec, - pub ruler: Vec, - pub count: Vec, + pub(crate) selected: Vec, } impl Default for DataPoints { fn default() -> Self { - let all = |s| available(s).into_iter().map(String::from).collect(); - Self { selection: all("selection"), ruler: all("ruler"), count: all("count") } + Self { selected: crate::analysis_cmds::COLUMNS.iter().map(|&(key, _)| String::from(key)).collect() } } } impl DataPoints { - pub(crate) fn of(&self, source: &str) -> &[String] { - match source { - "selection" => &self.selection, - "ruler" => &self.ruler, - _ => &self.count, - } + /// Whether the named point is enabled for recording. + pub fn contains(&self, key: &str) -> bool { + self.selected.iter().any(|point| point == key) } - pub(crate) fn of_mut(&mut self, source: &str) -> &mut Vec { - match source { - "selection" => &mut self.selection, - "ruler" => &mut self.ruler, - _ => &mut self.count, + + /// Selected keys that are available for the given source. + pub fn of(&self, source: &str) -> Vec<&'static str> { + available(source).into_iter().filter(|key| self.contains(key)).collect() + } + + pub(crate) fn is_shared(key: &str) -> bool { + COMMON.contains(&key) || key == "count" + } + + pub(crate) fn set(&mut self, key: &str, on: bool) { + if on { + if !self.contains(key) { + self.selected.push(key.into()); + } + } else { + self.selected.retain(|point| point != key); } } } diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 7cbb590a79..ddc4efa976 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -3,6 +3,8 @@ //! Contents: Foreground / Background / Color / Content-Aware / Pattern / History / Black / //! 50% Gray / White, blended with `mode` at `opacity`, optionally preserving the target's //! transparency. The selection (or the whole canvas) is filled, as one history step ("Fill"). +//! In an Indexed Color document the layer pixels stay inside the colour table: the fill colour +//! snaps to its nearest entry and opacity is a threshold at 50 % (Dissolve keeps its odds). //! Every parameter is validated: a bad one is an error, never a panic. use photocraft_algo::content_aware::FillOptions; @@ -18,7 +20,7 @@ use crate::color_cmds::swatch_in_doc; use crate::commands::{cmyk_param, color_param, layer_param, parse_blend}; use crate::content_sampling::{content_aware, content_aware_options}; pub use crate::pixel_fill::greyed_modes; -use crate::pixel_fill::{Blend, Source, blend_into, check_mode_available, read_rgba, snap_black_white}; +use crate::pixel_fill::{Blend, Source, blend_into, check_mode_available, keep_in_color_table, read_rgba, snap_black_white}; use crate::{EngineError, Result, Session}; const CMD: &str = "edit.fill"; @@ -111,7 +113,10 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { // and the filled pixels snap to black or white below (#17475). Alpha channels kept through the conversion and // the Quick Mask stay greyscale. let bitmap = st.doc.mode == ColorMode::Bitmap && !channel && !crate::commands::is_mask_target(p); - let opacity = if bitmap && mode != BlendMode::Dissolve { if opacity >= 0.5 { 1.0 } else { 0.0 } } else { opacity }; + // Indexed: every pixel is filled or left as it was, never a blend towards a colour outside the table (#17472). + let table = indexed_table(&st.doc, p); + let threshold = table.is_some() && mode != BlendMode::Dissolve; + let opacity = if (bitmap || table.is_some()) && mode != BlendMode::Dissolve { if opacity >= 0.5 { 1.0 } else { 0.0 } } else { opacity }; let doc_bounds = st.doc.bounds(); let sel = st.doc.selection.clone(); // With no selection a layer's pixels outside the canvas are filled too, as in the reference @@ -224,6 +229,11 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { }, source => source, }; + // One colour fills as its nearest table entry, uniform over the area, with no dither. + let source = match (&table, source) { + (Some(t), Source::Color(c) | Source::Cmyk { rgba: c, .. }) => Source::Color(table_color(t, c)), + (_, source) => source, + }; if area.is_empty() { return Ok(out); } @@ -233,7 +243,7 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { s.edit("Fill", |doc, _| { let sel = doc.selection.clone(); if inks { - let blend = Blend { mode, opacity, keep_alpha: false, restore }; + let blend = Blend { mode, opacity, keep_alpha: false, restore, threshold: false }; // A pattern reaches the first ink only; the others come out white, as the reference fills them. let white = Source::Color([1.0; 4]); for (k, surf) in photocraft_engine_core::multichannel_cmds::inks_mut(doc).enumerate() { @@ -243,16 +253,37 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { return Ok(()); } let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; - blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore })?; + let pre = table.as_ref().map(|_| surf.clone()); + blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore, threshold })?; if bitmap { snap_black_white(surf, area, sel.as_ref())?; } + // Patterns, history, Content-Aware and the other blend modes snap per pixel. + if let (Some(t), Some(pre)) = (&table, &pre) { + keep_in_color_table(t, pre, surf, area, preserve || lock); + } Ok(()) }) })?; Ok(out) } +/// The colour table a fill on `p`'s target must stay inside: an Indexed Color document's, when the +/// target is layer pixels (masks and channels are gray, not indexed). +fn indexed_table(doc: &photocraft_doc::Document, p: &Value) -> Option { + let pixels = crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; + doc.color_table.clone().filter(|t| pixels && doc.mode == ColorMode::Indexed && !t.colors.is_empty()) +} + +/// `c`'s colour as its nearest entry of `table`, keeping `c`'s alpha: Dissolve takes it as its odds, +/// and the per-pixel table step maps what a partly transparent colour blends to. +fn table_color(table: &photocraft_doc::ColorTable, c: [f32; 4]) -> [f32; 4] { + let mut px = [[c[0], c[1], c[2], 1.0]]; + photocraft_algo::quantize::quantize(&mut px, 1, &table.colors, photocraft_algo::quantize::Dither::None, 0.0, table.transparent.map(usize::from)); + let [[r, g, b, _]] = px; + [r, g, b, c[3]] +} + /// A fill colour as a Multichannel document takes it (#17479): its grey in Gray Gamma 2.2, the one /// value the reference writes into every channel (RGB 200,30,30 gives 104 and 30,30,200 gives 64). /// A failed conversion keeps the colour. @@ -405,6 +436,9 @@ mod fill_quick_mask_mode_gray_tests; #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; +#[cfg(test)] +mod indexed_palette_tests; + #[cfg(test)] mod multichannel_fill_tests; diff --git a/crates/engine-paint/src/cmd/fill_cmds/indexed_palette_tests.rs b/crates/engine-paint/src/cmd/fill_cmds/indexed_palette_tests.rs new file mode 100644 index 0000000000..9c6e90ecbb --- /dev/null +++ b/crates/engine-paint/src/cmd/fill_cmds/indexed_palette_tests.rs @@ -0,0 +1,249 @@ +//! #17472: Edit › Fill in an Indexed Color document stays inside the colour table. A colour fill +//! writes the nearest table entry, uniform over the selection, and opacity is a threshold at 50 % +//! (Dissolve keeps its odds). Fills in the other colour modes are unchanged. + +use super::*; +use serde_json::json; + +const BLACK: [u8; 3] = [0, 0, 0]; +const WHITE: [u8; 3] = [255, 255, 255]; +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +/// The issue's selection, 50,25-150,75. +const SEL: Rect = Rect { x0: 50, y0: 25, x1: 150, y1: 75 }; + +/// A 200 × 100 blue Indexed document whose Exact table is black, white, red and blue (a patch of each +/// in the corners), with the issue's selection and foreground (200,30,30) / background (30,30,200). +fn indexed() -> Session { + indexed_with(&[]) +} + +/// [`indexed`] with a 10 × 10 patch of each of `extra` (along the bottom edge) in the table too. +fn indexed_with(extra: &[&str]) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + for (x, c) in [(0, "#000000"), (190, "#ff0000")] { + s.execute("select.rect", json!({"x": x, "y": 0, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("select.rect", json!({"x": 0, "y": 90, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + for (i, c) in (1..).zip(extra) { + s.execute("select.rect", json!({"x": 20 * i, "y": 90, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "transparency": false})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Indexed); + select(&mut s); + s.execute("tools.setColors", json!({"foreground": "#c81e1e", "background": "#1e1ec8"})).unwrap(); + s +} + +fn select(s: &mut Session) { + s.execute("select.rect", json!({"x": SEL.x0, "y": SEL.y0, "width": SEL.width(), "height": SEL.height(), "antiAlias": false})).unwrap(); +} + +fn table(s: &Session) -> Vec<[u8; 3]> { + let mut t = s.active().unwrap().doc.color_table.as_ref().expect("an Indexed document has a table").colors.clone(); + t.sort_unstable(); + t +} + +/// Every pixel of the active layer as 8-bit RGB, with its position. +fn pixels(s: &Session) -> Vec<((i32, i32), [u8; 3])> { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let b = st.doc.bounds(); + (b.y0..b.y1) + .flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))) + .map(|(x, y)| { + let c = surf.rgba(x, y); + ((x, y), [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8)) + }) + .collect() +} + +/// The distinct colours inside the selection, and whether everything outside it kept `before`. +fn fill_result(s: &Session, before: &[((i32, i32), [u8; 3])]) -> (Vec<[u8; 3]>, bool) { + let after = pixels(s); + let mut inside: Vec<[u8; 3]> = after.iter().filter(|((x, y), _)| SEL.contains(*x, *y)).map(|(_, c)| *c).collect(); + inside.sort_unstable(); + inside.dedup(); + let outside_kept = after.iter().zip(before).filter(|(((x, y), _), _)| !SEL.contains(*x, *y)).all(|((_, a), (_, b))| a == b); + (inside, outside_kept) +} + +#[test] +fn each_colour_fill_writes_the_nearest_table_entry_over_the_selection() { + let cases: [(Value, &[[u8; 3]]); 8] = [ + (json!({"contents": "foreground"}), &[RED]), + (json!({"contents": "background"}), &[BLUE]), + (json!({"contents": "color", "color": "#33cc66"}), &[BLACK]), + (json!({"contents": "color", "color": "#8c8c8c"}), &[WHITE]), + // Equally near red and blue: either is a nearest entry (the tie-break was not measured). + (json!({"contents": "color", "color": "#800080"}), &[RED, BLUE]), + (json!({"contents": "black"}), &[BLACK]), + (json!({"contents": "gray"}), &[WHITE]), + (json!({"contents": "white"}), &[WHITE]), + ]; + for (params, want) in cases { + let mut s = indexed(); + let (table_before, before, steps) = (table(&s), pixels(&s), s.active().unwrap().history.past_len()); + s.execute(CMD, params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); + let (inside, outside_kept) = fill_result(&s, &before); + assert!(inside.len() == 1 && want.contains(&inside[0]), "{params}: the selection holds {inside:?}, wanted one of {want:?}"); + assert!(outside_kept, "{params}: nothing outside the selection changes"); + assert_eq!(table(&s), table_before, "{params}: the colour table is unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{params}: one history state"); + } +} + +#[test] +fn opacity_is_a_threshold_at_one_half() { + for (opacity, want) in [(1.0, BLUE), (25.0, BLUE), (49.0, BLUE), (50.0, WHITE), (51.0, WHITE), (75.0, WHITE), (100.0, WHITE)] { + let mut s = indexed(); + let before = pixels(&s); + s.execute(CMD, json!({"contents": "white", "opacity": opacity})).unwrap(); + let (inside, outside_kept) = fill_result(&s, &before); + assert_eq!(inside, vec![want], "White over blue at {opacity} %"); + assert!(outside_kept, "{opacity} %: nothing outside the selection changes"); + } +} + +#[test] +fn a_feathered_selection_edge_is_filled_or_left_never_blended() { + // With grey in the table, a faint white over blue would snap to grey if it were blended. + let mut s = indexed_with(&["#808080"]); + s.execute("select.modify.feather", json!({"radius": 8})).unwrap(); + let sel = s.active().unwrap().doc.selection.clone().expect("a feathered selection"); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + let px = pixels(&s); + let (mut faint, mut strong) = (0, 0); + for ((x, y), c) in px.into_iter().filter(|((x, y), _)| SEL.contains(*x, *y)) { + let k = sel.rgba(x, y)[0]; + if k > 0.0 && k < 0.5 { + faint += 1; + assert_eq!(c, BLUE, "({x}, {y}) is selected at {k}: left as it was"); + } else if k >= 0.5 { + strong += 1; + assert_eq!(c, WHITE, "({x}, {y}) is selected at {k}: fully filled"); + } + } + assert!(faint > 0 && strong > 0, "the feather has both kinds of edge pixel ({faint}, {strong})"); +} + +#[test] +fn dissolve_paints_a_share_of_pixels_in_the_full_table_colour() { + let mut s = indexed(); + s.execute(CMD, json!({"contents": "foreground", "mode": "dissolve", "opacity": 50})).unwrap(); + let inside: Vec<[u8; 3]> = pixels(&s).into_iter().filter(|((x, y), _)| SEL.contains(*x, *y)).map(|(_, c)| c).collect(); + let red = inside.iter().filter(|c| **c == RED).count(); + assert!(inside.iter().all(|c| *c == RED || *c == BLUE), "every pixel is the snapped fill or untouched"); + let share = red as f64 / inside.len() as f64; + assert!((0.3..0.7).contains(&share), "about half the pixels take the fill, got {share}"); +} + +#[test] +fn other_contents_and_blend_modes_stay_inside_the_table() { + for params in [ + // Red screened over blue is magenta, which the table lacks. + json!({"contents": "foreground", "mode": "screen"}), + json!({"contents": "color", "color": "#c81e1e", "mode": "multiply"}), + json!({"contents": "color", "color": "#33cc66", "mode": "difference", "opacity": 80}), + json!({"contents": "contentAware", "seed": 3}), + ] { + let mut s = indexed(); + let palette = table(&s); + s.execute(CMD, params.clone()).unwrap_or_else(|e| panic!("{params}: {e}")); + let off: Vec<[u8; 3]> = pixels(&s).into_iter().map(|(_, c)| c).filter(|c| !palette.contains(c)).collect(); + assert!(off.is_empty(), "{params}: {} pixels outside the table, e.g. {:?}", off.len(), off.first()); + } +} + +#[test] +fn other_colour_modes_still_blend_and_keep_the_colour() { + for mode in ["rgb", "cmyk", "lab", "grayscale"] { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": mode, "background": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "black", "opacity": 25})).unwrap(); + let st = s.active().unwrap(); + let v = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(10, 10)[0]; + assert!(v > 0.05 && v < 0.95, "{mode}: 25 % black over white is a grey, got {v}"); + } + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "color", "color": "#c81e1e"})).unwrap(); + let st = s.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(10, 10); + assert_eq!([0, 1, 2].map(|i| (c[i] * 255.0).round() as u8), [200, 30, 30], "an RGB fill keeps its colour"); +} + +/// A blue 200 × 100 Indexed document whose table has a transparent entry (which maps a mostly +/// transparent colour to transparency) besides red and blue, with the issue's selection. +fn indexed_with_transparent_entry() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 190, "y": 0, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "transparency": true})).unwrap(); + assert!(s.active().unwrap().doc.color_table.as_ref().is_some_and(|t| t.transparent.is_some()), "the table has a transparent entry"); + select(&mut s); + s +} + +#[test] +fn dissolve_takes_a_partly_transparent_colour_alpha_as_its_odds() { + let share = |alpha: f64| { + let mut s = indexed_with_transparent_entry(); + s.execute(CMD, json!({"contents": "color", "color": [1.0, 0.0, 0.0, alpha], "mode": "dissolve"})).unwrap(); + let inside: Vec<[u8; 3]> = pixels(&s).into_iter().filter(|((x, y), _)| SEL.contains(*x, *y)).map(|(_, c)| c).collect(); + assert!(inside.iter().all(|c| *c == RED || *c == BLUE), "alpha {alpha}: every pixel is the snapped fill or untouched"); + inside.iter().filter(|c| **c == RED).count() as f64 / inside.len() as f64 + }; + let (quarter, three_quarters) = (share(0.25), share(0.75)); + assert!(quarter > 0.1 && quarter < 0.4, "alpha 0.25 paints about a quarter, got {quarter}"); + assert!(three_quarters > 0.6 && three_quarters < 0.9, "alpha 0.75 paints about three quarters, got {three_quarters}"); +} + +#[test] +fn a_whole_canvas_fill_keeps_its_shared_solid_tiles() { + // Two colours in the table, then black over the white 512 × 512 canvas: every 256 px tile is + // the fill's one shared tile, and the table step doesn't copy it per tile. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 512, "height": 512, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "transparency": false})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + // The shared tile is for a layer whose transparency may change, not the Background. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute(CMD, json!({"contents": "black"})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let tiles: Vec<_> = surf.tiles().map(|(_, t)| t).collect(); + assert_eq!(tiles.len(), 4); + assert!(tiles.iter().all(|t| std::sync::Arc::ptr_eq(t, tiles[0])), "the filled tiles share one buffer"); +} + +#[test] +fn preserve_transparency_keeps_a_partly_transparent_pixel_alpha() { + let mut s = indexed_with_transparent_entry(); + // Pixels a quarter and three quarters opaque inside the selection. + let id = s.active().unwrap().active_layer.unwrap(); + for (x, a) in [(60, 0.25), (61, 0.75)] { + let doc = std::sync::Arc::make_mut(s.active_mut().unwrap().doc_mut()); + doc.layer_mut(id).unwrap().surface_mut().unwrap().write_region(Rect::new(x, 50, x + 1, 51), &[0.0, 0.0, 1.0, a]); + } + s.execute(CMD, json!({"contents": "color", "color": "#ff1010", "preserveTransparency": true})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(id).unwrap().surface().unwrap(); + for (x, a) in [(60, 0.25), (61, 0.75)] { + let c = surf.rgba(x, 50); + assert!((c[3] - a).abs() < 0.01, "({x}, 50) keeps its alpha {a}, got {}", c[3]); + assert_eq!([0, 1, 2].map(|i| (c[i] * 255.0).round() as u8), RED, "({x}, 50) takes the table colour"); + } +} diff --git a/crates/engine/tests/it/affinity.rs b/crates/engine/tests/it/affinity.rs index 5f85803263..b436d9e697 100644 --- a/crates/engine/tests/it/affinity.rs +++ b/crates/engine/tests/it/affinity.rs @@ -12,6 +12,8 @@ use serde_json::json; fn fixture() -> Vec { let mut src = Session::new(); src.execute("file.new", json!({"width": 2, "height": 1, "background": "#dc283c"})).unwrap(); + // This observed preview fixture has no XMP packet (or compressed PNG iTXt). + Arc::make_mut(src.active_mut().unwrap().doc_mut()).metadata.xmp = None; // Affinity's previews carry no colour profile. let mut opts = photocraft_io::ExportOptions::default(); opts.encode.embed_icc = false; diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 2fa350f868..11edd5f050 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -1050,6 +1050,8 @@ fn an_unavailable_dialog_is_reported_and_a_cancelled_one_is_not() { #[test] fn openraster_save_never_overwrites_what_it_cannot_hold() { let (mut app, files, written) = app(); + // The plain in-place-save control deliberately excludes metadata OpenRaster cannot hold. + Arc::make_mut(app.session.active_mut().unwrap().doc_mut()).metadata.xmp = None; app.run("layer.new.layer", json!({})).unwrap(); app.session.active_mut().unwrap().path = Some("/pics/art.ora".into()); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs index 8305a64e75..2c2b777a13 100644 --- a/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs +++ b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs @@ -1,13 +1,11 @@ -//! #16345: Image › Analysis › Select Data Points draws every check box with its data point's name, and each column's -//! title above its boxes. +//! Select Data Points draws each named checkbox under its group heading (#16345, #17404). -use egui::accesskit::Role; +use egui::accesskit::{Role, Toggled}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use photocraft_engine::analysis_cmds; use serde_json::{Value, json}; -use super::sources; use crate::PhotocraftApp; type H = Harness<'static, Box>; @@ -48,9 +46,29 @@ fn rect(r: egui::accesskit::Rect) -> egui::Rect { egui::Rect::from_min_max(egui::pos2(r.x0 as f32, r.y0 as f32), egui::pos2(r.x1 as f32, r.y1 as f32)) } +fn scroll_to(h: &mut H, label: &str) { + let pane = h.get_by_role_and_label(Role::Group, "Data Points").rect(); + h.hover_at(pane.center()); + for _ in 0..24 { + if h.query_all_by_label(label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).is_some_and(|node| pane.contains(node.rect().center())) { + return; + } + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + } + panic!("{label} did not scroll into the list"); +} + #[test] -fn every_check_box_draws_its_data_point_name_and_each_column_its_title_above() { - let h = open_dialog(json!({})); +fn every_check_box_draws_its_name_under_the_correct_group_heading() { + let mut h = open_dialog(json!({})); + let pane = h.get_by_role_and_label(Role::Group, "Data Points").rect(); let mut boxes: Vec = h .query_all_by_role(Role::CheckBox) .map(|b| { @@ -61,40 +79,46 @@ fn every_check_box_draws_its_data_point_name_and_each_column_its_title_above() { Shown { rect: b.rect(), name, text } }) .collect(); - // In columns by their left edge, each column top to bottom. - boxes.sort_by(|a, b| a.rect.left().total_cmp(&b.rect.left()).then(a.rect.top().total_cmp(&b.rect.top()))); - let mut columns: Vec> = Vec::new(); - for shown in boxes { - match columns.last_mut() { - Some(column) if (column[0].rect.left() - shown.rect.left()).abs() < 0.5 => column.push(shown), - _ => columns.push(vec![shown]), - } + boxes.sort_by(|a, b| a.rect.top().total_cmp(&b.rect.top())); + let names = boxes.iter().map(|b| b.name.as_str()).collect::>(); + let expected = analysis_cmds::DATA_POINT_GROUPS.into_iter().flatten().map(|key| name(key)).collect::>(); + assert_eq!(names, expected, "every data point has a named box in list order"); + + // At the top and bottom of the scroll area, each visible name is drawn beside its box. + for b in boxes.iter().filter(|b| pane.contains(b.rect.center())) { + let text = b.text.unwrap_or_else(|| panic!("{:?} draws no name", b.name)); + assert!(text.left() >= b.rect.right() - 0.5 && text.top() < b.rect.bottom() && text.bottom() > b.rect.top()); } - let names: Vec> = columns.iter().map(|c| c.iter().map(|s| s.name.as_str()).collect()).collect(); - assert_eq!(columns.len(), sources().len(), "one column of boxes per source: {names:?}"); - for (((source, title), column), shown) in sources().into_iter().zip(&columns).zip(&names) { - let want: Vec<&str> = analysis_cmds::available(source).into_iter().map(name).collect(); - assert_eq!(shown, &want, "{source}: each box is named after its data point, in order"); - // Each box draws its name: the text that names it stands after the box, on its line. - for b in column { - let text = b.text.unwrap_or_else(|| panic!("{source}: {:?} draws no name", b.name)); - assert!( - text.left() >= b.rect.right() - 0.5 && text.top() < b.rect.bottom() && text.bottom() > b.rect.top(), - "{source}: {:?} is named beside its box", - b.name - ); - } - // The title sits over its column's first box, under the dialog's "Data Points:" rather than on its line. - let heading = h.query_by_label("Data Points:").expect("\"Data Points:\" is drawn").rect(); - let first = column[0].rect; - let title = h - .query_all_by_label(title) - .find(|n| n.accesskit_node().role() != Role::CheckBox && n.rect().left() <= first.center().x && n.rect().right() >= first.center().x) - .unwrap_or_else(|| panic!("{title} heads its column")) - .rect(); - assert!(title.bottom() <= first.top() + 0.5, "{source}: the title {title:?} is above the first box {first:?}"); - assert!(heading.bottom() <= title.top() + 0.5, "{source}: \"Data Points:\" {heading:?} is above the title {title:?}"); + let mut remaining = boxes.as_slice(); + for (title, group) in ["Common", "Selections", "Ruler Tool", "Count Tool"].into_iter().zip(analysis_cmds::DATA_POINT_GROUPS) { + let (boxes, rest) = remaining.split_at(group.len()); + let first = boxes[0].rect; + let heading = h.query_all_by_label(title).find(|n| n.accesskit_node().role() != Role::CheckBox).expect("group heading").rect(); + assert!(heading.bottom() <= first.top() + 0.5, "{title}: the heading is above its checkboxes"); + remaining = rest; } + assert!(!pane.contains(boxes.last().unwrap().rect.center()), "the last group needs scrolling"); + scroll_to(&mut h, "Count"); + let box_at_bottom = h.query_all_by_role_and_label(Role::CheckBox, "Count").max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + assert!(pane.contains(box_at_bottom.rect().center()), "the last Count can be reached"); + let node = box_at_bottom.accesskit_node(); + let label = node.labelled_by().find(|label| label.role() == Role::Label && label.value().as_deref() == Some("Count")).and_then(|node| node.bounding_box()); + assert!(label.is_some(), "the last Count draws its name"); +} + +#[test] +fn changing_count_in_either_end_of_the_list_updates_all_three_checkboxes() { + let mut h = open_dialog(json!({})); + let states = |h: &H| h.query_all_by_role_and_label(Role::CheckBox, "Count").map(|n| n.accesskit_node().toggled()).collect::>(); + assert_eq!(states(&h), [Some(Toggled::True); 3]); + h.query_all_by_role_and_label(Role::CheckBox, "Count").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + h.run_steps(4); + assert_eq!(states(&h), [Some(Toggled::False); 3]); + + scroll_to(&mut h, "Count"); + h.query_all_by_role_and_label(Role::CheckBox, "Count").max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + h.run_steps(4); + assert_eq!(states(&h), [Some(Toggled::True); 3]); } #[test] @@ -102,13 +126,14 @@ fn select_data_points_disables_ok_and_enter_until_a_point_is_checked() { let mut h = open_dialog(json!({"selection": [], "ruler": ["length"], "count": []})); assert!(!h.get_by_role_and_label(Role::Button, "OK").accesskit_node().is_disabled()); + scroll_to(&mut h, "Angle"); h.get_by_role_and_label(Role::CheckBox, "Length").click(); h.run_steps(4); assert!(h.get_by_role_and_label(Role::Button, "OK").accesskit_node().is_disabled(), "no points are checked"); h.key_press(egui::Key::Enter); h.run_steps(4); assert!(h.query_by_role_and_label(Role::CheckBox, "Length").is_some(), "Enter leaves the dialog open"); - assert_eq!(h.state().session.analysis.data_points.ruler, ["length"]); + assert_eq!(h.state().session.analysis.data_points.of("ruler"), ["length"]); h.get_by_role_and_label(Role::CheckBox, "Angle").click(); h.run_steps(4); @@ -116,5 +141,5 @@ fn select_data_points_disables_ok_and_enter_until_a_point_is_checked() { h.get_by_role_and_label(Role::Button, "OK").click(); h.run_steps(4); assert!(h.query_by_role_and_label(Role::CheckBox, "Angle").is_none(), "OK closes the dialog"); - assert_eq!(h.state().session.analysis.data_points.ruler, ["angle"]); + assert_eq!(h.state().session.analysis.data_points.of("ruler"), ["angle"]); } diff --git a/crates/ui-egui/src/tools/analysis/dialogs.rs b/crates/ui-egui/src/tools/analysis/dialogs.rs index 067b50525e..c4e96430ee 100644 --- a/crates/ui-egui/src/tools/analysis/dialogs.rs +++ b/crates/ui-egui/src/tools/analysis/dialogs.rs @@ -2,10 +2,10 @@ //! host, answered through the `ParamFamily` row of `dialogs.rs`. use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; -use craft::ui::display::{Elide, Text}; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::display::{Divider, Elide, Text}; +use craft::ui::layout_components::Stack; use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::{Env, Label, UnitKind}; use photocraft_doc::Document; @@ -41,14 +41,9 @@ impl Kind { } } -/// The data-point sources of the Select Data Points dialog, in column order. -fn sources() -> [(&'static str, &'static str); 3] { - [("selection", tl!("Selections")), ("ruler", tl!("Ruler Tool")), ("count", tl!("Count Tool"))] -} - -/// The field key of the check box of column `column` in `source`. -fn point_key(source: &str, column: &str) -> String { - format!("{source}:{column}") +/// The four group headings paired with the engine's keys, in display order. +fn point_groups() -> impl Iterator { + [tl!("Common"), tl!("Selections"), tl!("Ruler Tool"), tl!("Count Tool")].into_iter().zip(analysis_cmds::DATA_POINT_GROUPS) } /// A "nice" bar length near a fifth of the image width (same rule as the engine default). @@ -73,12 +68,9 @@ pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result { - let points = serde_json::to_value(&app.session.analysis.data_points).unwrap_or_default(); - for (source, _) in sources() { - let chosen: Vec<&str> = points.get(source).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - for column in analysis_cmds::available(source) { - fields.set(point_key(source, column), chosen.contains(&column)); - } + let points = &app.session.analysis.data_points; + for &(key, _) in analysis_cmds::COLUMNS { + fields.set(key, points.contains(key)); } } Kind::ScaleMarker => { @@ -106,9 +98,7 @@ pub(crate) fn command(kind: Kind, f: &DialogFields) -> Option<(&'static str, Val (id, json!({"preset": "custom", "pixelLength": f.number("pixelLength"), "logicalLength": f.number("logicalLength"), "units": f.text("units")})) } Kind::DataPoints => { - let chosen = |source: &str| -> Vec<&'static str> { - analysis_cmds::available(source).into_iter().filter(|c| f.bool(&point_key(source, c)) == Some(true)).collect() - }; + let chosen = |source: &str| -> Vec<&'static str> { analysis_cmds::available(source).into_iter().filter(|c| f.bool(c) == Some(true)).collect() }; (id, json!({"selection": chosen("selection"), "ruler": chosen("ruler"), "count": chosen("count")})) } Kind::ScaleMarker => ( @@ -172,35 +162,35 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { }) } Kind::DataPoints => { - // Full width, with the title over the columns: in a labelled row every check box is named by the row and - // draws no name of its own. - let row = Param::custom("columns", tl!("Data Points"), |ui, fields, _| { + let row = Param::custom("points", tl!("Data Points"), |ui, fields, _| { Stack::new() + .fill_width() .show(ui, |ui, _| { Text::new(Label::from(tl!("Data Points:"))).show(ui); - Row::new().show(ui, |ui, _| { - for (source, title) in sources() { - Stack::new().show(ui, |ui, _| { + let height = 13.0 * ui.spacing().interact_size.y; + Stack::new().fill_width().room_height(height).show(ui, |ui, _| { + Stack::new().fill_width().scroll(Scroll::vertical()).label(tl!("Data Points")).show(ui, |ui, _| { + for (index, (title, keys)) in point_groups().enumerate() { + if index != 0 { + Divider::horizontal().show(ui); + } Text::new(Label::from(title)).show(ui); - for column in analysis_cmds::available(source) { - let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1); - let field = point_key(source, column); - let mut on = fields.bool(&field).unwrap_or(false); - Checkbox::new(Bind::bound(&mut on)).label(name.to_owned()).show(ui); - if fields.bool(&field) != Some(on) { - fields.set(field, on); + for &key in keys { + let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == key).map_or(key, |c| c.1); + let mut on = fields.bool(key).unwrap_or(false); + Checkbox::new(Bind::bound(&mut on)).label(tl!(name).to_owned()).show(ui); + if fields.bool(key) != Some(on) { + fields.set(key, on); } } - }); - } + } + }) }); }) .output }) .full_width(); - let has_points = sources() - .into_iter() - .any(|(source, _)| analysis_cmds::available(source).into_iter().any(|column| fields.bool(&point_key(source, column)) == Some(true))); + let has_points = analysis_cmds::COLUMNS.iter().any(|(key, _)| fields.bool(key) == Some(true)); ParamDialog::command(key, tl!("Select Data Points"), vec![row]).ok_enabled(has_points) } Kind::ScaleMarker => { diff --git a/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs index fffc0f5f7e..5ea538e1d7 100644 --- a/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs +++ b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs @@ -59,8 +59,8 @@ fn set_data_points_opens_select_data_points_whose_ok_only_stores_the_set() { let dialog = app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id).expect("Select Data Points is open"); // The current set: Ruler Length is ticked, Selection Area is not. let fields = serde_json::to_value(app.framework.dialogs.get_by_id::(dialog).unwrap().fields()).unwrap(); - assert_eq!(fields["ruler:length"], json!(true), "{fields}"); - assert_ne!(fields["selection:area"], json!(true), "{fields}"); + assert_eq!(fields["length"], json!(true), "{fields}"); + assert_ne!(fields["area"], json!(true), "{fields}"); crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap(); assert_eq!(rows(&mut app), 0, "its OK records nothing");