diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index f0f1497f..b8e80bca 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -14,6 +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 的参数。', '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/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index ff9744f7..681ac865 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 @@ -24,3 +24,13 @@ maxGenerationAttempts: 4 模板和项目锁定的品牌调性共同定义设计语言。按需读取 kind=brand 的资料来决定文案语气、配色和字体。默认保留模板元素、布局和图层样式,替换与本款有关的内容。确有必要调整或去掉元素时,在对应字段的 record_field_requirements 中记录原因;未映射的图层可用 record_screen_check 的问题记录在 field 中填写 nativeLayerId,在 reason 中记录理由及去留意见。 read_output_screen 默认提供当前成片、图层差异摘要及可见模板原文。需对照时用 includeTemplateImage 读取原屏,用 templateLayerId 看该层完整原值和现值。对照两张画面核对差异是否符合品牌调性。把原稿中的数值、材质和品牌文字与当前商品证据逐项核对,按图层定位;有字段时可登记事实依据,未映射时登记叠层问题。 + +## 画布上的产品标注 + +弧形虚线、引线、端点、尺寸和标题装饰都是模板设计的一部分。用屏幕总览找本屏的图位、标注和所属组,按图层 ID 用 `shape.info` 读取形状的锚点、控制柄、开闭、填充及描边(含虚线),用 `path.info {layer}` 读取其他矢量路径。默认屏幕回执中的 `knots` 是形状锚点数,`subjectHit` 表示标注包围盒是否和本屏估测的主体包围盒相交。坐标以整个画布左上角为原点,单位像素。需要核对未出现在屏幕总览的图层时,可用 `layer.list` 查文档图层及其可见状态。 + +- `layer.subjectGeometry {layer}` 读取已置入图层的主体包围盒和简化轮廓。透明素材按像素覆盖度取轮廓,实景图按显著主体估算。用实际屏幕图辨认具体部位,尤其是内部接缝、反光和被遮挡的边缘。 +- 产品有对应部位时,按本款的边缘和部位位置用 `path.moveAnchors`、`path.moveHandle`、`shape.edit` 等调线及端点,保留原有样式。仅当本款确实没有对应部位时移除该标注,并记录原因。 +- 尺寸图按本款资料更新数字和单位,同时对齐尺寸线与端点,保留图示布局。尺寸图不能改为纯文字列表。 +- 标题改字后用 `type.info` 读排版边界,检查单独图层上的括号、短线和引线是否需要对位。栅格或智能对象装饰可用 `edit.transform` 整层移位。说明文案也要检查边界和参考线。 +- 用 `native_catalog` 查具体参数。编辑后按需回读几何并查看 `read_output_screen` 的实际成图,核对曲线贴合、端点指向、文字溢出和尺寸对应关系。 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 edb798de..430e9aea 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3105,6 +3105,42 @@ fn read_screen_preview(native: &Document, input: &Value) -> R { read_production_screen_with(native, input, |area| screen_preview::render(native, area).map(std::sync::Arc::new)) } +// Screen summaries compare annotation bounds with the detected subject box. Exact +// path and silhouette geometry remain opt-in native reads. +fn add_annotation_subject_hits(receipt: &mut Value) { + let box_rect = |value: &Value| { + let [x, y, width, height] = serde_json::from_value::<[i32; 4]>(value.clone()).ok()?; + Some(photocraft_geom::Rect::from_xywh(x, y, width as u32, height as u32)) + }; + let subjects: Vec<_> = receipt["slotGeometry"].as_array().into_iter().flatten() + .filter_map(|slot| box_rect(&slot["subjectBounds"])) + .collect(); + if subjects.is_empty() { return; } + if let Some(overlays) = receipt["overlayLayers"].as_array_mut() { + for overlay in overlays.iter_mut().filter(|row| row["kind"] == "shape") { + if let Some(bounds) = box_rect(&overlay["bounds"]) { + overlay["subjectHit"] = json!(subjects.iter().any(|subject| !subject.intersect(&bounds).is_empty())); + } + } + } +} + +#[test] +fn screen_annotation_summary_reports_only_box_intersection() { + let mut receipt = json!({ + "slotGeometry":[{"subjectBounds":[10,10,40,40]}], + "overlayLayers":[ + {"kind":"shape","knots":2,"bounds":[5,20,20,2]}, + {"kind":"shape","knots":2,"bounds":[5,0,20,2]}, + {"kind":"text","bounds":[5,20,20,2]} + ] + }); + add_annotation_subject_hits(&mut receipt); + assert_eq!(receipt["overlayLayers"][0]["subjectHit"], true); + assert_eq!(receipt["overlayLayers"][1]["subjectHit"], false); + assert!(receipt["overlayLayers"][2].get("subjectHit").is_none()); +} + fn read_production_screen_with( native: &Document, input: &Value, preview: impl FnOnce(photocraft_geom::Rect) -> R>>, @@ -3146,6 +3182,7 @@ fn read_production_screen_with( } row }).collect::>()); + add_annotation_subject_hits(&mut receipt); if input["candidatePreview"].is_object() { receipt["imageSlots"] = json!(page["mapping"]["fields"].as_array().into_iter().flatten() .filter(|field| field["kind"] == "image").filter_map(|field| field["slotId"].as_str()).collect::>()); 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 14ae59f0..fd75473d 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/cutout_cmds.rs @@ -88,6 +88,118 @@ fn run(s: &mut Session, p: &Value) -> Result { ) } +/// Read the silhouette of the image already placed in canvas coordinates. +const SUBJECT_INFO: &str = "layer.subjectGeometry"; + +fn subject_geometry(s: &mut Session, p: &Value) -> Result { + use photocraft_algo::segment::{ImageSampler, RgbImage}; + + let id = layer_param(s, p)?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let surface = layer.surface().ok_or_else(|| EngineError::Other("layer has no rendered pixels".into()))?; + let mut area = surface.content_bounds().intersect(&doc.bounds()); + // The template's clip can crop a placed photograph without changing its cached pixels. + let vector_mask = layer.vector_mask.as_ref().filter(|mask| mask.enabled); + if let Some(mask) = vector_mask.filter(|mask| !mask.path.inverted && mask.density >= 1.0) + && let Some((x0, y0, x1, y1)) = mask.path.control_bounds() + { + area = area.intersect(&Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32)); + } + let empty = json!({"layer":id.0,"bounds":null,"contours":[]}); + if area.is_empty() { + return Ok(empty); + } + + // Sample in canvas space. Keep both segmentation work and contour tracing independent + // of the size of the source image and of the surrounding multi-screen document. + let step = area.width().max(area.height()).div_ceil(256); + let grid = Rect::from_xywh(0, 0, area.width().div_ceil(step), area.height().div_ceil(step)); + let mut pixels = Vec::with_capacity(grid.width() as usize * grid.height() as usize); + for row in 0..grid.height() { + for col in 0..grid.width() { + let x = area.x0 + (col * step + step / 2).min(area.width() - 1) as i32; + let y = area.y0 + (row * step + step / 2).min(area.height() - 1) as i32; + let mut pixel = [[0.0; 4]]; + surface.read_rgba_into(Rect::from_xywh(x, y, 1, 1), &mut pixel); + pixels.push(pixel[0]); + } + } + let transparent = match p.get("source").and_then(Value::as_str) { + Some("alpha") => true, + Some("selectSubject") => false, + _ => pixels.iter().filter(|pixel| pixel[3] < 0.5).count() > pixels.len() / 50, + }; + let (mut coverage, source) = if transparent { + (pixels.iter().map(|pixel| pixel[3]).collect::>(), "alpha") + } else { + let image = RgbImage::from_rgba(&pixels, grid.width() as usize, grid.height() as usize); + let sampler = ImageSampler { img: &image, origin: (0, 0) }; + let Some(region) = subject::select_subject(&sampler, grid) else { return Ok(empty) }; + let mut coverage = Vec::with_capacity(pixels.len()); + for y in 0..grid.y1 { + for x in 0..grid.x1 { + coverage.push(region.at(x, y)); + } + } + (coverage, "selectSubject") + }; + + if let Some(mask) = vector_mask { + use photocraft_geom::Affine; + let transform = Affine::translate(-f64::from(area.x0), -f64::from(area.y0)) + .then(&Affine::scale(1.0 / f64::from(step))); + let mask = photocraft_doc::VectorMask { path: mask.path.transform(&transform), ..mask.clone() }; + for (value, clip) in coverage.iter_mut().zip(photocraft_vector::vector_mask_values(&mask, grid)) { + *value *= clip; + } + } + let mut bounds = Rect::new(grid.x1, grid.y1, 0, 0); + for (i, value) in coverage.iter_mut().enumerate() { + let x = (i % grid.width() as usize) as i32; + let y = (i / grid.width() as usize) as i32; + if let Some(mask) = &layer.mask { + let px = area.x0 + ((x as u32 * step + step / 2).min(area.width() - 1)) as i32; + let py = area.y0 + ((y as u32 * step + step / 2).min(area.height() - 1)) as i32; + *value *= mask.value(px, py); + } + if *value >= 0.5 { + bounds.x0 = bounds.x0.min(x); + bounds.y0 = bounds.y0.min(y); + bounds.x1 = bounds.x1.max(x + 1); + bounds.y1 = bounds.y1.max(y + 1); + } + } + if bounds.is_empty() { + return Ok(empty); + } + let to_canvas = |x: f64, y: f64| [ + (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 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| { + let points = &line.pts; + points.iter().zip(points.iter().cycle().skip(1)) + .map(|((x0, y0), (x1, y1))| x0 * y1 - x1 * y0).sum::().abs() + }; + lines.sort_by(|a, b| area_of(b).total_cmp(&area_of(a))); + const MAX_CONTOURS: usize = 4; + const MAX_POINTS: usize = 64; + let simplified = lines.len() > MAX_CONTOURS || lines.iter().take(MAX_CONTOURS).any(|line| line.pts.len() > MAX_POINTS); + let contours: Vec> = lines.into_iter().take(MAX_CONTOURS).map(|line| { + let count = line.pts.len().min(MAX_POINTS); + (0..count).map(|index| { + let (x, y) = line.pts[index * line.pts.len() / count]; + to_canvas(x, y).map(|value| (value * 10.0).round() / 10.0) + }).collect() + }).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})) +} + /// Remove Background command spec (no menu path: a Properties Quick Action in Photoshop). pub fn specs() -> Vec { vec![CommandSpec { @@ -99,6 +211,15 @@ pub fn specs() -> Vec { enabled, run, journal: true, + }, CommandSpec { + id: SUBJECT_INFO, + 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)"##, + enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), + run: subject_geometry, + journal: false, }] } @@ -108,6 +229,112 @@ mod tests { use photocraft_algo::segment::Rng; use photocraft_doc::LayerId; + #[test] + fn 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(); + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("Place pixels", |doc, _| { + let surface = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + for y in 30..50 { + for x in 20..40 { + if x < 30 || y < 40 { + surface.write_pixel(x, y, &[0.6, 0.2, 0.1, 1.0]); + } + } + } + Ok(()) + }).unwrap(); + let revision = s.active().unwrap().revision; + 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])); + let contour = data["contours"][0].as_array().unwrap(); + assert!(contour.iter().any(|p| { + let x = p[0].as_f64().unwrap(); + let y = p[1].as_f64().unwrap(); + (x - 30.0).abs() < 2.0 && (y - 40.0).abs() < 2.0 + })); + assert_eq!(s.active().unwrap().revision, revision); + } + + #[test] + #[ignore = "local layered-document demo, requires JIANSUN_VECTOR_DEMO_DIR"] + fn subject_geometry_annotation_demo() { + use photocraft_codecs::{ChannelLayout, Format, Image, SampleType, decode, encode}; + use std::{fs, path::PathBuf}; + + let dir = PathBuf::from(std::env::var_os("JIANSUN_VECTOR_DEMO_DIR").unwrap()); + let plan: Value = serde_json::from_slice(&fs::read(dir.join("chair-plan.json")).unwrap()).unwrap(); + let doc = photocraft_format::load_draft(&dir.join("SFY-CHAIR-001-input.pcraft"), &dir.join("draft-objects")).unwrap(); + let mut session = Session::new(); + session.add_document(doc, None); + + for image in plan["images"].as_array().unwrap() { + let id = LayerId(image["layer"].as_u64().unwrap()); + let x = image["x"].as_i64().unwrap() as i32; + let y = image["y"].as_i64().unwrap() as i32; + let path = dir.join(image["file"].as_str().unwrap()); + let rgba = decode(&fs::read(path).unwrap()).unwrap().convert(ChannelLayout::Rgba, SampleType::U8); + session.edit("Mount alternate product reference", |doc, _| { + let layer = doc.layer_mut(id).unwrap(); + let LayerContent::Smart(smart) = &mut layer.content else { panic!("expected a product image slot") }; + let format = smart.cache.as_ref().unwrap().format(); + let mut surface = photocraft_raster::Surface::new(format); + let samples: Vec<_> = rgba.data().iter().map(|&value| f32::from(value) / 255.0).collect(); + assert_eq!(surface.channels(), 4); + surface.write_region(Rect::from_xywh(x, y, rgba.width(), rgba.height()), &samples); + smart.cache = Some(surface); + Ok(()) + }).unwrap(); + } + let mut evidence = Vec::new(); + for phase in ["before", "after"] { + for step in plan[phase].as_array().unwrap() { + let id = step["command"].as_str().unwrap(); + let params = step["params"].clone(); + let result = session.execute(id, params.clone()).unwrap_or_else(|error| panic!("{id} {params}: {error}")); + evidence.push(json!({"phase":phase,"command":id,"params":params,"result":result})); + } + if phase == "after" { + let title = &plan["titleAlignment"]; + let id = title["layer"].as_u64().unwrap(); + let info = session.execute("type.info", json!({"layer":id})).unwrap(); + let [left, top, right, bottom]: [i32; 4] = serde_json::from_value(info["bounds"].clone()).unwrap(); + let origin = info["transform"][4].as_f64().unwrap(); + let left = left.min((origin + info["lines"][0]["x0"].as_f64().unwrap()).floor() as i32); + let right = right.max((origin + info["lines"][0]["x1"].as_f64().unwrap()).ceil() as i32); + let gap = title["gap"].as_i64().unwrap() as i32; + let shift = (title["rightLimit"].as_i64().unwrap() as i32 - right).min(0); + if shift != 0 { + session.execute("edit.transform", json!({"layer":id,"dx":shift})).unwrap(); + } + for (role, x, y) in [("leftDecoration", left + shift - gap, top), ("rightDecoration", right + shift + gap, bottom)] { + let id = LayerId(title[role].as_u64().unwrap()); + let doc = &session.active().unwrap().doc; + let bounds = photocraft_compose::layer_bounds(doc.layer(id).unwrap(), doc.bounds()); + let dx = if role == "leftDecoration" { x - bounds.x1 } else { x - bounds.x0 }; + let dy = if role == "leftDecoration" { y - bounds.y0 } else { y - bounds.y1 }; + let params = json!({"layer":id.0,"dx":dx,"dy":dy}); + let result = session.execute("edit.transform", params.clone()).unwrap(); + evidence.push(json!({"phase":phase,"command":"edit.transform","params":params,"result":result})); + } + let result = session.execute("type.info", json!({"layer":id})).unwrap(); + evidence.push(json!({"phase":phase,"command":"type.info","params":{"layer":id},"result":result})); + } + let doc = &session.active().unwrap().doc; + for screen in plan["screens"].as_array().unwrap() { + let [x,y,w,h]: [i32; 4] = serde_json::from_value(screen["rect"].clone()).unwrap(); + let rgba = photocraft_compose::render(doc, Rect::from_xywh(x, y, w as u32, h as u32)).to_rgba8(); + let image = Image::from_u8(rgba.width, rgba.height, ChannelLayout::Rgba, rgba.pixels).unwrap(); + let png = encode(&image, Format::Png, &Default::default()).unwrap(); + fs::write(dir.join(format!("{}-{phase}.png", screen["name"].as_str().unwrap())), png).unwrap(); + } + } + fs::write(dir.join("chair-native-operations.json"), serde_json::to_vec_pretty(&evidence).unwrap()).unwrap(); + } + fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); @@ -152,6 +379,18 @@ mod tests { (s, inside) } + #[test] + fn subject_geometry_estimates_foreground_in_an_opaque_photo() { + let (mut s, _) = disc(8); + let id = active_id(&s); + let result = s.execute(SUBJECT_INFO, json!({"layer":id.0})).unwrap(); + assert_eq!(result["source"], "selectSubject"); + for (actual, expected) in result["bounds"].as_array().unwrap().iter().zip([55.0, 35.0, 90.0, 90.0]) { + assert!((actual.as_f64().unwrap() - expected).abs() < 12.0); + } + assert!(!result["contours"].as_array().unwrap().is_empty()); + } + fn active_id(s: &Session) -> LayerId { s.active().unwrap().active_layer.unwrap() } diff --git a/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds.rs b/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds.rs index 5f6b3c30..23bf6fb6 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds.rs @@ -118,7 +118,7 @@ pub fn specs() -> Vec { label: "Shape Layer Info", menu: &[], shortcut: None, - params: r##"{"layer":id?} → {layer,name,kind,path,fill,stroke,live,bounds:[x,y,w,h]}"##, + params: r##"{"layer":id?} → {layer,parentLayerId,name,kind,path,fill,stroke,live,bounds:[x,y,w,h]} (path anchors and handles are canvas pixels)"##, enabled: has_layer, run: |s, p| { let id = layer_id(s, p)?; @@ -142,10 +142,24 @@ pub fn specs() -> Vec { label: "Path Info", menu: &[], shortcut: None, - params: r##"{"name":str|"work"|"layer"="work"} → {name,path}"##, + params: r##"{"name":str|"work"|"layer"="work","layer":id?} → {name,layer?,parentLayerId?,path} (layer targets its shape path or vector mask; canvas pixels)"##, enabled: has_doc, run: |s, p| { let name = p.get("name").and_then(Value::as_str); + if p.get("layer").is_some() { + let id = layer_id(s, p)?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let path = match &layer.content { + LayerContent::Shape(shape) => Some(&shape.path), + _ => layer.vector_mask.as_ref().map(|mask| &mask.path), + }.ok_or_else(|| EngineError::Other("layer has no shape path or vector mask".into()))?; + let parent = doc.path_of(id).and_then(|mut path| { + path.pop(); + doc.layer_at(&path).map(|group| group.id.0) + }); + return Ok(json!({"name":"layer","layer":id.0,"parentLayerId":parent,"path":path_json(path)})); + } let path = resolve_path(s, name)?; Ok(json!({ "name": name.unwrap_or("work"), "path": path_json(&path) })) }, diff --git a/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds/shape.rs b/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds/shape.rs index 961e7679..72cff70b 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/vector_cmds/shape.rs @@ -250,8 +250,13 @@ pub(super) fn shape_info(s: &Session, id: LayerId) -> Result { return Err(EngineError::Other(format!("layer {} is {} {} layer, not a shape layer", id.0, l.content.article(), l.content.kind_name()))); }; let bounds = sh.cache.as_ref().map(|c| c.content_bounds()).filter(|r| !r.is_empty()).map(|r| json!([r.x0, r.y0, r.width(), r.height()])); + let parent = d.doc.path_of(id).and_then(|mut path| { + path.pop(); + d.doc.layer_at(&path).map(|group| group.id.0) + }); Ok(json!({ "layer": id.0, + "parentLayerId": parent, "name": l.name, "path": path_json(&sh.path), "fill": sh.fill.as_ref().map(fill_json), 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 ca6fc44e..a9765b0c 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 @@ -1320,6 +1320,119 @@ mod tests { assert!(!app.session.active().unwrap().doc.layer(layer).unwrap().visible); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn production_native_annotation_geometry_roundtrip() { + let (mut w, mut app, _) = fixture(); + let product = app.session.active().unwrap().active_layer.unwrap(); + app.session.edit("Place product pixels", |doc, _| { + let surface = doc.layer_mut(product).unwrap().surface_mut().unwrap(); + for y in 23..49 { + for x in 15..43 { + if x < 37 || y > 27 { + surface.write_pixel(x, y, &[0.24, 0.46, 0.65, 1.0]); + } + } + } + Ok(()) + }).unwrap(); + app.background_jobs = true; + w.pi_request_scope["productProduction"] = json!(true); + w.expected_revision = app.session.active().unwrap().revision; + fn command(w: &mut Workspace, app: &mut PhotocraftApp, command: &str, params: Value) -> Value { + let mut result = invoke(w, app, "engine.execute", json!({"command":command,"params":params})).unwrap(); + if let Some(job) = result["job"].as_u64().map(JobId) { + app.session.wait_job(job).unwrap(); + result = settle_jobs(w, app).into_iter().find(|receipt| receipt["job"] == job.0).unwrap(); + } + assert_eq!(result["executed"], true, "{command}: {result}"); + result["result"].clone() + } + for id in ["shape.info", "shape.edit", "path.info", "path.moveAnchors", "path.moveHandle", "layer.subjectGeometry"] { + let mut input = base(&w); + input["id"] = json!(id); + let response = catalog(&w, &mut app, &input).unwrap(); + let entry = &response["items"][0]; + assert_eq!(entry["id"], id); + assert!(entry["parameterDocs"].is_string()); + } + let mut execute = |id, params| command(&mut w, &mut app, id, params); + let geometry = execute("layer.subjectGeometry", json!({"layer":product.0})); + assert_eq!(geometry["bounds"], json!([15.0,23.0,28.0,26.0])); + assert!(!geometry["contours"].as_array().unwrap().is_empty()); + let mut create_path = |name: &str, start: [i32; 2], end: [i32; 2], dashes: Value| { + execute("shape.create", json!({"kind":"path","name":name,"fill":null, + "stroke":{"width":1,"color":"#143251","dashes":dashes}, + "path":{"subpaths":[{"closed":false,"knots":[{"anchor":start},{"anchor":end}]}]}})) + ["layer"].as_u64().unwrap() + }; + let curve = create_path("Edge", [12,24], [35,20], json!([3,2])); + let leader = create_path("Leader", [48,25], [50,32], json!([])); + let measure = create_path("Width", [12,54], [48,54], json!([])); + let dot = execute("shape.create", json!({"kind":"ellipse","rect":[49,31,2,2],"fill":"#143251"}))["layer"].as_u64().unwrap(); + let caption = execute("type.create", json!({"text":"Details","x":57,"y":24,"size":5}))["layer"].as_u64().unwrap(); + let value = execute("type.create", json!({"text":"18 cm","x":22,"y":61,"size":5}))["layer"].as_u64().unwrap(); + let title = execute("type.create", json!({"text":"A","x":10,"y":11,"size":7}))["layer"].as_u64().unwrap(); + let bracket = execute("shape.create", json!({"kind":"rect","rect":[17,7,1,5],"fill":"#143251"}))["layer"].as_u64().unwrap(); + + let group = execute("layer.new.group", json!({"name":"Product annotation"}))["layer"].as_u64().unwrap(); + execute("layer.moveTo", json!({"layer":curve,"target":group,"position":"into"})); + execute("layer.moveTo", json!({"layer":leader,"target":group,"position":"into"})); + + let demo = std::env::var_os("JIANSUN_VECTOR_DEMO_DIR").map(std::path::PathBuf::from); + fn export_fixture(app: &PhotocraftApp, dir: &std::path::Path, name: &str) { + let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; + std::fs::write(dir.join(name), bytes).unwrap(); + } + if let Some(dir) = &demo { + export_fixture(&app, dir, "generic-before.png"); + } + 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})); + }; + move_anchor(&mut execute, curve, 0, [3,-1]); + move_anchor(&mut execute, curve, 1, [2,3]); + execute("path.moveHandle", json!({"name":"layer","layer":curve,"subpath":0,"knot":0,"handle":"out","to":[22,23],"independent":true})); + move_anchor(&mut execute, leader, 1, [-9,0]); + execute("shape.edit", json!({"layer":dot,"move":[-9,0]})); + let caption_info = execute("type.info", json!({"layer":caption})); + let caption_right = caption_info["lines"][0]["x1"].as_f64().unwrap() + caption_info["transform"][4].as_f64().unwrap(); + let dx = 61 - caption_right.ceil() as i32; + assert!(dx < 0); + execute("edit.transform", json!({"layer":caption,"dx":dx})); + let caption_after = execute("type.info", json!({"layer":caption}))["bounds"][2].as_i64().unwrap(); + assert!(caption_after <= 62); + move_anchor(&mut execute, measure, 0, [3,0]); + move_anchor(&mut execute, measure, 1, [-5,0]); + execute("type.edit", json!({"layer":value,"text":"28 cm"})); + execute("type.edit", json!({"layer":title,"text":"Product"})); + let title_right = execute("type.info", json!({"layer":title}))["bounds"][2].as_i64().unwrap(); + execute("shape.edit", json!({"layer":bracket,"move":[title_right + 2 - 17,0]})); + + let read_curve = execute("shape.info", json!({"layer":curve})); + assert_eq!(style["dashes"], json!([3.0,2.0])); + assert_eq!(read_curve["stroke"], style); + assert_eq!(read_curve["parentLayerId"], group); + assert_eq!(read_curve["path"]["subpaths"][0]["closed"], false); + assert_eq!(read_curve["path"]["subpaths"][0]["knots"][0]["out"], json!([22.0,23.0])); + let endpoint = |value: &Value, index: usize| value["path"]["subpaths"][0]["knots"][index]["anchor"].clone(); + let read_leader = execute("path.info", json!({"layer":leader})); + assert_eq!(read_leader["parentLayerId"], group); + assert_eq!(endpoint(&read_leader, 1), json!([41.0,32.0])); + assert_eq!(execute("shape.info", json!({"layer":dot}))["bounds"], json!([40,31,2,2])); + let line = execute("path.info", json!({"layer":measure})); + assert_eq!(endpoint(&line, 0), json!([15.0,54.0])); + assert_eq!(endpoint(&line, 1), json!([43.0,54.0])); + assert_eq!(execute("type.info", json!({"layer":value}))["text"], "28 cm"); + assert_eq!(execute("type.info", json!({"layer":title}))["text"], "Product"); + assert_eq!(execute("shape.info", json!({"layer":bracket}))["bounds"], json!([title_right+2,7,1,5])); + if let Some(dir) = &demo { + export_fixture(&app, dir, "generic-after.png"); + } + } + #[test] fn published_underlay_and_annotation_path_roundtrip_as_editable_shapes() { let (mut w, mut app, _) = fixture(); 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 52b71d12..b075156a 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 @@ -96,6 +96,9 @@ pub fn screen_overlay_layers( let mut row = json!({"nativeLayerId":layer.id.0,"name":layer.name,"kind":kind, "mapped":is_text && copy_ids.contains(&layer.id.0), "bounds":[bounds.x0,bounds.y0,bounds.width(),bounds.height()],"overlapsSlots":overlaps}); + if let LayerContent::Shape(shape) = &layer.content { + row["knots"] = json!(shape.path.subpaths.iter().map(|subpath| subpath.knots.len()).sum::()); + } if path.len() > 1 && let Some(group) = native.layer_at(&path[..path.len() - 1]) { row["group"] = json!({"id":group.id.0,"name":group.name}); }