mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # crates/engine/src/cmd/channel_cmds/calc.rs
This commit is contained in:
commit
9dffd99892
9 files changed
+499
-34
No files matched your search
@@ -121,6 +121,9 @@ mod targeting;
|
||||
mod tone_target;
|
||||
mod view;
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_image_locked_layer_tests;
|
||||
|
||||
use calc::{apply_image, calculations};
|
||||
use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible};
|
||||
use planes::edit_mode;
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! Apply Image on a fully locked or pixel-locked layer: it applies, and the layer keeps its
|
||||
//! transparency as with Preserve transparency (#14476).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The spec's test document "target" (400 x 300): layer "Top" is empty except a 100 x 100 square
|
||||
/// at (150,100) of 0/255/0 at alpha 128. Document "source" is 128/128/128 on the left half and
|
||||
/// white on the right half.
|
||||
fn session(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "target"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 150, "y": 100, "width": 100, "height": 100, "mode": "replace"})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 128.0 / 255.0 * 100.0})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "source"})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300, "mode": "replace"})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.set_active(0);
|
||||
s
|
||||
}
|
||||
|
||||
fn apply() -> Value {
|
||||
json!({"source": {"document": 1}, "blending": "normal", "opacity": 100})
|
||||
}
|
||||
|
||||
fn layer(s: &Session) -> &Layer {
|
||||
let d = s.active().unwrap();
|
||||
d.doc.layer(d.active_layer.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn pixels(s: &Session) -> Vec<f32> {
|
||||
let d = s.active().unwrap();
|
||||
layer(s).surface().unwrap().read_region(d.doc.bounds())
|
||||
}
|
||||
|
||||
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
|
||||
layer(s).surface().unwrap().pixel(x, y)
|
||||
}
|
||||
|
||||
fn close(a: &[f32], b: &[f32]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
|
||||
}
|
||||
|
||||
fn lock(s: &mut Session, locks: &Value) {
|
||||
s.execute("layer.setProps", json!({"locks": locks})).unwrap();
|
||||
}
|
||||
|
||||
const LOCKS: [&str; 2] = [r#"{"all": true}"#, r#"{"pixels": true}"#];
|
||||
|
||||
fn locks() -> impl Iterator<Item = Value> {
|
||||
LOCKS.iter().map(|l| serde_json::from_str(l).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_layer_takes_the_image_in_one_step_and_keeps_its_transparency() {
|
||||
for depth in [8, 16, 32] {
|
||||
for locks in locks() {
|
||||
let mut s = session(depth);
|
||||
lock(&mut s, &locks);
|
||||
let before = px(&s, 175, 125);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute("image.applyImage", apply()).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
assert_eq!(d.history.past_len(), steps + 1, "{depth} bit {locks}: one history step");
|
||||
assert_eq!(d.history.undo_label(), Some("Apply Image"), "{depth} bit {locks}");
|
||||
assert!(!close(&px(&s, 175, 125), &before), "{depth} bit {locks}: (175,125) changes");
|
||||
assert_eq!(px(&s, 50, 50), vec![0.0; 4], "{depth} bit {locks}: (50,50) stays transparent");
|
||||
assert!((px(&s, 175, 125)[3] - before[3]).abs() < 1e-5, "{depth} bit {locks}: the square keeps its alpha");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_layer_gets_the_preserve_transparency_result() {
|
||||
for depth in [8, 16, 32] {
|
||||
for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] {
|
||||
let with = |p: Value| {
|
||||
let mut p = p;
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
p
|
||||
};
|
||||
let mut want = session(depth);
|
||||
let mut p = with(apply());
|
||||
p["preserveTransparency"] = json!(true);
|
||||
want.execute("image.applyImage", p).unwrap();
|
||||
for locks in locks() {
|
||||
let mut s = session(depth);
|
||||
lock(&mut s, &locks);
|
||||
s.execute("image.applyImage", with(apply())).unwrap();
|
||||
assert!(close(&pixels(&s), &pixels(&want)), "{depth} bit {locks} {extra}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_locks_stay_and_other_commands_keep_refusing() {
|
||||
for locks in locks() {
|
||||
let mut s = session(8);
|
||||
lock(&mut s, &locks);
|
||||
let set = layer(&s).locks;
|
||||
s.execute("image.applyImage", apply()).unwrap();
|
||||
assert_eq!(layer(&s).locks, set, "{locks}: the lock flags are unchanged");
|
||||
let after = pixels(&s);
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
let fill = s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap_err().to_string();
|
||||
assert!(fill.contains("is locked"), "{locks}: Fill refuses: {fill}");
|
||||
let stroke = s.execute("paint.stroke", json!({"points": [[160, 110], [240, 190]], "size": 20})).unwrap_err().to_string();
|
||||
assert!(stroke.contains("is locked"), "{locks}: a brush stroke refuses: {stroke}");
|
||||
assert!(close(&pixels(&s), &after), "{locks}: nothing else painted");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps, "{locks}: no more steps");
|
||||
s.undo();
|
||||
assert!(close(&pixels(&s), &pixels(&session(8))), "{locks}: undo restores the layer");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lock_from_a_group_still_refuses() {
|
||||
// Not measured in the reference application: keeps today's refusal, also when the layer is
|
||||
// locked itself as well.
|
||||
for own in [None, Some(json!({"pixels": true})), Some(json!({"all": true}))] {
|
||||
let mut s = session(8);
|
||||
let top = s.active().unwrap().active_layer.unwrap();
|
||||
if let Some(own) = &own {
|
||||
lock(&mut s, own);
|
||||
}
|
||||
s.execute("layer.new.groupFromLayers", json!({})).unwrap();
|
||||
lock(&mut s, &json!({"all": true}));
|
||||
s.set_active_layer(Some(top));
|
||||
let before = pixels(&s);
|
||||
let err = s.execute("image.applyImage", apply()).unwrap_err().to_string();
|
||||
assert!(err.contains("is locked"), "{own:?}: {err}");
|
||||
assert!(close(&pixels(&s), &before), "{own:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unlocked_layer_keeps_source_over() {
|
||||
let mut s = session(8);
|
||||
s.execute("image.applyImage", apply()).unwrap();
|
||||
let p = px(&s, 50, 50);
|
||||
let g = 128.0 / 255.0;
|
||||
assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{p:?}");
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! #14473: Apply Image with Preserve Transparency gives a semi-transparent pixel the full blend
|
||||
//! result and keeps its alpha, as the reference application does.
|
||||
|
||||
use crate::Session;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Target "target" (document 0): white Background, layer "Top" transparent except a 0/255/0
|
||||
/// square at alpha 128 over (10,4)-(19,13). Source "source" (document 1): 128/128/128.
|
||||
fn session(depth: u32) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "target"})).unwrap();
|
||||
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
|
||||
s.set_active(0);
|
||||
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 10, "y": 4, "width": 10, "height": 10, "mode": "replace"})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#00ff00", "opacity": 50})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
|
||||
let d = s.active().unwrap();
|
||||
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
|
||||
}
|
||||
|
||||
fn apply(s: &mut Session, extra: Value) {
|
||||
let mut p = json!({"source": {"document": 1, "layer": "merged", "channel": "composite"}});
|
||||
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
p.extend(extra.clone());
|
||||
}
|
||||
s.execute("image.applyImage", p).unwrap();
|
||||
}
|
||||
|
||||
/// Checks RGBA in 0..=255 levels, one level of slack (the fill's 50% alpha is 127.5).
|
||||
fn assert_rgba(got: &[f32], want: [f32; 4], what: &str) {
|
||||
let got: Vec<f32> = got.iter().map(|v| v * 255.0).collect();
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.01), "{what}: {got:?}, want {want:?}");
|
||||
}
|
||||
|
||||
const GRAY: f32 = 128.0;
|
||||
const HALF: f32 = 127.5;
|
||||
|
||||
#[test]
|
||||
fn normal_with_preserve_transparency_takes_the_source_and_keeps_alpha() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true}));
|
||||
assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, HALF], &format!("depth {depth}: green pixel"));
|
||||
assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiply_with_preserve_transparency_blends_fully_and_keeps_alpha() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
apply(&mut s, json!({"blending": "multiply", "preserveTransparency": true}));
|
||||
assert_rgba(&px(&s, 15, 8), [0.0, GRAY, 0.0, HALF], &format!("depth {depth}: green pixel"));
|
||||
assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_selection_still_scale_the_preserved_blend() {
|
||||
let mut s = session(8);
|
||||
// 50% Normal: the colour moves half way to the source, the alpha stays.
|
||||
apply(&mut s, json!({"blending": "normal", "opacity": 50, "preserveTransparency": true}));
|
||||
assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "opacity 50");
|
||||
s.undo();
|
||||
// Outside the selection nothing changes.
|
||||
s.execute("select.rect", json!({"x": 10, "y": 4, "width": 5, "height": 10, "mode": "replace"})).unwrap();
|
||||
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true}));
|
||||
assert_rgba(&px(&s, 12, 8), [GRAY, GRAY, GRAY, HALF], "inside the selection");
|
||||
assert_rgba(&px(&s, 17, 8), [0.0, 255.0, 0.0, HALF], "outside the selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_still_scales_the_preserved_blend() {
|
||||
let mut s = session(8);
|
||||
// A 50% gray alpha channel as the mask halves the effect, like 50% opacity.
|
||||
s.execute("channel.new", json!({"fill": "white"})).unwrap();
|
||||
s.execute("channel.target", json!({"channel": 0})).unwrap();
|
||||
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
|
||||
s.execute("channel.target", json!({"channel": "composite"})).unwrap();
|
||||
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true, "mask": {"document": 0, "channel": 0}}));
|
||||
assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "mask at 50%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_preserve_transparency_the_results_stay() {
|
||||
let mut s = session(8);
|
||||
apply(&mut s, json!({"blending": "normal"}));
|
||||
assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, 255.0], "normal, green pixel");
|
||||
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "normal, transparent pixel");
|
||||
s.undo();
|
||||
apply(&mut s, json!({"blending": "multiply"}));
|
||||
assert_rgba(&px(&s, 15, 8), [64.0, GRAY, 64.0, 255.0], "multiply, green pixel");
|
||||
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "multiply, transparent pixel");
|
||||
s.undo();
|
||||
apply(&mut s, json!({"blending": "normal", "opacity": 50}));
|
||||
assert_rgba(&px(&s, 15, 8), [85.0, 170.0, 85.0, 191.5], "normal 50%, green pixel");
|
||||
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, HALF], "normal 50%, transparent pixel");
|
||||
}
|
||||
@@ -5,6 +5,10 @@ use super::targeting::{Target, is_channel_target, is_spot_target, target_of, tar
|
||||
use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel};
|
||||
use photocraft_color::blend::blend_rgb;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "apply_image_preserve_tests.rs"]
|
||||
mod apply_image_preserve_tests;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Apply Image / Calculations
|
||||
|
||||
@@ -59,7 +63,18 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
|
||||
let fmt = doc.pixel_format();
|
||||
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
|
||||
// A fully locked or pixel-locked layer still takes the image, as in the reference
|
||||
// application, and keeps its transparency as with Preserve transparency. A lock that comes
|
||||
// from a group around it still refuses, through `paint_surface`.
|
||||
let own = doc.layer(id).map(|l| l.locks).unwrap_or_default();
|
||||
let groups = doc.path_of(id).map_or_else(Default::default, |p| doc.locks_at(p.get(..p.len().saturating_sub(1)).unwrap_or_default()));
|
||||
let locked = (own.pixels || own.all) && !(groups.pixels || groups.all);
|
||||
let preserve = preserve || locked;
|
||||
let surf = if locked {
|
||||
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?
|
||||
} else {
|
||||
crate::commands::paint_surface(doc, id, &Value::Null)?
|
||||
};
|
||||
let sf = surf.format();
|
||||
if sf != fmt {
|
||||
return Err(EngineError::Other("the target layer's format doesn't match the document".into()));
|
||||
@@ -74,11 +89,9 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut v = surf.read_region(area);
|
||||
for (i, px) in v.chunks_exact_mut(n).enumerate() {
|
||||
let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 };
|
||||
let mut w = weight(i);
|
||||
if preserve {
|
||||
w *= base_a;
|
||||
}
|
||||
if w <= 0.0 {
|
||||
let w = weight(i);
|
||||
// Preserve Transparency leaves transparent pixels as they are.
|
||||
if w <= 0.0 || (preserve && base_a <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
// Painted over the layer like a brush: the blend only acts where the layer has
|
||||
@@ -100,8 +113,17 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let top = top_of(c);
|
||||
let base = tone(sf.mode, *b);
|
||||
let mixed = picked.and_then(|p| p.get(c).copied()).unwrap_or_else(|| blending.apply(base, top));
|
||||
let blended = top + (mixed - top) * base_a;
|
||||
*b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a });
|
||||
// With Preserve Transparency the colour takes the full blend and only the alpha
|
||||
// stays the layer's (a pixel at 50% alpha turns fully to the source in Normal).
|
||||
*b = tone(
|
||||
sf.mode,
|
||||
if preserve {
|
||||
base + (mixed - base) * w
|
||||
} else {
|
||||
let blended = top + (mixed - top) * base_a;
|
||||
(w * blended + base_a * (1.0 - w) * base) / out_a
|
||||
},
|
||||
);
|
||||
}
|
||||
if sf.alpha {
|
||||
px[colors] = out_a;
|
||||
|
||||
@@ -9,14 +9,10 @@ use photocraft_geom::Affine;
|
||||
|
||||
/// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of
|
||||
/// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored).
|
||||
pub fn parse_brst(data: &[u8]) -> u32 {
|
||||
data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i)
|
||||
}
|
||||
pub use craft_psd::tagged::channel_restrictions as parse_brst;
|
||||
|
||||
/// Inverse of [`parse_brst`]; `None` when every channel blends (no block).
|
||||
pub fn brst_data(mask: u32) -> Option<Vec<u8>> {
|
||||
(mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect())
|
||||
}
|
||||
pub use craft_psd::tagged::channel_restrictions_data as brst_data;
|
||||
|
||||
/// The Advanced Blending blocks, as (key, value for `a`, Photoshop's default value): `knko`
|
||||
/// (0 none, 1 shallow, 2 deep), `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`. Each is stored as one
|
||||
|
||||
@@ -609,7 +609,7 @@ impl Ex<'_> {
|
||||
None => raw.retain(|(k, _)| k != b"fxrp"),
|
||||
}
|
||||
// Advanced Blending channel restrictions: written from the field (in place).
|
||||
match crate::blocks::brst_data(l.excluded_channels) {
|
||||
match craft_psd::tagged::channel_restrictions_data(l.excluded_channels) {
|
||||
Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") {
|
||||
Some(e) => e.1 = data,
|
||||
None => raw.push((*b"brst", data)),
|
||||
|
||||
@@ -479,7 +479,7 @@ impl Ctx<'_> {
|
||||
// Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out);
|
||||
// also kept in `psd_blocks`, where export rewrites it from the field.
|
||||
if let Some(b) = rec.block(b"brst") {
|
||||
l.excluded_channels = crate::blocks::parse_brst(&b.data);
|
||||
l.excluded_channels = craft_psd::tagged::channel_restrictions(&b.data);
|
||||
}
|
||||
// Advanced Blending (`knko`, `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`); the blocks stay in
|
||||
// `psd_blocks`, where export rewrites them from the field in place.
|
||||
|
||||
@@ -474,6 +474,58 @@ fn channel_restrictions_round_trip_as_brst() {
|
||||
assert!(f.layers().iter().find(|r| r.name() == "a").unwrap().block(b"brst").is_none());
|
||||
}
|
||||
|
||||
fn channel_restrictions_psd(payload: Vec<u8>) -> Vec<u8> {
|
||||
use craft_psd::{LayerSpec, PixelData, PsdBuilder, TaggedBlock};
|
||||
let mut layer = LayerSpec::new("restricted", 0, 0, 1, 1, PixelData::Rgba8(vec![80, 120, 160, 255]));
|
||||
layer.extra_blocks = vec![TaggedBlock::new(*b"zBef", vec![1, 2, 3, 4]), TaggedBlock::new(*b"brst", payload), TaggedBlock::new(*b"zAft", vec![5, 6, 7, 8])];
|
||||
let mut builder = PsdBuilder::new(1, 1);
|
||||
builder.push_layer(layer);
|
||||
builder.composite(PixelData::Rgba8(vec![80, 120, 160, 255]));
|
||||
builder.to_bytes().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_restrictions_partial_records_preserve_valid_indices_and_neighboring_blocks() {
|
||||
for trailing in [vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc]] {
|
||||
// The complete indices are 31, 32, 0, 31: 32 is ignored and 31 is a duplicate.
|
||||
let mut payload = vec![0, 0, 0, 31, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 31];
|
||||
payload.extend(trailing);
|
||||
let bytes = channel_restrictions_psd(payload.clone());
|
||||
let document = import("restrictions.psd", &bytes).unwrap().document;
|
||||
let layer = document.layers.iter().find(|layer| layer.name == "restricted").unwrap();
|
||||
assert_eq!(layer.excluded_channels, 0x8000_0001);
|
||||
assert!(layer.psd_blocks.iter().any(|(key, data)| key == b"brst" && data.as_slice() == payload));
|
||||
|
||||
let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
let file = PsdFile::from_bytes(&saved).unwrap();
|
||||
let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap();
|
||||
let preserved: Vec<_> = record.blocks.iter().filter(|block| [*b"zBef", *b"brst", *b"zAft"].contains(&block.key)).collect();
|
||||
assert_eq!(preserved.iter().map(|block| block.key).collect::<Vec<_>>(), vec![*b"zBef", *b"brst", *b"zAft"]);
|
||||
assert_eq!(preserved[0].data, vec![1, 2, 3, 4]);
|
||||
assert_eq!(preserved[1].data, vec![0, 0, 0, 0, 0, 0, 0, 31]);
|
||||
assert_eq!(preserved[2].data, vec![5, 6, 7, 8]);
|
||||
let reopened = import("restrictions.psd", &saved).unwrap().document;
|
||||
assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0x8000_0001);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_restrictions_without_valid_records_are_omitted() {
|
||||
for payload in [vec![], vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc], vec![0, 0, 0, 32, 255, 255, 255, 255]] {
|
||||
let bytes = channel_restrictions_psd(payload);
|
||||
let document = import("restrictions.psd", &bytes).unwrap().document;
|
||||
assert_eq!(document.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0);
|
||||
let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes;
|
||||
let file = PsdFile::from_bytes(&saved).unwrap();
|
||||
let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap();
|
||||
assert!(record.block(b"brst").is_none());
|
||||
assert_eq!(record.block(b"zBef").unwrap().data, vec![1, 2, 3, 4]);
|
||||
assert_eq!(record.block(b"zAft").unwrap().data, vec![5, 6, 7, 8]);
|
||||
let reopened = import("restrictions.psd", &saved).unwrap().document;
|
||||
assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Advanced Blending maps to `knko` / `infx` / `clbl` / `tsly` / `lmgm` / `vmgm` (one byte +
|
||||
/// three of padding), at every depth: non-default values are written, default layers gain no
|
||||
/// blocks, and imported blocks are rewritten in place.
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! #127: every shortcut the UI displays (menu items, shell commands, tool tooltips) dispatches its
|
||||
//! command, or the item is visibly disabled with a reason — through the whole app, with a
|
||||
//! realistic layered document, from the places focus usually is.
|
||||
//! command, or the item is visibly disabled with a reason, in the whole app with a realistic layered
|
||||
//! document. Every shortcut's command is fired into the dispatcher directly; one shortcut of each kind
|
||||
//! of key and route is pressed from the places focus usually is (#15678).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft::keymap::Chord;
|
||||
use craft::ui::runtime::focus;
|
||||
@@ -204,11 +207,146 @@ fn displayed(app: &PhotocraftApp) -> Vec<(String, String, bool)> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Press every displayed shortcut from each place focus usually is: each dispatches its command,
|
||||
/// or the menu shows it disabled and the press reports why. (Dry run: File › Exit, Open, Help
|
||||
/// The way [`super::run_fired`] takes a fired command `id`: a row of [`super::RUNTIME_COMMANDS`] by its kind, a tool
|
||||
/// letter, a Shift+letter group step, a recorded action, else an app command through [`super::dispatch_as`].
|
||||
fn route(id: &str) -> String {
|
||||
if let Some((_, bridged)) = super::RUNTIME_COMMANDS.iter().find(|(row, _)| *row == id) {
|
||||
let kind = format!("{bridged:?}");
|
||||
return kind.split('(').next().unwrap_or(&kind).to_string();
|
||||
}
|
||||
if crate::tool_shortcuts::tool(id).is_some() {
|
||||
"tool".into()
|
||||
} else if super::next_in_group_letter(id).is_some() {
|
||||
"group".into()
|
||||
} else if id.starts_with(crate::actions::SHORTCUT_PREFIX) {
|
||||
"action".into()
|
||||
} else {
|
||||
"app".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press of `chord` shares with every other chord of its group: the keyboard path (the runtime's key stage,
|
||||
/// a focused field's typing rule, a focused component's held keys) depends on the kind of key and the modifiers,
|
||||
/// not on the command. Letters, digits and function keys are one kind each; every other key is its own kind.
|
||||
fn key_kind(chord: &Chord) -> String {
|
||||
let key = chord.key;
|
||||
let kind = if key.is_letter() {
|
||||
"letter".to_string()
|
||||
} else if key.is_digit() {
|
||||
"digit".to_string()
|
||||
} else if key.is_function_key() {
|
||||
"function".to_string()
|
||||
} else {
|
||||
format!("{key:?}")
|
||||
};
|
||||
let m = chord.mods;
|
||||
format!("{kind} cmd={} ctrl={} alt={} shift={}", m.cmd, m.ctrl, m.alt, m.shift)
|
||||
}
|
||||
|
||||
/// Every live displayed shortcut (id, text) and its chord.
|
||||
fn live_chords(app: &PhotocraftApp) -> Vec<(String, String, Chord)> {
|
||||
displayed(app)
|
||||
.into_iter()
|
||||
.filter(|(_, _, live)| *live)
|
||||
.map(|(id, sc, _)| {
|
||||
let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}"));
|
||||
(id, sc, chord)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One displayed shortcut per (route, kind of key, modifiers): the shortcuts whose press goes the same way.
|
||||
fn representatives(app: &PhotocraftApp) -> Vec<(String, String, Chord)> {
|
||||
let mut seen = HashSet::new();
|
||||
live_chords(app).into_iter().filter(|(id, _, chord)| seen.insert((route(id), key_kind(chord)))).collect()
|
||||
}
|
||||
|
||||
/// The command the runtime fires for `chord`, shown for menu row `id`: the row's own command when the keymap shows
|
||||
/// the chord for it (no other command wins it where the binding applies), else the key's holder.
|
||||
fn fired_by(ctx: &egui::Context, id: &str, chord: &Chord) -> Option<craft::ui::runtime::commands::CommandRef> {
|
||||
let own = super::keymap_command(id);
|
||||
if craft::ui::runtime::commands::chord(ctx, &own) == Some(*chord) {
|
||||
return Some(own);
|
||||
}
|
||||
// `holder` answers with no panel active; it falls back to a panel's binding when no unscoped command holds the key.
|
||||
craft::ui::runtime::commands::holder(ctx, chord)
|
||||
}
|
||||
|
||||
/// Every displayed shortcut runs its menu item's command, or the menu shows the item disabled and the shortcut
|
||||
/// says why: the keymap's command for each chord is fired into [`super::run_fired`] as a key press, with no key
|
||||
/// events and no frames between them. The keyboard's way to the keymap is the same for every chord of a kind, and
|
||||
/// [`every_kind_of_shortcut_dispatches_from_where_focus_usually_is`] presses one of each. The view, screen-mode,
|
||||
/// momentary, Swatches and Workspace rows run in the runtime, the canvas or the shell instead of `run_fired`; that
|
||||
/// test presses one of each kind of key for them. Every tool letter picks a tool of that letter.
|
||||
#[test]
|
||||
fn every_displayed_shortcut_runs_its_menu_item() {
|
||||
use craft::ui::runtime::commands::{FirePhase, FireSource, Fired};
|
||||
let mut h = harness();
|
||||
set_dry_run(&h.ctx, true);
|
||||
put_focus(&mut h, Place::Canvas);
|
||||
let ctx = h.ctx.clone();
|
||||
let items = crate::menus::menu_rows(h.state());
|
||||
let chords = live_chords(h.state());
|
||||
assert!(chords.len() > 100, "the menus show their shortcuts: {}", chords.len());
|
||||
let fire = |h: &mut Harness<'_, Box<PhotocraftApp>>, command| {
|
||||
super::run_fired(h.state_mut(), &ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]);
|
||||
take_log(&ctx)
|
||||
};
|
||||
let mut failures = Vec::new();
|
||||
let mut fired = 0;
|
||||
for (id, sc, chord) in &chords {
|
||||
let Some(command) = fired_by(&ctx, id, chord) else {
|
||||
failures.push(format!("{sc} ({id}) runs nothing"));
|
||||
continue;
|
||||
};
|
||||
match route(id).as_str() {
|
||||
"View" | "Momentary" | "ScreenMode" | "Swatches" | "Workspace" => {
|
||||
if command != super::keymap_command(id) {
|
||||
failures.push(format!("{sc} ({id}) fires {command:?}"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
"tool" | "group" => {
|
||||
let want = crate::tool_shortcuts::tool(id).map(Tool::key).or_else(|| super::next_in_group_letter(id));
|
||||
fire(&mut h, command);
|
||||
if Some(h.state().ui.tool.key()) != want {
|
||||
failures.push(format!("{sc} ({id}) left {:?}", h.state().ui.tool));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let enabled = items.iter().find(|i| i.command.id == *id).map_or_else(|| crate::menus::is_enabled(h.state(), id), |i| i.enabled);
|
||||
fired += 1;
|
||||
match fire(&mut h, command).as_slice() {
|
||||
[(bound, Outcome::Ran)] if same(id, bound) && enabled => {}
|
||||
[(bound, Outcome::Disabled(why))] if same(id, bound) && !enabled && !why.is_empty() => {}
|
||||
other => failures.push(format!("{sc} ({id}, menu enabled: {enabled}) -> {other:?}")),
|
||||
}
|
||||
}
|
||||
assert!(fired > 80, "most displayed shortcuts go through run_fired: {fired}");
|
||||
for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') {
|
||||
let chord = Chord::parse(&t.key().to_string()).unwrap_or_else(|_| panic!("tool key {}", t.key()));
|
||||
let Some(command) = craft::ui::runtime::commands::holder(&ctx, &chord) else {
|
||||
failures.push(format!("tool key {} runs nothing", t.key()));
|
||||
continue;
|
||||
};
|
||||
h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
|
||||
fire(&mut h, command);
|
||||
if h.state().ui.tool.key() != t.key() {
|
||||
failures.push(format!("tool key {} left {:?}", t.key(), h.state().ui.tool));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} shortcut failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Press one displayed shortcut of each (route, kind of key, modifiers) from each place focus usually is: each
|
||||
/// dispatches its command, or the menu shows it disabled and the press reports why; a focused field keeps its typing
|
||||
/// keys and a focused component the keys it holds. The other shortcuts of a group take the same path to a different
|
||||
/// row of the table [`every_displayed_shortcut_runs_its_menu_item`] checks. (Dry run: File › Exit, Open, Help
|
||||
/// links… resolve and check enablement without running.)
|
||||
#[test]
|
||||
fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
|
||||
fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() {
|
||||
let mut failures = Vec::new();
|
||||
for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] {
|
||||
let mut h = harness();
|
||||
@@ -216,11 +354,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
|
||||
put_focus(&mut h, place);
|
||||
let typing = WindowHost::of(&h.ctx).typing();
|
||||
let items = crate::menus::menu_rows(h.state());
|
||||
for (id, sc, live) in displayed(h.state()) {
|
||||
if !live {
|
||||
continue;
|
||||
}
|
||||
let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}"));
|
||||
for (id, sc, chord) in representatives(h.state()) {
|
||||
// A press the focused component holds (the Layers rows' stacking and visibility keys)
|
||||
// is the component's and reaches no app command.
|
||||
let held = focus_holds(&h.ctx, chord);
|
||||
@@ -241,14 +375,19 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
|
||||
other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")),
|
||||
}
|
||||
}
|
||||
// Tool letters from the tools panel tooltips ("Brush Tool (B)").
|
||||
if !typing {
|
||||
for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') {
|
||||
h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
|
||||
press_in_one_frame(&mut h, &t.key().to_string());
|
||||
if h.state().ui.tool.key() != t.key() {
|
||||
failures.push(format!("{place:?}: tool key {} left {:?}", t.key(), h.state().ui.tool));
|
||||
}
|
||||
// Tool letters from the tools panel tooltips ("Brush Tool (B)"): a letter of one tool and a letter its group
|
||||
// shares take different picks (`pick_tool`); the table checks every letter's tool. In a focused text field the
|
||||
// letter is typed and the tool stays.
|
||||
let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1;
|
||||
let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t));
|
||||
let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t));
|
||||
for t in one.into_iter().chain(many) {
|
||||
let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
|
||||
h.state_mut().ui.tool = start;
|
||||
press_in_one_frame(&mut h, &t.key().to_string());
|
||||
let want = if typing { start } else { t };
|
||||
if h.state().ui.tool.key() != want.key() {
|
||||
failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user