diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 535f35a1..b3a61a06 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3087,7 +3087,6 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va let unverified_copy = unverified_export_copy(native, &meta, &journal); if !unverified_copy.is_empty() { result["unverifiedCopy"] = json!(unverified_copy); - return blocked(result); } let path = receipt_path(dir, &variant_id, component); let pages = meta["outputs"].as_array().ok_or("没有可导出的画布页面")?; @@ -5213,10 +5212,12 @@ mod tests { doc.metadata.text.push((MAPPING.into(), meta.to_string())); doc.layers.extend([caption,blank]); save(&doc); - let blocked = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); - assert_eq!(blocked["unverifiedCopy"], json!(["S01-T01"])); - assert!(blocked["files"].as_array().unwrap().is_empty()); - assert!(!receipt_path(&fixture.dir,variant,"detail").exists()); + let exported = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); + assert_eq!(exported["unverifiedCopy"], json!(["S01-T01"])); + assert_eq!(exported["productionDelivery"]["outputState"], "exported"); + assert!(artifact_matches(&exported["files"][0], true)); + let saved = read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap(); + assert_eq!(saved["unverifiedCopy"], exported["unverifiedCopy"]); let audit_path = fixture.dir.join("agent").join("test-account").join(fixture.dir.file_name().unwrap()) .join("conversation-v1").join(format!("production-detail-{variant}.json")); @@ -5229,6 +5230,7 @@ mod tests { doc.layers.push(fixed); save(&doc); let ready = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); + assert!(ready["unverifiedCopy"].is_null()); assert_eq!(ready["warnings"], json!(["该模板未发布固定文字许可"])); assert_eq!(ready["productionDelivery"]["outputState"], "exported"); assert!(ready["localSave"].is_null() && ready["cloudSync"].is_null()); @@ -5311,9 +5313,10 @@ mod tests { else { panic!("expected caption"); }; text.text = "未验收的新卖点".into(); save(&doc); - let blocked = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); - assert_eq!(blocked["unverifiedCopy"], json!(["S01-T01"])); - assert!(blocked["files"].as_array().unwrap().is_empty()); + let exported = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); + assert_eq!(exported["unverifiedCopy"], json!(["S01-T01"])); + assert_eq!(exported["productionDelivery"]["outputState"], "exported"); + assert!(artifact_matches(&exported["files"][0], true)); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index 27bf187f..181d5f1d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -90,7 +90,7 @@ fn variant_name(brief: &Value, variant: &str) -> Option { .map(name_component) } -fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec) -> R<()> { +fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec) -> R> { let component = output["outputId"].as_str().ok_or("成品类型缺失")?; let label = match component { "detail" => "详情页", @@ -142,7 +142,9 @@ fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, f files.push(copy_artifact(root, generation, image, label, folder, &name)?); } } - Ok(()) + Ok(data["unverifiedCopy"].as_array().filter(|fields| !fields.is_empty()).map(|fields| { + json!({"variantId":variant,"outputId":component,"generationId":id,"fields":fields}) + })) } fn sync_tree(dir: &Path) -> R<()> { @@ -175,7 +177,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu .ok() .filter(|saved| saved["deliveryId"] == delivery_id) .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"], - "missingOutputs":saved["missingOutputs"],"missing":saved["missing"]})) + "missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"unverifiedCopy":saved["unverifiedCopy"]})) }; // Recover a committed directory if the client lost the completion event. for number in 1.. { @@ -226,6 +228,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let variants: HashSet<_> = outputs.iter().filter_map(|output| output["variantId"].as_str()).collect(); let mut variant_folders = BTreeMap::new(); let mut seen = HashSet::new(); + let mut unverified_copy = Vec::new(); for output in outputs { admitted()?; let variant = output["variantId"].as_str().ok_or("成品花色缺失")?; @@ -241,7 +244,9 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu } PathBuf::from(format!("{index:02} {}", color.as_deref().unwrap_or("花色"))) }); - copy_generation(root, project, input, output, folder, color.as_deref(), &mut files)?; + if let Some(review) = copy_generation(root, project, input, output, folder, color.as_deref(), &mut files)? { + unverified_copy.push(review); + } } let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?; let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?; @@ -268,7 +273,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu } let manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed, "completedOutputs":outputs.len(),"totalOutputs":total,"missingOutputs":missing_outputs,"missing":missing, - "counts":counts,"files":files}); + "counts":counts,"files":files,"unverifiedCopy":unverified_copy}); transfer::no_credentials(&manifest)?; write_json(&root.join("交付清单.json"), &manifest)?; sync_tree(root)?; @@ -286,7 +291,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu Ok(()) => { let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error)); return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed, - "counts":counts,"missingOutputs":missing_outputs,"missing":missing,"durabilityWarning":flush})); + "counts":counts,"missingOutputs":missing_outputs,"missing":missing, + "unverifiedCopy":unverified_copy,"durabilityWarning":flush})); } Err(_) if target.exists() => continue, Err(error) => return Err(disk(error)), @@ -351,6 +357,11 @@ mod tests { let variant = Uuid::new_v4().to_string(); write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅", "variants":[{"id":variant,"name":"浅橡木"}]}})).unwrap(); + let assets = project.join("creation-assets"); + fs::create_dir(&assets).unwrap(); + let image = photocraft_codecs::Image::from_u8(7, 5, photocraft_codecs::ChannelLayout::Rgb, vec![0; 7 * 5 * 3]).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + fs::write(assets.join("sample.png"), png).unwrap(); let workspace = Uuid::new_v4().to_string(); let mut published = Vec::new(); for (component, regions, screens) in [ @@ -360,6 +371,9 @@ mod tests { ] { let receipt = canvas_workspace::receipt_path(&project, &variant, component); let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component}); + if component == "detail" { + result["unverifiedCopy"] = json!(["S01-T01"]); + } canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(7), &mut result, ®ions, &screens).unwrap(); assert_eq!(result["layeredDocument"]["format"], "psd"); assert_eq!(result["validation"]["filesVerified"], 2 + regions.len() + screens.len()); @@ -402,6 +416,16 @@ mod tests { let manifest_path = final_dir.join("交付清单.json"); let manifest = read_json(&manifest_path).unwrap(); transfer::no_credentials(&manifest).unwrap(); + let detail = &input["published"][0]; + assert_eq!(manifest["unverifiedCopy"], json!([{ + "variantId":detail["variantId"],"outputId":"detail", + "generationId":detail["generationId"],"fields":["S01-T01"] + }])); + assert_eq!(delivered["unverifiedCopy"], manifest["unverifiedCopy"]); + let asset = manifest["files"].as_array().unwrap().iter().find(|entry| + entry["category"] == "工程资源" && entry["relativePath"].as_str().unwrap().ends_with("/creation-assets/sample.png") + ).unwrap(); + assert_eq!((&asset["width"], &asset["height"]), (&json!(7), &json!(5))); for entry in manifest["files"].as_array().unwrap() { let path = final_dir.join(entry["relativePath"].as_str().unwrap()); assert!(path.is_file(), "{}", path.display()); @@ -468,7 +492,9 @@ mod tests { assert_eq!(reopened.metadata.psd_global_blocks[0].2.as_slice(), vec![123; 1 << 20]); fs::rename(root.path().join("hidden-source"), &project).unwrap(); let original = fs::read(manifest_path).unwrap(); - assert_eq!(deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap()["path"], delivered["path"]); + let recovered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + assert_eq!(recovered["path"], delivered["path"]); + assert_eq!(recovered["unverifiedCopy"], delivered["unverifiedCopy"]); input["deliveryId"] = json!(Uuid::new_v4().to_string()); let second = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); assert!(second["path"].as_str().unwrap().ends_with("天青椅-成品 (2)")); diff --git a/apps/detail-photocraft/crates/codecs/src/codecs/png.rs b/apps/detail-photocraft/crates/codecs/src/codecs/png.rs index e119e225..14cf5de6 100644 --- a/apps/detail-photocraft/crates/codecs/src/codecs/png.rs +++ b/apps/detail-photocraft/crates/codecs/src/codecs/png.rs @@ -26,6 +26,32 @@ pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 { if (whole / f64::from(METERS_PER_INCH)).round() == f64::from(ppm) { whole as f32 } else { dpi as f32 } } +fn check_header(info: &png::Info<'_>, limits: &Limits, file_len: usize) -> Result<(), CodecError> { + let (w, h) = info.size(); + // Worst case output: 4 channels x 16 bit. + limits.check_bytes(w, h, 8)?; + // zlib never beats 1032:1. Check the stored samples before palette/bit expansion. + let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(info.bits_per_pixel() as u64).div_ceil(8); + Limits::check_plausible(stored, file_len, 1100) +} + +pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, Option>), CodecError> { + let mut decoder = png::Decoder::new_with_limits(Cursor::new(bytes), png::Limits { bytes: limits.alloc_usize() }); + decoder.set_transformations(png::Transformations::EXPAND); + decoder.set_ignore_text_chunk(true); + check_header(decoder.read_header_info().map_err(map_png_err)?, limits, bytes.len())?; + let mut reader = decoder.read_info().map_err(map_png_err)?; + let info = reader.info(); + let (w, h) = info.frame_control.map_or(info.size(), |frame| (frame.width, frame.height)); + // eXIf can follow IDAT. The reader can skip compressed image data while collecting metadata. + if info.exif_metadata.is_none() + && let Err(e @ png::DecodingError::LimitsExceeded) = reader.finish() + { + return Err(map_png_err(e)); + } + Ok((w, h, reader.info().exif_metadata.as_ref().map(|exif| exif.to_vec()))) +} + pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let mut input = Cursor::new(bytes); let mut decoder = png::Decoder::new_with_limits(&mut input, png::Limits { bytes: limits.alloc_usize() }); @@ -33,16 +59,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result // png's lazy text get_text() inflates without consulting its allocation limit. // Read text separately below, without retaining compressed copies in the decoder. decoder.set_ignore_text_chunk(true); - { - let info = decoder.read_header_info().map_err(map_png_err)?; - let (w, h) = info.size(); - // Worst case output: 4 channels x 16 bit. - limits.check_bytes(w, h, 8)?; - // zlib never beats 1032:1; refuse a file too small for the declared image before the - // output buffer exists. Measured on the stored samples (before palette/bit expansion). - let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(info.bits_per_pixel() as u64).div_ceil(8); - Limits::check_plausible(stored, bytes.len(), 1100)?; - } + check_header(decoder.read_header_info().map_err(map_png_err)?, limits, bytes.len())?; let mut reader = decoder.read_info().map_err(map_png_err)?; // APNG: the IDAT image is the first frame, or an extra default image when no fcTL precedes it. let images = reader.info().animation_control.map_or(1, |a| u64::from(a.num_frames) + u64::from(reader.info().frame_control.is_none())); @@ -854,6 +871,14 @@ mod stereo_tests { out } + #[test] + fn probe_rejects_dimensions_that_exceed_decode_limits() { + let bytes = png_with(&[]); + let limits = Limits { max_width: 1, ..Limits::default() }; + assert!(matches!(probe(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + assert!(matches!(decode(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + } + #[test] fn reads_both_defined_views() { assert_eq!(stereo(&png_with(&[0])), Some(PngStereo::CrossFuse)); diff --git a/apps/detail-photocraft/crates/codecs/src/lib.rs b/apps/detail-photocraft/crates/codecs/src/lib.rs index 632ecbf0..d29b61b8 100644 --- a/apps/detail-photocraft/crates/codecs/src/lib.rs +++ b/apps/detail-photocraft/crates/codecs/src/lib.rs @@ -115,7 +115,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res } /// The upright pixel size [`decode`] would return, read from the file's header without decoding -/// pixels, for JPEG, WebP, OpenEXR (flat) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same +/// pixels, for JPEG, PNG, WebP, OpenEXR (flat) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same /// header reads and size checks as the decoder (default [`Limits`]) and swaps the size for an /// EXIF orientation of 5–8, so wherever [`decode`] succeeds the two agree. Other formats (and /// deep EXR or AVIF) return [`CodecError::Unsupported`]: decode those to learn their size. @@ -127,6 +127,7 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { let l = &Limits::default(); let (w, h, exif) = match format { Format::Jpeg => jpeg::probe(bytes, l)?, + Format::Png => png::probe(bytes, l)?, Format::WebP => webp::probe(bytes, l)?, Format::OpenExr => exr::probe(bytes, l).map(|(w, h)| (w, h, None))?, Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::probe(format, bytes, l)?, diff --git a/apps/detail-photocraft/crates/codecs/tests/it/orientation.rs b/apps/detail-photocraft/crates/codecs/tests/it/orientation.rs index 2b2daf77..baa452da 100644 --- a/apps/detail-photocraft/crates/codecs/tests/it/orientation.rs +++ b/apps/detail-photocraft/crates/codecs/tests/it/orientation.rs @@ -75,9 +75,9 @@ fn jpeg_with_exif(jpeg: &[u8], exif: &[u8]) -> Vec { out } -/// Inserts a PNG eXIf chunk before the first IDAT. -fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec { - let at = png.windows(4).position(|w| w == b"IDAT").unwrap() - 4; +/// Inserts a PNG eXIf chunk before the chosen chunk. +fn png_with_exif(png: &[u8], exif: &[u8], before: &[u8; 4]) -> Vec { + let at = png.windows(4).position(|w| w == before).unwrap() - 4; let mut chunk = (exif.len() as u32).to_be_bytes().to_vec(); let mut body = b"eXIf".to_vec(); body.extend_from_slice(exif); @@ -199,9 +199,10 @@ fn png_opens_upright_for_every_orientation() { for o in 1..=8u16 { let (s, sw, sh) = stored(&up, w, h, o); let png = encode(&gray(sw, sh, s.clone()), Format::Png, &EncodeOptions::default()).unwrap(); - let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false)); + let file = png_with_exif(&png, &exif(u32::from(o), o % 2 == 0, false), b"IDAT"); let img = decode(&file).unwrap(); assert_eq!(img.dimensions(), (w as u32, h as u32), "o={o}"); + assert_eq!(probe_size(&file).unwrap(), img.dimensions(), "o={o}"); assert_eq!(img.data(), &up[..], "o={o}"); assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "o={o}: metadata says upright"); // Opting out keeps the stored pixels and the tag. @@ -211,6 +212,14 @@ fn png_opens_upright_for_every_orientation() { } } +#[test] +fn png_probe_reads_exif_after_image_data() { + let png = encode(&gray(3, 5, vec![0; 15]), Format::Png, &EncodeOptions::default()).unwrap(); + let file = png_with_exif(&png, &exif(6, false, false), b"IEND"); + assert_eq!(decode(&file).unwrap().dimensions(), (5, 3)); + assert_eq!(probe_size(&file).unwrap(), (5, 3)); +} + /// Extra samples (a TIFF's alpha and spot planes) turn with the image, so a channel stays /// aligned with the pixels for every orientation. #[test] @@ -580,7 +589,7 @@ fn long_orientation_reads_and_rewrites_in_both_byte_orders() { #[test] fn probe_size_matches_decode() { let img = synth(7, 5, ChannelLayout::Rgb, SampleType::U8, 3, 0.0); - let probed = [Format::WebP, Format::Gif, Format::Bmp, Format::Tga, Format::Qoi, Format::Hdr, Format::Ico, Format::OpenExr]; + let probed = [Format::Png, Format::WebP, Format::Gif, Format::Bmp, Format::Tga, Format::Qoi, Format::Hdr, Format::Ico, Format::OpenExr]; assert!(probed.iter().all(|f| rw_formats().contains(f))); for format in rw_formats() { let bytes = encode(&img, format, &EncodeOptions::default()).unwrap();