补齐小壹模板保真、重开核验及采用图交付证据

This commit is contained in:
WuYongJie 2026-11-28 22:19:18 +08:00
parent 2aed7dc1cf
commit 2cdac1a99c
6 changed files with 342 additions and 11 deletions

View File

@ -125,7 +125,7 @@ export const productionOperationTools = [
blocker:obj({kind:Type.Union([Type.Literal('missing_required_input'),Type.Literal('authorization_required'),
Type.Literal('permanent_service_failure')]),reason:text,requiredAction:text}),
})],
['finish_production','保存并导出当前画布修订,返回实际文件、版本及客观进度。progressSummary 列出未复核、有未解决问题和复核通过的屏,以及保留的模板原文和未回填图位。scope=all 按各成品导出版本的复核状态核验本轮交付,可附当前画布修订提交该成品。若确需带着问题交付,在 issues 中逐屏填写 outputId、variantId、从 1 开始的 page 和 reason,作为交付清单的已知问题。',obj({
['finish_production','保存并导出当前画布修订,返回实际文件、版本及客观进度。progressSummary 列出未复核、有未解决问题和复核通过的屏,以及保留的模板原文和未回填图位。fidelityReport 列出与锁定原稿的逐屏差异,deltaPx 顺序为左、上、右、下。reopenVerification 列出重开图层差异和各图位的采用图一致性。scope=all 按各成品导出版本的复核状态核验本轮交付,可附当前画布修订提交该成品。若确需带着问题交付,在 issues 中逐屏填写 outputId、variantId、从 1 开始的 page 和 reason,作为交付清单的已知问题。',obj({
...outputScope,revision:optional(rev),scope:optional(Type.Union([Type.Literal('current'),Type.Literal('all')])),issues:optional(Type.Array(obj({outputId:optional(text),variantId:optional(text),page:optional(Type.Integer({minimum:1})),field:optional(text),reason:text}))),
})],
];

View File

@ -520,6 +520,7 @@ fn clear_sample_copy(layers: &mut [photocraft_doc::Layer]) {
fn prepare_product_template(native: &mut Document, meta: &mut Value, pack: &Value, component: &str) -> R<()> {
let profile = production_profile::select(pack, component)?;
meta["fidelityBaseline"] = fidelity::baseline(native, meta, profile);
if let Some(profile) = profile {
production_profile::apply(native, meta, profile)?;
meta["productionProfile"] = production_profile::source(pack, component);
@ -1512,6 +1513,7 @@ fn reuse_archived_candidate(dir: &Path, state: Value, input: &Value, preflight:
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete","sourceType":"archived-candidate",
"reusedFrom":origin,"materialTaskId":material_task,"sourceRequestId":source_request,"requestId":null,
"inputHash":target_input,"references":original_refs,
"prompt":source_record.get("prompt").filter(|prompt| prompt.is_string()).unwrap_or(&source_task["prompt"]),
"instructions":"历史候选,等待当前图位验收","artifact":artifact,"createdAt":now()});
reserve(dir,state,&record)?;
Ok(record)
@ -2441,7 +2443,7 @@ impl Backend {
}
}
fn candidate_pixels(dir: &Path, artifact: &Value) -> R<Vec<u8>> {
pub(super) fn candidate_pixels(dir: &Path, artifact: &Value) -> R<Vec<u8>> {
use std::io::Read;
let task = uuid(&artifact["taskId"], "候选原任务")?;
let relative = format!("image-jobs/{task}/generated.png");
@ -2599,6 +2601,7 @@ fn candidate_export_source(dir: &Path, record: &Value) -> Value {
.filter(|task| task["id"] == record["id"] && task["slotBinding"] == record["binding"]);
let mut source = json!({
"candidateId":candidate_id,"materialTaskId":material_task_id(record),
"prompt":record["prompt"],"requestId":record["requestId"],
"candidateRecord":format!("{archive}/{CANDIDATE}"),"candidateArtifact":record["artifact"],"kind":"unrecorded",
});
if task.is_some() {
@ -2661,6 +2664,8 @@ fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value,
source["fieldId"] = json!(id);
source["slotId"] = json!(slot);
source["nativeLayerId"] = json!(layer.id.0);
source["variantId"] = json!(variant);
source["embeddedSha256"] = json!(fidelity::embedded_hash(layer));
source["embeddedSize"] = json!(creation::png_size(bytes).ok());
Some(source)
});
@ -3122,6 +3127,7 @@ pub(super) fn publish_product_generation(
|| reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text {
return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into());
}
let reopen_verification = fidelity::reopen(native, &reopened, &result["imageSources"]);
super::transfer::check_pcraft_file(&editable)?;
let layered = export_layered_document(generation.path(), component, id, &reopened)?;
let exported_mapping = mapping(&reopened);
@ -3178,6 +3184,7 @@ pub(super) fn publish_product_generation(
let size = fs::metadata(&editable).map_err(|error| format!("无法读取成品工程信息:{error}"))?.len();
let sha = file_digest(&editable).map_err(|error| format!("无法核对成品工程内容:{error}"))?;
let delivery = json!({"state":"output_exported","outputState":"exported","outputId":component,"generationId":id});
result["reopenVerification"] = reopen_verification;
result["generationId"] = json!(id);
result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id,
"revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height,
@ -3266,6 +3273,7 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
return Err("可编辑画布属于其他款式或模板".into());
}
let profile = production_profile::select(&state["template"], component)?;
result["fidelityReport"] = fidelity::report(native, &meta);
if let Some(profile) = profile {
result["productionProfile"] = production_profile::source(&state["template"], component);
if let Some(layer) = production_profile::visible_sample_layer(native, profile) {
@ -4396,6 +4404,9 @@ impl Backend {
}
}
#[path = "jiansun_fidelity.rs"]
mod fidelity;
#[cfg(test)]
#[path = "jiansun_fidelity_tests.rs"]
mod fidelity_tests;
@ -5622,6 +5633,7 @@ mod tests {
assert_eq!(snapshot["screenFiles"][0]["pageId"], "S01");
assert_eq!(snapshot["imageSources"][0]["materialTaskId"], candidate["id"]);
assert_eq!(snapshot["imageSources"][0]["embeddedSize"], json!([8,4]));
assert_eq!(snapshot["reopenVerification"]["adoptions"][0]["consistent"], true);
assert_eq!(read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap()["imageSources"], snapshot["imageSources"]);
let receipt = receipt_path(&fixture.dir, variant, "detail");

View File

@ -90,7 +90,7 @@ fn variant_name(brief: &Value, variant: &str) -> Option<String> {
.map(name_component)
}
fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec<Value>) -> R<Option<Value>> {
fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec<Value>) -> R<Value> {
let component = output["outputId"].as_str().ok_or("成品类型缺失")?;
let label = match component {
"detail" => "详情页",
@ -142,9 +142,23 @@ fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, f
files.push(copy_artifact(root, generation, image, label, folder, &name)?);
}
}
Ok(data["unverifiedCopy"].as_array().filter(|fields| !fields.is_empty()).map(|fields| {
json!({"variantId":variant,"outputId":component,"generationId":id,"fields":fields})
}))
let mut adopted = Vec::new();
for (index, source) in data["imageSources"].as_array().into_iter().flatten().enumerate() {
let bytes = canvas_workspace::candidate_pixels(project, &source["candidateArtifact"])?;
let parent = root.join("采用图").join(folder).join(label);
fs::create_dir_all(&parent).map_err(disk)?;
let path = parent.join(format!("{:02}.png", index + 1));
fs::write(&path, &bytes).map_err(disk)?;
let size = artifact_size(&path, "png")?;
let file = file_record(root, &path, "采用图", size)?;
adopted.push(json!({"pageId":source["pageId"],"fieldId":source["fieldId"],
"slotId":source["slotId"],"candidateId":source["candidateId"],"prompt":source["prompt"],
"requestId":source["requestId"],"relativePath":file["relativePath"],"sha256":file["sha256"]}));
files.push(file);
}
Ok(json!({"variantId":variant,"outputId":component,"generationId":id,
"unverifiedCopy":data["unverifiedCopy"],"unverifiedFacts":data["unverifiedFacts"],
"adoptedImages":adopted,"fidelityReport":data["fidelityReport"],"reopenVerification":data["reopenVerification"]}))
}
fn sync_tree(dir: &Path) -> R<()> {
@ -229,6 +243,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
let mut variant_folders = BTreeMap::new();
let mut seen = HashSet::new();
let mut unverified_copy = Vec::new();
let mut output_evidence = Vec::new();
for output in outputs {
admitted()?;
let variant = output["variantId"].as_str().ok_or("成品花色缺失")?;
@ -244,9 +259,12 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
}
PathBuf::from(format!("{index:02} {}", color.as_deref().unwrap_or("花色")))
});
if let Some(review) = copy_generation(root, project, input, output, folder, color.as_deref(), &mut files)? {
unverified_copy.push(review);
let evidence = copy_generation(root, project, input, output, folder, color.as_deref(), &mut files)?;
if let Some(fields) = evidence["unverifiedCopy"].as_array().filter(|fields| !fields.is_empty()) {
unverified_copy.push(json!({"variantId":variant,"outputId":component,
"generationId":evidence["generationId"],"fields":fields}));
}
output_evidence.push(evidence);
}
let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?;
let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?;
@ -273,7 +291,8 @@ 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,"knownIssues":input["knownIssues"],"unverifiedCopy":unverified_copy});
"counts":counts,"files":files,"knownIssues":input["knownIssues"],"unverifiedCopy":unverified_copy,
"outputEvidence":output_evidence});
transfer::no_credentials(&manifest)?;
write_json(&root.join("交付清单.json"), &manifest)?;
sync_tree(root)?;
@ -361,7 +380,12 @@ mod tests {
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();
fs::write(assets.join("sample.png"), &png).unwrap();
let task = Uuid::new_v4().to_string();
let adopted = format!("image-jobs/{task}/generated.png");
fs::create_dir_all(project.join(format!("image-jobs/{task}"))).unwrap();
fs::write(project.join(&adopted), &png).unwrap();
let adopted_sha = canvas_workspace::file_digest(&project.join(&adopted)).unwrap();
let workspace = Uuid::new_v4().to_string();
let mut published = Vec::new();
for (component, regions, screens) in [
@ -373,6 +397,9 @@ mod tests {
let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component});
if component == "detail" {
result["unverifiedCopy"] = json!(["S01-T01"]);
result["imageSources"] = json!([{"pageId":"S01","fieldId":"I01","slotId":"slot",
"candidateId":task,"requestId":"request","prompt":"Adopted image prompt",
"candidateArtifact":{"taskId":task,"path":adopted,"sha256":adopted_sha}}]);
}
canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(7), &mut result, &regions, &screens).unwrap();
assert_eq!(result["layeredDocument"]["format"], "psd");
@ -417,6 +444,11 @@ mod tests {
let manifest_path = final_dir.join("交付清单.json");
let manifest = read_json(&manifest_path).unwrap();
assert_eq!(manifest["knownIssues"], input["knownIssues"]);
let adopted = &manifest["outputEvidence"][0]["adoptedImages"][0];
assert_eq!(adopted["prompt"], "Adopted image prompt");
assert_eq!(adopted["requestId"], "request");
let image = final_dir.join(adopted["relativePath"].as_str().unwrap());
assert_eq!(adopted["sha256"], canvas_workspace::file_digest(&image).unwrap());
assert_eq!(delivered["knownIssues"], input["knownIssues"]);
transfer::no_credentials(&manifest).unwrap();
let detail = &input["published"][0];

View File

@ -0,0 +1,213 @@
use super::{page_fields, production_profile};
use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartSource};
use photocraft_ui_egui::jiansun::production_facts::{layer_frame, path_visible, screen_area};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap};
pub(super) fn embedded_hash(layer: &Layer) -> Option<String> {
let LayerContent::Smart(smart) = &layer.content else { return None };
let SmartSource::Embedded { bytes, .. } = &smart.source else { return None };
Some(format!("{:x}", Sha256::digest(bytes.as_slice())))
}
fn bounds(doc: &Document, layer: &Layer) -> [i32; 4] {
let frame = layer_frame(doc, layer);
[frame.x0, frame.y0, frame.x1, frame.y1]
}
fn layer_state(doc: &Document, path: &[usize], layer: &Layer) -> Value {
let (text, transform) = match &layer.content {
LayerContent::Text(text) => (Some(&text.text), Some(text.transform)),
_ => (None, None),
};
let endpoints = match &layer.content {
LayerContent::Shape(shape) => shape
.path
.subpaths
.iter()
.filter(|path| !path.closed)
.filter_map(|path| Some([path.knots.first()?.anchor, path.knots.last()?.anchor]))
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let track_geometry = !matches!(&layer.content, LayerContent::Group(group) if group.artboard.is_none())
|| layer.vector_mask.as_ref().is_some_and(|mask| mask.enabled)
|| layer.mask.as_ref().is_some_and(|mask| mask.enabled);
json!({"layerId":layer.id.0,"name":layer.name,"bounds":bounds(doc, layer),"trackGeometry":track_geometry,
"visible":layer.visible,"effectiveVisible":path_visible(doc, path),"text":text,"textTransform":transform,"endpoints":endpoints})
}
pub(super) fn baseline(doc: &Document, meta: &Value, profile: Option<&Value>) -> Value {
let dimension_layers: std::collections::HashSet<_> = profile
.into_iter()
.flat_map(|profile| profile["dimensionGuides"].as_array().into_iter().flatten())
.flat_map(|row| row["guides"].as_array().into_iter().flatten())
.filter_map(Value::as_u64)
.collect();
let layers: Vec<_> = doc
.walk()
.into_iter()
.map(|(path, _, layer)| {
let mut row = layer_state(doc, &path, layer);
row["dimensionGuide"] = json!(layer.psd_id.map(u64::from).is_some_and(|id| dimension_layers.contains(&id)));
let field = page_fields(meta)
.find_map(|(page, fields)| fields.iter().find(|field| field["nativeLayerId"].as_u64() == Some(layer.id.0)).map(|field| (page, field)));
row["classification"] = json!(if field.is_some() {
"registeredField"
} else if profile.is_some_and(|profile| production_profile::is_sample_layer(profile, layer)) {
"allowedHidden"
} else {
"fixed"
});
if let Some((page, field)) = field {
row["pageId"] = page.clone();
row["fieldId"] = field["fieldId"].clone();
row["imageFrame"] = json!(field["kind"] == "image");
}
row
})
.collect();
json!({"layers":layers,"guides":doc.guides})
}
pub(super) fn report(doc: &Document, meta: &Value) -> Value {
let original = &meta["fidelityBaseline"];
let Some(layers) = original["layers"].as_array() else {
return json!({"status":"baselineUnavailable"});
};
let current: HashMap<_, _> = doc.walk().into_iter().map(|(path, _, layer)| (layer.id.0, layer_state(doc, &path, layer))).collect();
let mut changes = Vec::new();
let mut frames = Vec::new();
let mut endpoints = Vec::new();
let mut dimension_guides = Vec::new();
for row in layers {
let id = row["layerId"].as_u64().unwrap();
let after = current.get(&id).unwrap_or(&Value::Null);
let before_bounds: [i32; 4] = serde_json::from_value(row["bounds"].clone()).unwrap();
let after_bounds = serde_json::from_value::<[i32; 4]>(after["bounds"].clone()).ok();
let delta = after_bounds.map(|after| std::array::from_fn::<_, 4, _>(|i| after[i] - before_bounds[i]));
let mut kinds = Vec::new();
if after.is_null() {
kinds.push("deleted");
} else {
if row["visible"] != after["visible"] || row["effectiveVisible"] != after["effectiveVisible"] {
kinds.push(if after["effectiveVisible"] == false { "hidden" } else { "visibility" });
}
if row["trackGeometry"] == true
&& let Some([left, top, right, bottom]) = delta
{
if left != 0 || top != 0 {
kinds.push("moved");
}
if left != right || top != bottom {
kinds.push("scaled");
}
}
if row["text"] != after["text"] {
kinds.push("text");
}
if row["endpoints"] != after["endpoints"] {
kinds.push("endpoints");
}
}
if row["imageFrame"] == true {
frames.push(json!({"pageId":row["pageId"],"fieldId":row["fieldId"],"layerId":id,"deltaPx":delta}));
}
if row["dimensionGuide"] == true {
dimension_guides.push(json!({"layerId":id,"name":row["name"],"before":row["bounds"],
"after":after["bounds"],"visible":after["effectiveVisible"],"deleted":after.is_null()}));
}
if row["endpoints"].as_array().is_some_and(|points| !points.is_empty()) {
endpoints.push(json!({"layerId":id,"before":row["endpoints"],"after":after["endpoints"],
"visible":after["effectiveVisible"]}));
}
if !kinds.is_empty() {
let expected = (row["classification"] == "registeredField"
&& kinds.contains(&"text")
&& row["textTransform"] == after["textTransform"]
&& kinds.iter().all(|kind| matches!(*kind, "text" | "moved" | "scaled")))
|| (row["classification"] == "allowedHidden" && kinds.as_slice() == ["hidden"]);
changes.push(json!({"before":row,"after":after,"changes":kinds,"expected":expected}));
}
}
let pages: Vec<_> = meta["outputs"]
.as_array()
.into_iter()
.flatten()
.map(|page| {
let ids: Vec<_> = layers
.iter()
.filter(|row| {
row["pageId"] == page["documentId"]
|| (row["pageId"].is_null()
&& screen_area(doc.bounds(), page).is_ok_and(|area| {
let [l, t, r, b]: [i32; 4] = serde_json::from_value(row["bounds"].clone()).unwrap();
l < area.x1 && r > area.x0 && t < area.y1 && b > area.y0
}))
})
.map(|row| &row["layerId"])
.collect();
json!({"pageId":page["documentId"],"layerIds":ids})
})
.collect();
let guides = json!(doc.guides);
json!({"status":"compared","templateHash":meta["templateHash"],
"originalSha256":meta["enterprise"]["originalSha256"],
"changes":changes,"imageFrames":frames,"screens":pages,
"guides":{"before":original["guides"],"after":guides,"unchanged":original["guides"] == guides},
"endpoints":endpoints,"dimensionGuides":dimension_guides})
}
pub(super) fn reopen(before: &Document, after: &Document, sources: &Value) -> Value {
let snapshots = |doc: &Document| -> BTreeMap<u64, Value> {
doc.walk()
.into_iter()
.map(|(path, _, layer)| {
let mut row = layer_state(doc, &path, layer);
row["embeddedSha256"] = json!(embedded_hash(layer));
row["layerPath"] = json!(path);
let bounds = photocraft_compose::layer_bounds(layer, doc.bounds());
row["contentBounds"] = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]);
if let LayerContent::Smart(smart) = &layer.content {
row["smartTransform"] = json!(smart.transform);
}
(layer.id.0, row)
})
.collect()
};
let original = snapshots(before);
let reopened = snapshots(after);
let ids: BTreeSet<_> = original.keys().chain(reopened.keys()).collect();
let differences: Vec<_> = ids
.into_iter()
.filter_map(|id| {
let (left, right) = (original.get(id), reopened.get(id));
(left != right).then(|| json!({"layerId":id,"before":left,"after":right}))
})
.collect();
let adoptions: Vec<_> = sources
.as_array()
.into_iter()
.flatten()
.map(|source| {
let id = source["nativeLayerId"].as_u64().map(LayerId);
let marker = format!("jiansun.adopted.{}.{}", source["variantId"].as_str().unwrap_or_default(), source["slotId"].as_str().unwrap_or_default());
let candidate = |doc: &Document| doc.metadata.text.iter().find(|(key, _)| key == &marker).map(|(_, id)| json!(id)).unwrap_or(Value::Null);
let canvas = id.and_then(|id| original.get(&id.0)).map(|row| row["embeddedSha256"].clone()).unwrap_or(Value::Null);
let saved = id.and_then(|id| reopened.get(&id.0)).map(|row| row["embeddedSha256"].clone()).unwrap_or(Value::Null);
let (canvas_candidate, saved_candidate) = (candidate(before), candidate(after));
let consistent = !canvas.is_null()
&& canvas == saved
&& canvas == source["embeddedSha256"]
&& source["candidateId"] == canvas_candidate
&& canvas_candidate == saved_candidate;
json!({"slotId":source["slotId"],"candidateId":source["candidateId"],
"canvasCandidateId":canvas_candidate,"reopenedCandidateId":saved_candidate,
"candidateSha256":source["candidateArtifact"]["sha256"],"canvasSha256":canvas,
"reopenedSha256":saved,"consistent":consistent})
})
.collect();
json!({"layersCompared":original.len(),"differences":differences,"adoptions":adoptions,
"consistent":differences.is_empty() && adoptions.iter().all(|row| row["consistent"] == true)})
}

View File

@ -375,3 +375,77 @@ fn published_sibling_components_bind_the_actual_native_layers() {
}
write_json(&root.join("native-components.json"), &json!(results)).unwrap();
}
#[test]
fn fidelity_reports_fixed_visibility_and_frame_drift_with_expected_copy() {
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Path as VectorPath, Subpath, VectorMask};
use photocraft_geom::Size;
let mut original = Document::new("Template", Size::new(100, 100), ColorMode::Rgb, SampleType::U8);
let decoration = Layer::group("Decoration", vec![]);
let mut frame = Layer::group("Image frame", vec![]);
let mask = |x: f64| VectorMask::new(VectorPath::new(vec![Subpath::polygon(&[
(x, 0.0), (x + 20.0, 0.0), (x + 20.0, 20.0), (x, 20.0),
])]));
frame.vector_mask = Some(mask(0.0));
let copy = Layer::new("Copy", LayerContent::Text(TextLayer {
text: "Original".into(), ..Default::default()
}));
let (decoration_id, frame_id, copy_id) = (decoration.id, frame.id, copy.id);
original.layers = vec![decoration, frame, copy];
let mut meta = json!({"outputs":[{"documentId":"S01","top":0,"width":100,"height":100,"mapping":{"fields":[
{"nativeLayerId":frame_id.0,"kind":"image","fieldId":"I01"},
{"nativeLayerId":copy_id.0,"kind":"text","fieldId":"T01"}
]}}]});
meta["fidelityBaseline"] = fidelity::baseline(&original, &meta, None);
let mut edited = original.clone();
edited.layer_mut(decoration_id).unwrap().visible = false;
edited.layer_mut(frame_id).unwrap().vector_mask = Some(mask(12.0));
let LayerContent::Text(text) = &mut edited.layer_mut(copy_id).unwrap().content else { unreachable!() };
text.text = "Replacement".into();
let report = fidelity::report(&edited, &meta);
let changes = report["changes"].as_array().unwrap();
assert_eq!(changes[0]["before"]["classification"], "fixed");
assert_eq!(changes[0]["changes"], json!(["hidden"]));
assert_eq!(changes[1]["changes"], json!(["moved"]));
assert_eq!(report["imageFrames"][0]["deltaPx"], json!([12, 0, 12, 0]));
assert_eq!(changes[2]["changes"], json!(["text"]));
assert_eq!(changes[2]["expected"], true);
}
#[test]
fn reopen_detects_replaced_embedded_image_and_verifies_the_adoption() {
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Affine, SmartObject, SmartSource};
use photocraft_geom::Size;
use std::sync::Arc;
let mut canvas = Document::new("Template", Size::new(10, 10), ColorMode::Rgb, SampleType::U8);
let smart = |bytes| LayerContent::Smart(SmartObject::new(
SmartSource::Embedded { file_name:"candidate.png".into(), bytes:Arc::new(bytes) },
Affine::IDENTITY, None,
));
let layer = Layer::new("Image", smart(vec![1, 2, 3]));
let id = layer.id;
let sha = fidelity::embedded_hash(&layer).unwrap();
canvas.layers.push(layer);
canvas.metadata.text.push(("jiansun.adopted.variant.slot".into(), "candidate".into()));
let sources = json!([{"variantId":"variant","slotId":"slot","candidateId":"candidate",
"nativeLayerId":id.0,"embeddedSha256":sha,"candidateArtifact":{"sha256":sha}}]);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("reopen.pcraft");
photocraft_format::PcraftWriter::new().save_path(&canvas, &path, &Default::default()).unwrap();
let mut reopened = photocraft_format::load_path(&path).unwrap();
let report = fidelity::reopen(&canvas, &reopened, &sources);
assert_eq!(report["consistent"], true);
assert_eq!(report["adoptions"][0]["consistent"], true);
reopened.layer_mut(id).unwrap().content = smart(vec![4, 5, 6]);
let report = fidelity::reopen(&canvas, &reopened, &sources);
assert_eq!(report["consistent"], false);
assert_eq!(report["differences"][0]["layerId"], id.0);
assert_eq!(report["adoptions"][0]["consistent"], false);
}

View File

@ -67,7 +67,7 @@ fn listed_layer(ids: &Value, layer: &Layer) -> bool {
layer.psd_id.is_some_and(|source| ids.as_array().into_iter().flatten().any(|id| id.as_u64() == Some(source.into())))
}
fn is_sample_layer(profile: &Value, layer: &Layer) -> bool {
pub(super) fn is_sample_layer(profile: &Value, layer: &Layer) -> bool {
let name = layer.name.to_lowercase();
listed_layer(&profile["hideLayerIds"], layer) || matches_name(&profile["hideNames"], &name)
|| !matches!(layer.content, LayerContent::Text(_)) && matches_name(&profile["hideGraphicNames"], &name)