Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Keep shape fill and stroke alpha through PSD round-trip (#6180) (#6868)

Vikram Bhaskaran74ada29c1224
diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs
index 1ae5e1fff..3e804a7ed 100644
--- a/crates/io/src/blocks.rs
+++ b/crates/io/src/blocks.rs
@@ -182,6 +182,17 @@ pub fn color_from_desc(d: &Descriptor) -> Option<Color> {
Color::rgb(g("Rd ")? / 255.0, g("Grn ")? / 255.0, g("Bl ")? / 255.0)
}
})
+ .map(|c| with_pc_alpha(c, d))
+}
+
+/// PSD colour descriptors have no alpha. PhotoCraft writes `pcAl` (0..1) so shape fill
+/// opacity round-trips (#6180). Photoshop ignores the key.
+fn with_pc_alpha(mut c: Color, d: &Descriptor) -> Color {
+ // A hostile file's NaN or infinity would survive the clamp: keep the colour opaque instead.
+ if let Some(a) = num(d.get("pcAl")).filter(|a| a.is_finite()) {
+ c.alpha = (a as f32).clamp(0.0, 1.0);
+ }
+ c
}
/// [`Color`] → descriptor in its own model.
@@ -204,6 +215,13 @@ pub fn color_to_desc(c: &Color) -> Descriptor {
}
}
+/// Solid shape fills have no other alpha slot. Write `pcAl` only here so gradient stops
+/// keep using `Trns` alone (#6180).
+fn color_to_desc_with_pc_alpha(c: &Color) -> Descriptor {
+ let desc = color_to_desc(c);
+ if c.alpha.is_finite() && (c.alpha - 1.0).abs() > 1e-6 { desc.with("pcAl", Value::Double(f64::from(c.alpha.clamp(0.0, 1.0)))) } else { desc }
+}
+
pub(crate) fn get_desc<'a>(d: &'a Descriptor, key: &str) -> Option<&'a Descriptor> {
match d.get(key)? {
Value::Descriptor(x) | Value::GlobalObject(x) => Some(x),
@@ -499,7 +517,7 @@ pub fn write_fill(f: &Fill) -> ([u8; 4], Vec<u8>) {
/// A fill as (block key, descriptor with class `null`).
pub fn fill_to_desc(f: &Fill) -> ([u8; 4], Descriptor) {
match f {
- Fill::Solid(c) => (*b"SoCo", Descriptor::new("null").with("Clr ", Value::Descriptor(color_to_desc(c)))),
+ Fill::Solid(c) => (*b"SoCo", Descriptor::new("null").with("Clr ", Value::Descriptor(color_to_desc_with_pc_alpha(c)))),
Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => {
let prc = |v: f32| Value::UnitFloat { unit: *b"#Prc", value: f64::from(v * 100.0) };
let mut d = Descriptor::new("null")
@@ -991,6 +1009,55 @@ mod tests {
assert!(super::color_from_desc(&Descriptor::new("HSBC").with("Strt", Value::Double(50.0))).is_none());
}
+ #[test]
+ fn color_descriptor_keeps_photocraft_alpha() {
+ use photocraft_color::Color;
+ use photocraft_doc::Fill;
+ let c = Color::rgba(0.2, 0.4, 0.6, 0.25);
+ let (k, d) = super::fill_to_desc(&Fill::Solid(c));
+ let Fill::Solid(back) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") };
+ assert!((back.alpha - 0.25).abs() < 1e-5);
+ assert!((back.to_rgb()[0] - 0.2).abs() < 1e-3);
+ let (k, d) = super::fill_to_desc(&Fill::Solid(Color::rgb(1.0, 0.0, 0.0)));
+ let Fill::Solid(opaque) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") };
+ assert!((opaque.alpha - 1.0).abs() < 1e-6);
+ assert!(super::color_to_desc(&c).get("pcAl").is_none(), "generic colour descriptors have no pcAl");
+ }
+
+ #[test]
+ fn non_finite_photocraft_alpha_is_ignored() {
+ use photocraft_color::Color;
+ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(bad));
+ let c = super::color_from_desc(&d).unwrap();
+ assert_eq!(c.alpha, 1.0, "pcAl {bad}");
+ }
+ let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(0.5));
+ assert!((super::color_from_desc(&d).unwrap().alpha - 0.5).abs() < 1e-6);
+ }
+
+ #[test]
+ fn gradient_stop_alpha_round_trips_once() {
+ use photocraft_color::Color;
+ use photocraft_doc::Fill;
+ let fill = Fill::Gradient {
+ stops: vec![(0.0, Color::rgba(1.0, 0.0, 0.0, 0.5)), (1.0, Color::WHITE)],
+ angle: 90.0,
+ scale: 1.0,
+ style: photocraft_doc::GradientStyle::Linear,
+ reverse: false,
+ opacity_stops: vec![],
+ midpoints: vec![],
+ offset: (0.0, 0.0),
+ dither: false,
+ align: true,
+ };
+ let (k, d) = super::fill_to_desc(&fill);
+ let Fill::Gradient { stops, opacity_stops, .. } = super::fill_from_desc(&k, &d).unwrap() else { panic!("grad") };
+ assert!((stops[0].1.alpha - 1.0).abs() < 1e-4, "colour alpha lives in Trns, not the stop colour");
+ assert!(opacity_stops.iter().any(|(_, a)| (*a - 0.5).abs() < 1e-3), "{opacity_stops:?}");
+ }
+
#[test]
fn blending_ranges_map_to_blend_if() {
use photocraft_doc::{BlendIf, BlendRange};
diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs
index bb830dbd6..621edf47b 100644
--- a/crates/io/src/vector_map.rs
+++ b/crates/io/src/vector_map.rs
@@ -258,10 +258,20 @@ pub fn parse_vstk(data: &[u8], dpi: f32) -> Option<VstkInfo> {
_ => Vec::new(),
};
let paint = get_desc(&d, "strokeStyleContent").and_then(content_fill).unwrap_or(Fill::Solid(photocraft_color::Color::BLACK));
+ let mut opacity = num(d.get("strokeStyleOpacity")).map_or(1.0, |v| v as f32 / 100.0);
+ // Write folds colour alpha into strokeStyleOpacity for Photoshop. Restore both Appearance
+ // fields when pcAl is present so PhotoCraft does not show a maxed colour alpha (#6180).
+ if let Fill::Solid(c) = &paint
+ && c.alpha.is_finite()
+ && c.alpha > 1e-6
+ && (c.alpha - 1.0).abs() > 1e-6
+ {
+ opacity = (opacity / c.alpha).clamp(0.0, 1.0);
+ }
let stroke = ShapeStroke {
width: unit_px(d.get("strokeStyleLineWidth"), dpi).unwrap_or(1.0) as f32,
paint,
- opacity: num(d.get("strokeStyleOpacity")).map_or(1.0, |v| v as f32 / 100.0),
+ opacity,
align,
cap,
join,
@@ -276,10 +286,28 @@ fn en(ty: &str, v: &str) -> Value {
Value::Enumerated { type_id: Id::new(ty), value: Id::new(v) }
}
+/// Photoshop's stroke colour has no alpha. Fold the colour's alpha into `strokeStyleOpacity`
+/// so Appearance still matches after a PSD round-trip (#6180).
+fn fold_stroke_color_alpha(s: &ShapeStroke) -> ShapeStroke {
+ let mut out = s.clone();
+ if let Fill::Solid(c) = &mut out.paint
+ && c.alpha.is_finite()
+ && (c.alpha - 1.0).abs() > 1e-6
+ {
+ out.opacity = (out.opacity * c.alpha).clamp(0.0, 1.0);
+ c.alpha = 1.0;
+ }
+ out
+}
+
pub fn vstk_bytes(stroke: Option<&ShapeStroke>, fill_enabled: bool, dpi: f32) -> Vec<u8> {
let default = ShapeStroke::default();
- let s = stroke.unwrap_or(&default);
- let (_, content) = fill_to_desc(&s.paint);
+ let folded = stroke.map(fold_stroke_color_alpha);
+ let s = folded.as_ref().unwrap_or(&default);
+ // Keep pcAl on the original colour so Appearance can restore fill/stroke alphas separately
+ // from the folded Photoshop opacity (#6180).
+ let paint = stroke.map(|st| &st.paint).unwrap_or(&s.paint);
+ let (_, content) = fill_to_desc(paint);
let class = match s.paint {
Fill::Solid(_) => "solidColorLayer",
Fill::Gradient { .. } => "gradientLayer",
@@ -660,6 +688,20 @@ mod tests {
assert!(off.stroke.is_none() && off.fill_enabled);
}
+ #[test]
+ fn vstk_folds_color_alpha_into_stroke_opacity() {
+ let s = ShapeStroke { width: 2.0, paint: Fill::Solid(Color::rgba(0.0, 0.0, 1.0, 0.4)), opacity: 0.5, ..ShapeStroke::default() };
+ let bytes = vstk_bytes(Some(&s), true, 72.0);
+ let raw = crate::blocks::parse_prefix_versioned(&bytes).unwrap();
+ let file_opacity = crate::blocks::num(raw.get("strokeStyleOpacity")).unwrap() as f32 / 100.0;
+ assert!((file_opacity - 0.2).abs() < 1e-4, "Photoshop sees the product in strokeStyleOpacity");
+ let got = parse_vstk(&bytes, 72.0).unwrap().stroke.unwrap();
+ assert!((got.opacity - 0.5).abs() < 1e-4);
+ let Fill::Solid(c) = got.paint else { panic!("solid") };
+ assert!((c.alpha - 0.4).abs() < 1e-5);
+ assert!((c.to_rgb()[2] - 1.0).abs() < 1e-3);
+ }
+
#[test]
fn vogk_roundtrip() {
for s in [
diff --git a/crates/io/tests/it/vector.rs b/crates/io/tests/it/vector.rs
index e32cbed3f..71bf66823 100644
--- a/crates/io/tests/it/vector.rs
+++ b/crates/io/tests/it/vector.rs
@@ -135,6 +135,37 @@ fn shape_layer_typed_roundtrip() {
}
}
+/// #6180: Appearance fill and stroke alphas survive PSD save/load, and a redraw
+/// (move/crop) uses those values instead of snapping to opaque.
+#[test]
+fn rectangle_appearance_alphas_survive_psd_and_redraw() {
+ let mut d = doc();
+ let sh = ShapeLayer {
+ path: photocraft_vector::shapes::rect(16.0, 16.0, 128.0, 96.0),
+ fill: Some(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5))),
+ stroke: Some(ShapeStroke { width: 4.0, paint: Fill::Solid(Color::rgba(0.0, 0.0, 1.0, 0.4)), opacity: 0.5, ..ShapeStroke::default() }),
+ live: Some(LiveShape::Rect { rect: [16.0, 16.0, 128.0, 96.0], radii: [0.0; 4] }),
+ ..Default::default()
+ };
+ d.layers.push(shape_layer(sh));
+ let b = roundtrip(&d);
+ let LayerContent::Shape(s) = &b.layers[1].content else { panic!("not a shape") };
+ let Fill::Solid(fill) = s.fill.as_ref().unwrap() else { panic!("solid fill") };
+ assert!((fill.alpha - 0.5).abs() < 1e-4, "fill appearance alpha {}", fill.alpha);
+ let st = s.stroke.as_ref().unwrap();
+ let Fill::Solid(stroke_c) = &st.paint else { panic!("solid stroke") };
+ assert!((stroke_c.alpha - 0.4).abs() < 1e-4, "stroke colour alpha {}", stroke_c.alpha);
+ assert!((st.opacity - 0.5).abs() < 1e-4, "stroke opacity {}", st.opacity);
+ let mut redrawn = s.clone();
+ redrawn.cache = Some(photocraft_vector::render_shape(&redrawn, photocraft_color::PixelFormat::RGBA8, Rect::new(0, 0, 256, 256)));
+ let Fill::Solid(fill2) = redrawn.fill.as_ref().unwrap() else { panic!("solid fill") };
+ assert!((fill2.alpha - 0.5).abs() < 1e-4);
+ let st2 = redrawn.stroke.as_ref().unwrap();
+ let Fill::Solid(stroke2) = &st2.paint else { panic!("solid stroke") };
+ assert!((stroke2.alpha - 0.4).abs() < 1e-4);
+ assert!((st2.opacity - 0.5).abs() < 1e-4);
+}
+
#[test]
fn custom_stroke_styles_roundtrip_through_psd_vstk() {
for align in [StrokeAlign::Inside, StrokeAlign::Center, StrokeAlign::Outside] {