Skip to content

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

CodeRabbit follow-ups for the #8095 batch (#5807, #4816, #7180)

David Mann168701779cdd
diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs
index 5e3e2cda9..14273c2bd 100644
--- a/crates/engine/src/preset_import_cmds.rs
+++ b/crates/engine/src/preset_import_cmds.rs
@@ -92,7 +92,8 @@ fn import_abr(s: &mut Session, p: &Value) -> Result<Value> {
// A background job when started with `Session::start` (#210): reading and decoding the
// file run on a worker, cancellable before each brush; the library changes on apply.
let params = p.clone();
- let params_apply = p.clone();
+ // Only the keys the apply step reads: `data` can be a ~1.3 GiB base64 string.
+ let params_apply = json!({ "replace": p.get("replace"), "select": p.get("select") });
crate::jobs::run(
s,
label,
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs
index 030fe1851..44b6a98be 100644
--- a/crates/engine/src/type_cmds.rs
+++ b/crates/engine/src/type_cmds.rs
@@ -108,7 +108,8 @@ pub fn check_kerning(p: &Value) -> std::result::Result<(), String> {
}
/// Validates text metrics (size, tracking, leading, baseline shift, scales) that can otherwise
-/// exceed the rasterizer's supported range or overflow `f32`, which a .pcraft manifest cannot hold.
+/// exceed the rasterizer's supported range or overflow `f32`, which a .pcraft manifest cannot hold,
+/// and the superscript/subscript `baseline`, so a typo is an error rather than a reset to Normal.
pub fn check_size_tracking(p: &Value) -> std::result::Result<(), String> {
if let Some(v) = p.get("size") {
match v.as_f64() {
@@ -138,6 +139,11 @@ pub fn check_size_tracking(p: &Value) -> std::result::Result<(), String> {
_ => return Err(format!("baselineShift must be between -{max} and {max} pt")),
}
}
+ if let Some(v) = p.get("baseline").filter(|v| !v.is_null())
+ && !matches!(v.as_str(), Some("normal" | "superscript" | "subscript"))
+ {
+ return Err("baseline must be \"normal\", \"superscript\" or \"subscript\"".into());
+ }
for key in ["horizontalScale", "verticalScale"] {
if let Some(v) = p.get(key) {
match v.as_f64() {
@@ -365,12 +371,17 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {
hit(true);
}
if let Some(v) = p.get("baseline").and_then(Value::as_str) {
- s.baseline = match v {
- "superscript" => FontBaseline::Superscript,
- "subscript" => FontBaseline::Subscript,
- _ => FontBaseline::Normal,
+ let baseline = match v {
+ "superscript" => Some(FontBaseline::Superscript),
+ "subscript" => Some(FontBaseline::Subscript),
+ "normal" => Some(FontBaseline::Normal),
+ _ => None,
};
- hit(true);
+ // An unknown value keeps the style (the commands reject it in `check_size_tracking`).
+ if let Some(b) = baseline {
+ s.baseline = b;
+ hit(true);
+ }
}
if let Some(Value::Object(m)) = p.get("features") {
for (tag, v) in m {
@@ -1617,6 +1628,23 @@ mod tests {
assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]);
}
+ /// A misspelt `baseline` is an error and keeps superscript, instead of resetting it to Normal.
+ #[test]
+ fn unknown_baseline_is_rejected_and_keeps_the_style() {
+ let mut s = session();
+ let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "x2", "size": 30})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("type.setStyle", json!({"layer": id, "range": [1, 2], "baseline": "superscript"})).unwrap();
+ let before = text_layer(&s, id).runs;
+ for b in [json!("superscipt"), json!("Superscript"), json!(1)] {
+ assert!(matches!(s.execute("type.setStyle", json!({"layer": id, "baseline": b})), Err(EngineError::BadParams { .. })), "{b}");
+ assert!(s.execute("type.edit", json!({"layer": id, "baseline": b})).is_err(), "{b}");
+ assert!(s.execute("type.create", json!({"x": 0, "y": 10, "text": "a", "baseline": b})).is_err(), "{b}");
+ }
+ assert_eq!(text_layer(&s, id).runs, before);
+ s.execute("type.setStyle", json!({"layer": id, "baseline": "normal"})).unwrap();
+ assert!(text_layer(&s, id).char_runs().iter().all(|r| r.style.baseline == FontBaseline::Normal));
+ }
+
fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> {
let t = text_layer(s, id);
let mut out = Vec::new();
diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs
index b268efcb9..9d1d677ad 100644
--- a/crates/io/src/palette_map.rs
+++ b/crates/io/src/palette_map.rs
@@ -35,7 +35,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFil
_ => return None,
};
let mut warnings = Vec::new();
- if doc.layers.len() > 1 {
+ if !flattens_losslessly(doc) {
warnings.push(format!("{:?} documents have no layers in Photoshop: written flattened", doc.mode));
}
let big = doc.size.width > 30_000 || doc.size.height > 30_000;
@@ -69,6 +69,28 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFil
Some((file, warnings))
}
+/// Whether the merged image holds everything the layers do: no layer, or a single visible pixel
+/// layer at full opacity, Normal blend, unclipped, without masks or layer effects. Anything else
+/// (more layers, a type, shape or smart object layer, a mask, a hidden layer) is lost when the
+/// document is written flattened.
+fn flattens_losslessly(doc: &Document) -> bool {
+ match doc.layers.as_slice() {
+ [] => true,
+ [l] => {
+ l.visible
+ && matches!(l.content, photocraft_doc::LayerContent::Raster(_))
+ && l.mask.is_none()
+ && l.vector_mask.is_none()
+ && !l.clipped
+ && l.opacity >= 1.0
+ && l.fill_opacity >= 1.0
+ && l.blend == photocraft_color::BlendMode::Normal
+ && !(l.effects.enabled && l.effects.items.iter().any(photocraft_doc::Effect::enabled))
+ }
+ _ => false,
+ }
+}
+
/// The Color Table as Color Mode Data: 256 reds, 256 greens, 256 blues (unused entries black).
fn palette(t: &ColorTable) -> Vec<u8> {
let mut m = vec![0u8; 768];
diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rs
index 650aab3d9..29b488855 100644
--- a/crates/io/tests/psd_structure.rs
+++ b/crates/io/tests/psd_structure.rs
@@ -287,6 +287,33 @@ fn indexed_document_whose_only_entry_is_transparent_is_not_written_as_indexed()
assert_eq!(&f.composite_rgba8().unwrap().data[..4], &[255, 0, 0, 255]);
}
+#[test]
+fn indexed_save_warns_whenever_flattening_loses_a_layer() {
+ // One plain visible pixel layer is the merged image: no warning. A single hidden, masked,
+ // half-opaque or type layer, or a second layer, is lost in the flat file, so the save says so.
+ let flat = |d: &photocraft_doc::Document| {
+ let out = export(d, "x.psd", &ExportOptions::default()).unwrap();
+ assert_eq!(PsdFile::from_bytes(&out.bytes).unwrap().header.color_mode, ColorMode::Indexed);
+ out.warnings.iter().any(|w| w.contains("written flattened"))
+ };
+ let plain = indexed_doc(photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0), vec![[255, 255, 255], [0, 0, 0]], None);
+ assert!(!flat(&plain), "a single plain layer flattens losslessly");
+ let changes: [fn(&mut photocraft_doc::Layer); 4] = [
+ |l| l.visible = false,
+ |l| l.opacity = 0.5,
+ |l| l.mask = Some(photocraft_doc::LayerMask::hide_all()),
+ |l| l.content = LayerContent::Text(photocraft_doc::TextLayer::default()),
+ ];
+ for (i, change) in changes.iter().enumerate() {
+ let mut d = plain.clone();
+ change(&mut d.layers[0]);
+ assert!(flat(&d), "change {i} is lost when flattened, so the save warns");
+ }
+ let mut two = plain.clone();
+ two.layers.push(two.layers[0].clone());
+ assert!(flat(&two));
+}
+
#[test]
fn indexed_and_bitmap_documents_with_channels_keep_them() {
// PhotoCraft does not read extra channels of a palette-mode PSD back, so these documents keep