diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index a59125e9..916d897e 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -14,7 +14,7 @@ export const NATIVE_CANVAS_QUICK_REFERENCE = [ 'layer.delete {layer}。layer.moveTo {layer, target, position},target 填目标层 ID,position 为 "above"、"below"、"into"。', 'layer.select {layer, mode?},mode 为 "replace"、"toggle"、"range"、"add"、"remove"。', 'edit.transform {layer, dx?, dy?, scaleX?, scaleY?, rotate?},位移为像素,缩放为百分比,旋转为度。matrix 可传 [a,b,c,d,e,f]。', - 'shape.info {layer}、path.info {layer} 按图层读取画布像素坐标下的路径。layer.subjectGeometry {layer} 读取已置入图片的主体包围盒和轮廓。用 native_catalog 查 path.moveAnchors、path.moveHandle 和 shape.edit 的参数。', + 'shape.info {layer}、path.info {layer} 按图层读取画布像素坐标下的路径。layer.subjectGeometry {layer} 读取已置入图片的主体包围盒、轮廓、四向极值和高度分带的左右边缘。path.moveAnchors 支持 positions 绝对画布坐标。用 native_catalog 查 path.moveAnchors、path.moveHandle 和 shape.edit 的参数。', 'type.info {layer} 读取文字、段落、排版行与边界。type.edit {layer, text} 替换全文并保留样式。type.setStyle {layer, font?, size?, color?, align?},size 用 pt,color 可填 "#rrggbb",align 常用 "left"、"center"、"right"。', 'layer.layerStyle.dropShadow {layer, color?, opacity?, angle?, distance?, size?};layer.layerStyle.stroke {layer, size?, position?, color?, opacity?},position 为 "inside"、"outside"、"center";layer.layerStyle.colorOverlay {layer, color?, opacity?}。效果 opacity 为 0–100,distance 和 size 为像素。', ].join('\n'); diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index e948795a..61d04805 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -130,7 +130,7 @@ export const productionOperationTools = [ ['adopt_production_image','采用选定的候选,返回画布修订和模板叠层。可用 reason 记录采用理由。单图位屏与已有验图画面一致时附复核结论。screensReadyForReview 列出图位已齐、待复核的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})], ['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})], ['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原请求已收口。网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或 180 秒恢复预算用完后原查询仍是 unresolved 或 404 request_not_found,都会进入此终态。404 request_not_found 收口时按未发起处理。expired 可以为同图位另备新请求;按未发起处理的请求不计入该图位的生图次数,其他已派发请求仍计入。',obj({...outputScope,slotIds:optional(ids)})], - ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry 和 annotationLayout。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({ + ['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry、annotationLayout 和 textClipping。annotationLayout.dimensionGroups 按模板图层编号列出标签和线,subjectBoundsOffsets 为端点减去主体框左、上、右、下边界的坐标差。textClipping 列出越出当前屏的文字图层和墨迹边界矩形 [x,y,w,h]。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({ page:optional(page),pages:optional(Type.Array(page)), region:optional(Type.Tuple([Type.Integer(),Type.Integer(),Type.Integer({minimum:1}),Type.Integer({minimum:1})])), zoom:optional(Type.Number({minimum:1,maximum:4})), diff --git a/apps/detail-agent-pi/src/screen-review.mjs b/apps/detail-agent-pi/src/screen-review.mjs index d0669665..741af53a 100644 --- a/apps/detail-agent-pi/src/screen-review.mjs +++ b/apps/detail-agent-pi/src/screen-review.mjs @@ -57,8 +57,9 @@ export function normalizeScreenReview({screenReview,templateFidelity,...args}) { return args; } -export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout}) { - const layerIds = new Set([...overlayLayers,...(annotationLayout?.texts??[]),...(annotationLayout?.lines??[]),...(templateFidelity?.changes??[]),...(templateFidelity?.retainedTemplateText??[])].map(layer => layer.nativeLayerId)); +export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout,textClipping}) { + const dimensionLayers = annotationLayout?.dimensionGroups?.flatMap(group=>[...group.labels,...group.guides])??[]; + const layerIds = new Set([...overlayLayers,...dimensionLayers,...(textClipping??[]),...(annotationLayout?.texts??[]),...(annotationLayout?.lines??[]),...(templateFidelity?.changes??[]),...(templateFidelity?.retainedTemplateText??[])].map(layer => layer.nativeLayerId)); for (const row of templateFidelity?.factConflicts??[]) { for (const id of row.visibleLayerIds??[]) layerIds.add(id); } @@ -140,7 +141,7 @@ export function screenFindings({overlayLayers,screenCopy,slots,templateFidelity, } export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) { - const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,annotationLayout,fieldRequirements,templateFidelity,screenCopy=[]} = screen.details; + const {revision,screenFingerprint,screenChanged,overlayLayers,overlayGroups,slotGeometry,annotationLayout,fieldRequirements,templateFidelity,textClipping,screenCopy=[]} = screen.details; const images = screen.content.filter(item => item.type === 'image'); if (!screenFingerprint || ![1,2].includes(images.length)) throw Error('未读取到当前屏的实际画面和内容指纹'); if (screenChanged) throw Error('读取画面后本屏已变化,请复查当前屏'); @@ -148,7 +149,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const {product,photos} = await references(); signal?.throwIfAborted(); const example='最小提交示例 '+JSON.stringify({verdict:'pass',summary:'标注与商品部位对齐,文案符合商品资料。'}); - const {facts,normalize,validate} = screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout}); + const {facts,normalize,validate} = screenFindings({overlayLayers,screenCopy,slots,templateFidelity,annotationLayout,textClipping}); let receipt; function prepare(raw) { return validateWorkerArguments('review_output_screen',screenAssessment, @@ -173,14 +174,14 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl const scope = screenReviewScope(variantId,outputId,page); const instructions = [ '按项目锁定的企业 Skill 及小壹补充复核整屏成片。第一张是整屏实际画面,如有模板原屏,它位于成片之后,再后面是本款实拍。', - '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,原生标注也可引用 annotationLayout 中的编号,正文问题填写 screenCopy 中的 field。', + '用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,原生标注也可引用 annotationLayout 或 textClipping 中的编号,正文问题填写 screenCopy 中的 field。', '每项问题只引用一个编号,从本屏对应清单原样复制。一个问题涉及多个字段时逐项填写。找不到对应图位、叠层或文案字段时,省略编号并用 location 描述画面位置。', OVERLAY_SCREEN_FIELDS, TEMPLATE_REVIEW_GUIDANCE('顶层 templateStyle'), SCREEN_REVIEW_REQUIREMENTS, ].join('\n'); const prompt = JSON.stringify({page,revision,product,slots:numberScreenSlots(slots),slotGeometry,annotationLayout, - screenCopy:numberScreenCopy(screenCopy),fieldRequirements,overlayLayers,overlayGroups,templateFidelity,productReferenceCount:photos.length}); + screenCopy:numberScreenCopy(screenCopy),fieldRequirements,overlayLayers,overlayGroups,templateFidelity,textClipping,productReferenceCount:photos.length}); const captions = ['当前整屏成片', ...(images.length===2?['模板原屏']:[]), ...photos.map((_,index) => `本款实拍 ${index + 1}`)]; await runAgent(`screen-${page}`, instructions, prompt, [tool], [...images,...photos], scope, captions,signal); signal?.throwIfAborted(); diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 2fff395d..bf3b8336 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -21,6 +21,8 @@ maxGenerationAttempts: 4 - `read_output_screen` 返回合成画面与图层差异。`page` 从 0 开始,`region` 为画布像素坐标 `[x,y,w,h]`,`zoom` 为 1–4 倍。网格刻度使用原画布坐标。`includeTemplateImage` 返回原屏,`templateLayerId` 返回指定图层的完整原值与现值。 - `canvasFacts` 描述图层与画布关系。`outsideCanvas` 为 true 表示完全在画布外,`emptyBounds` 为 true 表示边界为空。`layerVisible` 是图层自身的可见性,`ancestorsVisible` 是祖先图层的可见性。 - `overlayLayers` 中的 `group` 是直属组,`overlayGroups` 列出各组的本屏成员 ID。`knots` 是形状锚点数,`subjectHit` 表示标注框与估测主体框是否相交。`belowSlot` 按 `fieldId` 列出上方图位,`coverage` 是图位覆盖屏内图层边界的比例,`opacity` 和 `blendMode` 是图位内容的不透明度和混合模式。 +- `annotationLayout.dimensionGroups` 按模板的 dimensionGuides 列出标签、线及源图层编号。各线的 subjectBoundsOffsets 按图位列出端点相对主体包围盒左、上、右、下边界的有符号像素差。 +- `textClipping` 按图层列出原始墨迹边界、屏内边界和屏外边界条带,矩形均为画布坐标 [x,y,w,h]。 - `annotationLayout.texts` 列出文字图层 ID、文字和 `bounds`,`nearestLine` 给出最近线的图层、子路径及像素距离,`subjectOverlap` 按 `slotId` 列出主体框占文字边界的重叠比例。`lines` 列出线的图层、子路径、端点、线宽和 `nearestText`。`crossings` 列出文字图层、线图层、子路径及文字边界内的穿线长度。`truncated` 表示列表有截断。`distanceBasis`、`crossingBasis` 和 `subjectBasis` 分别标明距离、穿线和主体重叠的计算依据。 ## 原生命令 @@ -38,12 +40,12 @@ maxGenerationAttempts: 4 | `layer.list` | 列出文档图层及其可见状态。 | | `shape.info` | 用 `layer` 读取形状的锚点、控制柄、开闭状态、填充和描边,包括虚线。 | | `path.info` | 用 `layer` 查询图层路径,返回子路径及锚点、控制柄。 | -| `path.moveAnchors` | 用 `name: layer` 和 `layer` 指定图层路径,用 `anchors` 列出 `[subpath,knot]`,`move: [dx,dy]` 平移锚点及其控制柄。 | +| `path.moveAnchors` | 用 `layer` 指定图层路径,用 `anchors` 列出 `[subpath,knot]`,`move: [dx,dy]` 平移锚点及其控制柄。positions: [[x,y],…] 则逐一设置对应锚点的绝对画布坐标并平移控制柄,与 move 和 curvature 互斥。 | | `path.moveHandle` | 用 `name: layer`、`layer`、`subpath` 和 `knot` 定位,`handle` 选 `in` 或 `out`,`to` 指定目标坐标。 | | `shape.edit` | 用 `layer` 指定形状,可传 `path`、`move`、`fill` 或 `stroke` 更新几何和样式。 | | `type.info` | 用 `layer` 读取文字及其排版边界。 | | `edit.transform` | 用 `layer` 指定整层变换,`dx`、`dy` 平移,`scaleX`、`scaleY` 缩放,`rotate` 旋转。 | -| `layer.subjectGeometry` | 用 `layer` 查询已置入素材的主体包围盒和简化轮廓。透明素材按像素覆盖度取轮廓,实景图按显著主体估算。 | +| `layer.subjectGeometry` | 用 `layer` 查询已置入素材的主体包围盒、简化轮廓、四向极值像素中心及按高度分带的左右边缘。透明素材按像素覆盖度取轮廓,实景图按显著主体估算。 | | `paint.remove` | 用 `layer` 指定图层,`target: pixels` 指定像素,闭合的 `points` 指定区域,`size` 是笔刷尺寸。`newLayer: true` 可将智能对象的补片保存为剪贴图层。替换候选或改变放置方式时,回填回执的 `hiddenRetouchLayers` 列出已隐藏的旧补片。 | `native_call` 示例 diff --git a/apps/detail-agent-pi/test/screen-review.test.mjs b/apps/detail-agent-pi/test/screen-review.test.mjs index 640be00f..8e3416e4 100644 --- a/apps/detail-agent-pi/test/screen-review.test.mjs +++ b/apps/detail-agent-pi/test/screen-review.test.mjs @@ -125,6 +125,7 @@ async function fixture(t) { state.reads.push(page); if(page>=pages.length)throw Error('此屏不属于当前工作画布'); return {page,revision:state.revision,screenFingerprint:state.fingerprints[page],images:[pixels],fields:[slots[page].fieldId], + textClipping:[{nativeLayerId:600+page,clippedInkBounds:[[100,20,7,14]]}], annotationLayout:{lines:[{nativeLayerId:501+page,endpoints:[[10,20],[10,80]]}]}, ...(state.overlay?{overlayLayers:[{nativeLayerId:201+page,name:'尺寸标注',text:'45cm',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}}, {nativeLayerId:301+page,name:'尺寸线',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}}, @@ -256,7 +257,8 @@ test('非当前成品的候选等待验图时直接读取其已保存画布', {t test('screen reviews keep images in the worker and persist findings and passes',async t=>{ const {host,state,journal}=await fixture(t); host.runDetailAgent=async(_id,system,input,[tool],images,scope)=>{ - const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout}=JSON.parse(input); + const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout,textClipping}=JSON.parse(input); + assert.deepEqual(textClipping,[{nativeLayerId:599+page,clippedInkBounds:[[100,20,7,14]]}]); assert.deepEqual(annotationLayout.lines,[{nativeLayerId:500+page,endpoints:[[10,20],[10,80]]}]); assert.equal(scope,screenReviewScope(variantId,outputId,page)); assert.match(scope,/^product\/review\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/); 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 f8784cd6..15a7bbeb 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -527,6 +527,9 @@ fn prepare_product_template(native: &mut Document, meta: &mut Value, pack: &Valu if let Some(profile) = profile { production_profile::apply(native, meta, profile)?; meta["productionProfile"] = production_profile::source(pack, component); + for page in meta["outputs"].as_array_mut().into_iter().flatten() { + page["dimensionGuides"] = json!(production_profile::screen_dimension_groups(profile, page)); + } } if let Some(policy) = profile.and_then(|profile| profile.get("allowedChanges")) .or_else(|| pack["allowedChanges"].get(component)) @@ -3087,7 +3090,27 @@ impl Backend { } pub(super) fn attach_template_fidelity(&self, native: &Document, receipt: &mut Value, include_image: bool, detail_layer: Option) -> R<()> { - template_fidelity::attach(&self.project_dir(native.id.0)?, native, receipt, include_image, detail_layer); + let dir = self.project_dir(native.id.0)?; + template_fidelity::attach(&dir, native, receipt, include_image, detail_layer); + if receipt["annotationLayout"].is_object() + && let Some(meta) = mapping(native) + && meta["productionProfile"].is_object() + && let Some(index) = receipt["page"].as_u64() + && let Some(page) = meta["outputs"].get(index as usize).filter(|page| page.get("dimensionGuides").is_none()) + && let Ok(state) = load_detail_workspace(&dir) + && let Some(component) = meta["component"].as_str() + && let Some(pack) = [&state["template"], &state["productTemplates"][component]].into_iter() + .find(|pack| pack["contentHash"].is_string() && pack["contentHash"] == meta["templateHash"]) + && let Ok(Some(profile)) = production_profile::select(pack, component) + { + let groups = production_profile::screen_dimension_groups(profile, page); + if !groups.is_empty() { + let area = screen_area(native.bounds(), page)?; + let mut page = page.clone(); + page["dimensionGuides"] = json!(groups); + receipt["annotationLayout"]["dimensionGroups"] = json!(dimension_group_facts(native, &meta, &page, area, receipt)); + } + } Ok(()) } @@ -3346,6 +3369,79 @@ fn screen_annotation_summary_reports_only_box_intersection() { assert!(receipt["overlayLayers"][2].get("subjectHit").is_none()); } +fn dimension_group_facts(native: &Document, meta: &Value, page: &Value, area: photocraft_geom::Rect, receipt: &Value) -> Vec { + use photocraft_ui_egui::jiansun::production_facts::{guide_lines, path_visible}; + let Some(groups) = page["dimensionGuides"].as_array().filter(|groups| !groups.is_empty()) else { + return Vec::new(); + }; + let layers = native.walk(); + let resolve = |source: &Value, kind: &str| { + let id = source.as_u64(); + layers.iter().filter(|(path, _, layer)| { + id.is_some() && production_profile::source_id(meta, layer).map(u64::from) == id + && page["originalGroupId"].as_u64().is_none_or(|group| native.layers[path[0]].id.0 == group) + }).map(|(path, _, layer)| { + let native_id = layer.id.0; + let bounds = photocraft_compose::layer_bounds(layer, native.bounds()); + let mut row = json!({"sourceLayerId":source,"nativeLayerId":native_id,"visible":path_visible(native,path), + "bounds":[bounds.x0,bounds.y0,bounds.width(),bounds.height()]}); + if kind == "guides" { + let lines: Vec<_> = guide_lines(layer, area) + .into_iter().map(|mut line| { + let offsets: Vec<_> = receipt["slotGeometry"].as_array().into_iter().flatten().filter_map(|slot| { + let [x,y,w,h] = serde_json::from_value::<[f64;4]>(slot["subjectBounds"].clone()).ok()?; + let points = serde_json::from_value::<[[f64;2];2]>(line["endpoints"].clone()).ok()?; + Some(json!({"slotId":slot["slotId"],"endpointOffsets":points.map(|[px,py]| + [px-x,py-y,px-x-w,py-y-h])})) + }).collect(); + line["subjectBoundsOffsets"] = json!(offsets); + line + }).collect(); + row["lines"] = json!(lines); + } else if let photocraft_doc::LayerContent::Text(text) = &layer.content { + row["text"] = json!(text.text); + } + (row, !bounds.intersect(&area).is_empty()) + }).collect::>() + }; + groups.iter().filter_map(|group| { + let labels: Vec<_> = group["labels"].as_array().into_iter().flatten().flat_map(|id| resolve(id,"labels")).collect(); + let guides: Vec<_> = group["guides"].as_array().into_iter().flatten().flat_map(|id| resolve(id,"guides")).collect(); + labels.iter().chain(&guides).any(|(_,on_screen)| *on_screen).then(|| json!({ + "source":group, + "labels":labels.into_iter().map(|(row,_)| row).collect::>(), + "guides":guides.into_iter().map(|(row,_)| row).collect::>() + })) + }).collect() +} + +#[test] +fn jiansun_dimension_groups_resolve_original_ids_and_read_hidden_guides() { + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::Layer; + use photocraft_geom::Size; + let mut session = photocraft_engine::Session::new(); + session.add_document(Document::new("Screen", Size::new(80, 80), ColorMode::Rgb, SampleType::U8), None); + session.execute("shape.create", json!({"kind":"path","fill":null,"stroke":{"width":1,"color":"#143251"}, + "path":{"subpaths":[{"closed":false,"knots":[[10,20],[60,20]]}]}})).unwrap(); + let mut doc = session.active().unwrap().doc.as_ref().clone(); + let mut guide = doc.layers.pop().unwrap(); + guide.visible = false; + let guide_id = guide.id.0; + let group = Layer::group("Page", vec![guide]); + let group_id = group.id.0; + doc.layers = vec![group]; + let meta = json!({"originalPsdLayerIds":{(guide_id.to_string()):50}}); + let page = json!({"originalGroupId":group_id,"dimensionGuides":[{"labels":[],"guides":[50]}]}); + let groups = dimension_group_facts(&doc, &meta, &page, doc.bounds(), + &json!({"slotGeometry":[{"slotId":"image","subjectBounds":[12,24,40,38]}]})); + let guide = &groups[0]["guides"][0]; + assert_eq!(guide["nativeLayerId"], guide_id); + assert_eq!(guide["visible"], false); + assert_eq!(guide["lines"][0]["endpoints"], json!([[10.0,20.0],[60.0,20.0]])); + assert_eq!(guide["lines"][0]["subjectBoundsOffsets"][0]["endpointOffsets"][0], json!([-2.0,-4.0,-42.0,-42.0])); +} + fn read_production_screen_with( native: &Document, input: &Value, preview: impl FnOnce(photocraft_geom::Rect) -> R>>, @@ -3362,6 +3458,10 @@ fn read_production_screen_with( let mut receipt = json!({"page":index,"totalPages":pages.len(),"revision":input["revision"],"fields":fields, "screenFingerprint":screen_fingerprint(native, page, area),"overlayLayers":screen_overlay_layers(native, &meta, area, None)}); let with_image = input["signatureOnly"] != true; + if with_image || input["preflight"] == true { + receipt["textClipping"] = json!(photocraft_ui_egui::jiansun::production_facts::text_clipping( + native, area, &page["mapping"]["fields"])); + } let check_blank = input["preflight"] == true && fields.is_empty(); if !with_image && !check_blank { return Ok(receipt); } let jpeg = if input["region"].is_null() { @@ -3405,6 +3505,7 @@ fn read_production_screen_with( if !input["candidatePreview"].is_object() { receipt["annotationLayout"] = photocraft_ui_egui::jiansun::production_facts::annotation_layout( native, area, &receipt["slotGeometry"]); + receipt["annotationLayout"]["dimensionGroups"] = json!(dimension_group_facts(native, &meta, page, area, &receipt)); } if input["candidatePreview"].is_object() { receipt["imageSlots"] = json!(page["mapping"]["fields"].as_array().into_iter().flatten() @@ -8145,6 +8246,6 @@ fn jiansun_annotation_replay() { let meta = mapping(&native).unwrap(); for index in 0..meta["outputs"].as_array().unwrap().len() { let receipt = read_screen_preview(&native,&json!({"page":index})).unwrap(); - println!("{}", json!({"page":index,"annotationLayout":receipt["annotationLayout"],"slotGeometry":receipt["slotGeometry"]})); + println!("{}", json!({"page":index,"annotationLayout":receipt["annotationLayout"],"slotGeometry":receipt["slotGeometry"],"textClipping":receipt["textClipping"]})); } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs index 29a9a06a..c22624e6 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs @@ -71,7 +71,7 @@ fn matches_name(patterns: &Value, name: &str) -> bool { .any(|pattern| !pattern.is_empty() && name.contains(&pattern.to_lowercase())) } -fn source_id(mapping: &Value, layer: &Layer) -> Option { +pub(super) fn source_id(mapping: &Value, layer: &Layer) -> Option { if let Some(ids) = mapping["originalPsdLayerIds"].as_object() { ids.get(&layer.id.0.to_string()).and_then(Value::as_u64).map(|id| id as u32) } else { @@ -104,6 +104,11 @@ fn dimension_groups(profile: &Value) -> impl Iterator { profile["dimensionGuides"].as_array().into_iter().flatten() } +pub(super) fn screen_dimension_groups(profile: &Value, page: &Value) -> Vec { + dimension_groups(profile).chain(page["documentId"].as_str().into_iter() + .flat_map(|id| dimension_groups(&profile["pages"][id]))).cloned().collect() +} + pub(super) fn is_sample_layer(doc: &Document, path: &[usize], profile: &Value, mapping: &Value, layer: &Layer) -> bool { let source = source_id(mapping, layer); let original = original_group(doc, path, mapping); diff --git a/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs b/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs index fd75473d..68e7a5f1 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs @@ -177,6 +177,32 @@ fn subject_geometry(s: &mut Session, p: &Value) -> Result { (area.x0 as f64 + x * step as f64).clamp(area.x0 as f64, area.x1 as f64), (area.y0 as f64 + y * step as f64).clamp(area.y0 as f64, area.y1 as f64), ]; + let mut extrema = [[bounds.x1, 0], [bounds.x0 - 1, 0], [0, bounds.y1], [0, bounds.y0 - 1]]; + const BANDS: i32 = 8; + let mut bands = [(None::<[i32; 2]>, None::<[i32; 2]>); BANDS as usize]; + let height = bounds.y1 - bounds.y0; + for (index, _) in coverage.iter().enumerate().filter(|(_, value)| **value >= 0.5) { + let x = (index % grid.width() as usize) as i32; + let y = (index / grid.width() as usize) as i32; + if x < extrema[0][0] { extrema[0] = [x,y]; } + if x > extrema[1][0] { extrema[1] = [x,y]; } + if y < extrema[2][1] { extrema[2] = [x,y]; } + if y > extrema[3][1] { extrema[3] = [x,y]; } + let (left, right) = &mut bands[((y - bounds.y0) * BANDS / height) as usize]; + if left.is_none_or(|[edge, _]| x < edge) { *left = Some([x,y]); } + if right.is_none_or(|[edge, _]| x > edge) { *right = Some([x,y]); } + } + let center = |[x,y]: [i32; 2]| { + let [left, top] = to_canvas(f64::from(x), f64::from(y)); + let [right, bottom] = to_canvas(f64::from(x+1), f64::from(y+1)); + [(left + right) / 2.0, (top + bottom) / 2.0] + }; + let [subject_left, subject_right, subject_top, subject_bottom] = extrema.map(center); + let horizontal_bands: Vec<_> = bands.into_iter().enumerate().filter_map(|(band, (left, right))| { + let row = |boundary| bounds.y0 + (boundary * height + BANDS - 1) / BANDS; + Some(json!({"yRange":[to_canvas(0.0,f64::from(row(band as i32)))[1], + to_canvas(0.0,f64::from(row(band as i32+1)))[1]],"left":center(left?),"right":center(right?)})) + }).collect(); let path = photocraft_vector::trace::trace_mask(&coverage, grid, 0.0, 2.0); let mut lines = photocraft_vector::flatten_path(&path, 2.0); let area_of = |line: &photocraft_vector::Polyline| { @@ -197,7 +223,7 @@ fn subject_geometry(s: &mut Session, p: &Value) -> Result { }).collect(); let [left, top] = to_canvas(bounds.x0 as f64, bounds.y0 as f64); let [right, bottom] = to_canvas(bounds.x1 as f64, bounds.y1 as f64); - Ok(json!({"layer":id.0,"source":source,"sampleStepPx":step,"bounds":[left,top,right-left,bottom-top],"contours":contours,"simplified":simplified})) + Ok(json!({"extrema":{"left":subject_left,"right":subject_right,"top":subject_top,"bottom":subject_bottom},"horizontalBands":horizontal_bands,"layer":id.0,"source":source,"sampleStepPx":step,"bounds":[left,top,right-left,bottom-top],"contours":contours,"simplified":simplified})) } /// Remove Background command spec (no menu path: a Properties Quick Action in Photoshop). @@ -216,7 +242,7 @@ pub fn specs() -> Vec { label: "Read Layer Subject Geometry", menu: &[], shortcut: None, - params: r##"{"layer":id,"source":"auto|alpha|selectSubject"="auto"} → {layer,source:"alpha|selectSubject",sampleStepPx,bounds:[x,y,w,h]|null,contours:[[[x,y],…],…],simplified} (up to 4 closed polylines, 64 points each in canvas pixels; uses transparency or estimates the most salient subject from the placed image)"##, + params: r##"{"layer":id,"source":"auto|alpha|selectSubject"="auto"} → {layer,source:"alpha|selectSubject",sampleStepPx,bounds:[x,y,w,h]|null,contours:[[[x,y],…],…],extrema:{left,right,top,bottom},horizontalBands:[{yRange,left,right},…],simplified} (up to 4 closed polylines, 64 points each in canvas pixels; extrema and band edges are sample centers; uses transparency or estimates the most salient subject from the placed image)"##, enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), run: subject_geometry, journal: false, @@ -230,7 +256,7 @@ mod tests { use photocraft_doc::LayerId; #[test] - fn subject_geometry_reads_translated_alpha_silhouette_without_editing() { + fn jiansun_subject_geometry_reads_translated_alpha_silhouette_without_editing() { let mut s = Session::new(); s.execute("file.new", json!({"width":100, "height":100})).unwrap(); s.execute("layer.new.layer", json!({"name":"Product"})).unwrap(); @@ -250,6 +276,9 @@ mod tests { let data = s.execute(SUBJECT_INFO, json!({"layer":id.0})).unwrap(); assert_eq!(data["source"], "alpha"); assert_eq!(data["bounds"], json!([20.0,30.0,20.0,20.0])); + assert_eq!(data["extrema"]["left"], json!([20.5,30.5])); + assert_eq!(data["extrema"]["bottom"], json!([20.5,49.5])); + assert_eq!(data["horizontalBands"][7]["right"], json!([29.5,48.5])); let contour = data["contours"][0].as_array().unwrap(); assert!(contour.iter().any(|p| { let x = p[0].as_f64().unwrap(); diff --git a/apps/detail-photocraft/crates/engine/src/cmd/path_edit_cmds.rs b/apps/detail-photocraft/crates/engine/src/cmd/path_edit_cmds.rs index 75839357..af443c19 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/path_edit_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/path_edit_cmds.rs @@ -94,6 +94,15 @@ fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce( fn move_anchors(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.moveAnchors"; + // Match path.info when a caller passes an explicit layer without a path name. + let mut layer_target; + let p = if p.get("name").is_none() && p.get("layer").is_some() { + layer_target = p.clone(); + layer_target["name"] = json!("layer"); + &layer_target + } else { + p + }; let anchors: Vec<[usize; 2]> = p .get("anchors") .and_then(Value::as_array) @@ -105,6 +114,16 @@ fn move_anchors(s: &mut Session, p: &Value) -> Result { n(0).zip(n(1)).map(|(s, k)| [s, k]).ok_or_else(|| bad(CMD, "each anchor is [subpath, knot]")) }) .collect::>()?; + if let Some(positions) = p.get("positions") { + let targets: Vec<[f64; 2]> = serde_json::from_value(positions.clone()) + .map_err(|_| bad(CMD, "positions must list canvas [x,y] coordinates"))?; + if targets.len() != anchors.len() || targets.iter().any(|target| !finite(*target)) + || p.get("move").is_some() || p["curvature"] == true + { + return Err(bad(CMD, "provide one finite position per anchor without move or curvature")); + } + return edit_path(s, CMD, p, "Set Anchor Positions", |path| edit::set_anchors(path, &anchors, &targets)); + } let d = offset(CMD, p)?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { return edit_path(s, CMD, p, "Drag Anchor Points", |path| edit::move_anchors_curvature(path, &anchors, d)); @@ -251,7 +270,7 @@ pub fn specs() -> Vec { journal: true, }; vec![ - spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors)"#.into(), move_anchors), + spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy] or "positions":[[x,y],…] (one absolute canvas position per anchor, without curvature; explicit layer selects its path when name is omitted),"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors)"#.into(), move_anchors), spec( "path.moveHandle", "Drag Direction Point", @@ -322,6 +341,19 @@ mod tests { s.active().unwrap().doc.work_path.clone().unwrap() } + #[test] + fn jiansun_absolute_anchor_positions_are_atomic_and_undoable() { + let mut s = session(); + s.execute("path.set", json!({"path": square()})).unwrap(); + let before = work(&s); + assert!(s.execute("path.moveAnchors", json!({"anchors":[[0,1],[0,9]],"positions":[[12,14],[20,22]]})).is_err()); + assert_eq!(work(&s), before); + let r = s.execute("path.moveAnchors", json!({"anchors":[[0,1],[0,2]],"positions":[[12.5,14],[20,22]]})).unwrap(); + assert_eq!((anchor(&r,1), anchor(&r,2)), ([12.5,14.0], [20.0,22.0])); + assert!(s.undo()); + assert_eq!(work(&s), before); + } + #[test] fn anchors_move_in_one_undoable_step() { let mut s = session(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs index 41edbe97..44173fbd 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs @@ -1646,7 +1646,7 @@ mod tests { let mut execute = |id, params| command(&mut w, &mut app, id, params); let style = execute("shape.info", json!({"layer":curve}))["stroke"].clone(); let move_anchor = |execute: &mut dyn FnMut(&'static str, Value) -> Value, layer: u64, knot: usize, delta: [i32; 2]| { - execute("path.moveAnchors", json!({"name":"layer","layer":layer,"anchors":[[0,knot]],"move":delta})); + execute("path.moveAnchors", json!({"layer":layer,"anchors":[[0,knot]],"move":delta})); }; move_anchor(&mut execute, curve, 0, [3,-1]); move_anchor(&mut execute, curve, 1, [2,3]); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs index 8e613c4c..1e93de00 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts.rs @@ -479,4 +479,4 @@ fn layer_canvas_facts_distinguish_empty_bounds_from_off_canvas_and_hidden_parent } mod annotation_layout; -pub use annotation_layout::annotation_layout; +pub use annotation_layout::{annotation_layout, guide_lines, text_clipping}; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs index 25fd027d..a87931dd 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/production_facts/annotation_layout.rs @@ -122,6 +122,63 @@ fn line_geometry(id: u64, shape: &photocraft_doc::ShapeLayer, max_bar_width: f64 })) } +pub fn guide_lines(layer: &photocraft_doc::Layer, area: Rect) -> Vec { + let LayerContent::Shape(shape) = &layer.content else { return Vec::new(); }; + line_geometry(layer.id.0, shape, f64::from(area.width().min(area.height())) / 32.0) + .map(|line| json!({"subpath":line.subpath,"endpoints":line.endpoints,"width":line.width})) + .collect() +} + +/// Reports the portions of text ink bounds outside the exported screen. +pub fn text_clipping(doc: &Document, area: Rect, fields: &Value) -> Vec { + let rect = |r: Rect| [r.x0, r.y0, r.width() as i32, r.height() as i32]; + doc.walk().into_iter().filter_map(|(path, _, layer)| { + let LayerContent::Text(text) = &layer.content else { return None }; + if !path_visible(doc, &path) || layer.fill_opacity == 0.0 { return None; } + let ink = layer.surface()?.content_bounds(); + let visible = ink.intersect(&area); + let mapped = fields.as_array().into_iter().flatten().any(|field| field["nativeLayerId"] == layer.id.0); + let spans_screen_rows = ink.y0 < area.y1 && area.y0 < ink.y1; + if ink.is_empty() || ink == visible || visible.is_empty() && !mapped && !spans_screen_rows { return None; } + let clipped: Vec<_> = if visible.is_empty() { + vec![rect(ink)] + } else { + [ + Rect::new(ink.x0, ink.y0, ink.x1, visible.y0), + Rect::new(ink.x0, visible.y1, ink.x1, ink.y1), + Rect::new(ink.x0, visible.y0, visible.x0, visible.y1), + Rect::new(visible.x1, visible.y0, ink.x1, visible.y1), + ].into_iter().filter(|r| !r.is_empty()).map(rect).collect() + }; + Some(json!({"nativeLayerId":layer.id.0,"text":text.text,"inkBounds":rect(ink), + "visibleInkBounds":(!visible.is_empty()).then(|| rect(visible)), "clippedInkBounds":clipped})) + }).collect() +} + +#[test] +fn jiansun_text_clipping_reports_export_edge_and_fully_outside_mapped_text() { + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::{Layer, TextLayer}; + use photocraft_geom::Size; + use photocraft_raster::Surface; + + let mut doc = Document::new("Screen", Size::new(20, 20), ColorMode::Rgb, SampleType::U8); + for x in [17, 25] { + let mut cache = Surface::new(doc.pixel_format()); + cache.fill_rect(Rect::new(x, 3, x + 7, 7), &[0.0, 0.0, 0.0, 1.0]); + doc.layers.push(Layer::new("Text", LayerContent::Text(TextLayer { + text:"820mm".into(), cache:Some(cache), ..Default::default() + }))); + } + let mapped = json!([{"nativeLayerId":doc.layers[1].id.0}]); + let rows = text_clipping(&doc, doc.bounds(), &mapped); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0]["visibleInkBounds"], json!([17,3,3,4])); + assert_eq!(rows[0]["clippedInkBounds"], json!([[20,3,4,4]])); + assert_eq!(rows[1]["visibleInkBounds"], Value::Null); + assert_eq!(rows[1]["clippedInkBounds"], json!([[25,3,7,4]])); +} + pub fn annotation_layout(doc: &Document, area: Rect, slots: &Value) -> Value { const LIMIT: usize = 48; let max_bar_width = f64::from(area.width().min(area.height())) / 32.0; diff --git a/apps/detail-photocraft/crates/vector/src/edit.rs b/apps/detail-photocraft/crates/vector/src/edit.rs index 7f1f4d58..f815b3c7 100644 --- a/apps/detail-photocraft/crates/vector/src/edit.rs +++ b/apps/detail-photocraft/crates/vector/src/edit.rs @@ -122,6 +122,21 @@ pub fn move_anchors(path: &mut Path, anchors: &[[usize; 2]], d: [f64; 2]) -> Res Ok(()) } +/// Sets each anchor in canvas coordinates and translates its handles with it. +pub fn set_anchors(path: &mut Path, anchors: &[[usize; 2]], positions: &[[f64; 2]]) -> Result<(), String> { + for &anchor in anchors { + knot_mut(path, anchor)?; + } + for (&anchor, &[x, y]) in anchors.iter().zip(positions) { + let knot = knot_mut(path, anchor)?; + let delta = [x - knot.anchor.x, y - knot.anchor.y]; + knot.in_ctrl = add(knot.in_ctrl, delta); + knot.out_ctrl = add(knot.out_ctrl, delta); + knot.anchor = Point::new(x, y); + } + Ok(()) +} + /// The Curvature Pen's anchor drag: moves the anchors like [`move_anchors`], then recomputes the /// handles of every smooth knot in the subpaths it touched with [`curvature_knots`], so the curve /// keeps flowing smoothly through all its anchors, as Photoshop does. Corner knots keep their own