diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs index 7d277780..954b5b5f 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs @@ -1724,6 +1724,14 @@ impl Backend { self.last_saved.insert(doc.id.0, saved_identity.clone()); } } + if !metadata_only && canvas_problem.is_none() && (!dir.join("cover-v1.png").exists() || activate_view || self.last_saved.get(&doc.id.0) == Some(&saved_identity)) { + if !dir.join("cover-v1.png").exists() + || fs::symlink_metadata(dir.join("canvas.pcraft")).ok().zip(fs::symlink_metadata(dir.join("cover-v1.png")).ok()) + .is_some_and(|(draft, cache)| draft.modified().ok() > cache.modified().ok()) + { + projects::write_cover_cache(&dir, &doc); + } + } // UI snapshots may lag a completed sync or creation task. Preserve backend-owned // links/status and creation metadata; an old autosave must never erase them. let previous = if dir.join("context.json").exists() { read_json(&dir.join("context.json"))? } else { json!({}) }; 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 acd8e983..d72f7234 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -127,12 +127,12 @@ fn runnable_stages(state: &Value, mut remaining: Vec) -> Vec { remaining } -fn production_output_state(mut state: Value, output: &str, variant_id: &str) -> R { - if output == "detail" { +fn output_state_inner(mut state: Value, output: &str, variant_id: &str, enforce_color: bool) -> R { + if enforce_color && output == "detail" { creation::require_detail_barcode(&state["brief"])?; } variant(&state, variant_id)?; - if !output_uses_variant(&state["brief"], output, variant_id) { + if enforce_color && !output_uses_variant(&state["brief"], output, variant_id) { return Err("花色不属于所选成品".into()); } let pack = state["productTemplates"].get(output).filter(|pack| pack.is_object()) @@ -147,6 +147,10 @@ fn production_output_state(mut state: Value, output: &str, variant_id: &str) -> Ok(state) } +fn production_output_state(state: Value, output: &str, variant_id: &str) -> R { + output_state_inner(state, output, variant_id, true) +} + fn image_output_component<'a>(state: &'a Value, binding: &Value) -> Option<&'a str> { state["productTemplates"].as_object().into_iter().flat_map(|packs| packs.iter()) .find(|(component, pack)| pack["contentHash"] == binding["templateHash"] @@ -156,18 +160,61 @@ fn image_output_component<'a>(state: &'a Value, binding: &Value) -> Option<&'a s } fn image_output_state(state: Value, binding: &Value) -> R { - if state["template"]["contentHash"] == binding["templateHash"] && state["structureHash"] == binding["structureHash"] { + let batch = binding["detailBatch"] == true; + if state["template"]["contentHash"] == binding["templateHash"] + && state["structureHash"] == binding["structureHash"] + && (batch || binding["variantId"] == state["activeVariantId"]) + { return Ok(state); } let output = image_output_component(&state, binding).ok_or("原候选模板已变化")?.to_owned(); let variant_id = binding["variantId"].as_str().ok_or("原候选花色缺失")?; - let scoped = production_output_state(state, &output, variant_id)?; - if binding["structureHash"] != scoped["structureHash"] || !product_slot_binding(&scoped, binding) { + let scoped = output_state_inner(state, &output, variant_id, batch)?; + let slot_ok = if batch { + product_slot_binding(&scoped, binding) + } else { + binding["workspaceId"] == scoped["id"] + && binding["slotId"].as_str().is_some_and(|slot| definition(&scoped, slot, variant_id).is_ok()) + }; + if binding["structureHash"] != scoped["structureHash"] || !slot_ok { return Err("原候选模板或图位已变化".into()); } Ok(scoped) } +/// Resolve an in-memory project state scoped to the view output/variant the user is +/// currently inspecting without altering the active output stored on disk. +fn scope_state_for_view(state: Value, input: &Value) -> R<(Value, bool)> { + let Some(view_output) = input["viewOutputId"].as_str().filter(|output| !output.is_empty()) else { + return Ok((state, false)); + }; + if !state["productTemplates"][view_output].is_object() { + return Ok((state, false)); + } + let view_variant = input["viewVariantId"] + .as_str() + .filter(|value| !value.is_empty()) + .or_else(|| input["variantId"].as_str().filter(|value| !value.is_empty())) + .or_else(|| state["activeVariantId"].as_str().filter(|value| !value.is_empty())) + .ok_or("花色编号缺失")? + .to_owned(); + if state["activeOutput"] == view_output && state["activeVariantId"] == view_variant { + if let Some(expected_hash) = input["viewTemplateHash"].as_str().filter(|hash| !hash.is_empty()) + && state["template"]["contentHash"] != expected_hash + { + return Err("当前画布模板已变化,请重新切换页面".into()); + } + return Ok((state, false)); + } + let scoped = output_state_inner(state, view_output, &view_variant, false)?; + if let Some(expected_hash) = input["viewTemplateHash"].as_str().filter(|hash| !hash.is_empty()) + && scoped["template"]["contentHash"] != expected_hash + { + return Err("当前画布模板已变化,请重新切换页面".into()); + } + Ok((scoped, true)) +} + fn output_variant<'a>(state: &'a Value, component: &str, requested: Option<&'a str>) -> R<&'a str> { if let Some(id) = requested { variant(state, id)?; @@ -951,6 +998,7 @@ fn pending_production_images(dir: &Path, state: &Value) -> R { Ok(json!(pending)) } +#[cfg(test)] fn reserve(dir: &Path, state: Value, record: &Value) -> R<()> { reserve_candidate(dir, state, record, false) } @@ -1153,7 +1201,7 @@ fn product_reference_index(value: &Value) -> R { .ok_or_else(|| "所选商品原图编号无效".into()) } -fn import_local_candidate(dir: &Path, state: Value, output: &Value, field: &Value, slot: &str, variant: &str, input: &Value) -> R { +fn import_local_candidate(dir: &Path, state: Value, output: &Value, field: &Value, slot: &str, variant: &str, input: &Value, project_scoped: bool) -> R { use std::io::Read; const MAX_IMPORT: u64 = 64 * 1024 * 1024; let path = input["localPath"].as_str().map(Path::new).filter(|path| path.is_absolute() && path.is_file()) @@ -1171,7 +1219,7 @@ fn import_local_candidate(dir: &Path, state: Value, output: &Value, field: &Valu let id = Uuid::new_v4().to_string(); let mut binding = new_binding(&state, output, field, slot, variant, &id, "本机导入"); binding["origin"] = json!("human"); - stage_local_image(dir, state, binding, "local-import", json!([]), &png, false) + stage_local_image(dir, state, binding, "local-import", json!([]), &png, project_scoped) } fn stage_local_image(dir: &Path, state: Value, binding: Value, source: &str, references: Value, bytes: &[u8], project_scoped: bool) -> R { @@ -1634,6 +1682,10 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope: } fn reuse_archived_candidate(dir: &Path, state: Value, input: &Value, preflight: Option<&Backend>) -> R { + reuse_archived_candidate_scoped(dir, state, input, preflight, false) +} + +fn reuse_archived_candidate_scoped(dir: &Path, state: Value, input: &Value, preflight: Option<&Backend>, project_scoped: bool) -> R { let local = input["sourceProjectId"].is_null(); let project = if local { uuid(&json!(dir.file_name().and_then(|name| name.to_str())), "当前项目")? @@ -1746,7 +1798,7 @@ fn reuse_archived_candidate(dir: &Path, state: Value, input: &Value, preflight: "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)?; + reserve_candidate(dir, state, &record, project_scoped)?; Ok(record) } fn operation_receipt(mut canonical: Value, candidate: Option, error: Option) -> Value { @@ -4662,6 +4714,25 @@ impl Backend { json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":enrich_creation(dir,creation::load(dir)?)?,"pending":workflow["pending"],"canvasFirst":true}), ) } + fn canvas_workspace_result_for_snapshot(&self, doc: u64, dir: &Path, scoped: Value) -> R { + let workflow = snapshot_for_view(dir, Some(scoped), false)?; + Ok(json!({ + "doc": doc, + "accountId": self.auth["account"]["id"], + "origin": self.origin, + "workflow": workflow, + "creation": enrich_creation(dir, creation::load(dir)?)?, + "pending": workflow["pending"], + "canvasFirst": true, + })) + } + fn canvas_workspace_result_for_view(&self, doc: u64, dir: &Path, input: &Value, view_scoped: bool) -> R { + if !view_scoped { + return self.canvas_workspace_result(doc, dir); + } + let (scoped, _) = scope_state_for_view(load(dir)?, input)?; + self.canvas_workspace_result_for_snapshot(doc, dir, scoped) + } pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context, snapshot: Option<&photocraft_ui_egui::jiansun::PiCanvasSnapshot>) -> Result { let cancellation = snapshot.map(|snapshot| snapshot.cancellation.as_ref()); @@ -4888,7 +4959,14 @@ impl Backend { Some(lock_slot_dispatch(dir, slot)?.ok_or("本图位已有生图批次正在处理")?) } else { None }; let admitted = production.is_some() && slot["detailBatch"] == true; - let source = if admitted { image_output_state(state.clone(), slot)? } else { state.clone() }; + let view_scoped_image = !admitted + && state["productTemplates"].is_object() + && (state["template"]["contentHash"] != slot["templateHash"] + || state["structureHash"] != slot["structureHash"] + || (slot["detailBatch"] != true && state["activeVariantId"] != slot["variantId"])) + && image_output_component(&state, slot).is_some(); + let scoped_output = admitted || view_scoped_image; + let source = if scoped_output { image_output_state(state.clone(), slot)? } else { state.clone() }; if slot["detailBatch"] == true { let (_, max, generation_cap) = candidate_limits(dir, &source, task["outputScope"].as_str().ok_or("输出类型缺失")?)?; let (used, generations, pending) = { @@ -4912,9 +4990,14 @@ impl Backend { return Ok(candidate_receipt(&existing)); } } else { - reserve_candidate(dir, state, record, admitted)?; + reserve_candidate(dir, state, record, scoped_output)?; } - let mut snapshot = self.canvas_workspace_result(doc, dir)?; + let mut snapshot = if view_scoped_image { + let fresh = image_output_state(load(dir)?, slot)?; + self.canvas_workspace_result_for_snapshot(doc, dir, fresh)? + } else { + self.canvas_workspace_result(doc, dir)? + }; if let Some(operation) = record["workflowOperationId"].as_str() { snapshot["workflowGeneration"] = json!({"operationId":operation, "outputId":task["outputScope"],"candidate":candidate_receipt(record)}); @@ -5172,7 +5255,13 @@ impl Backend { persist(&dir, next, expected)?; } let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep" | "slot-transform-image"); - let mut state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? }; + let state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? }; + let browsing = method == "slot-product-view"; + let (mut state, view_scoped) = if !batch && !browsing && method != "slot-skeleton" { + scope_state_for_view(state, input)? + } else { + (state, false) + }; let project_scoped_image = batch && input["projectScopedImage"] == true; if project_scoped_image { state = production_image_target(state, &input["detailWorkspace"])?; @@ -5184,7 +5273,6 @@ impl Backend { } // Sibling candidates change the workspace revision, not this document or slot. // The mapped layer and candidate are checked again below before reading any pixels. - let browsing = method == "slot-product-view"; // Production handoff binds to the workspace and resolves the requested // output from its live configuration. Candidate receipts may advance it. let handoff = method == "slot-skeleton" && input["continueProduct"] == true @@ -5412,7 +5500,7 @@ impl Backend { events.send(Event::SlotCanvas(Box::new(native), result)).map_err(|_| "工作台已关闭,模板骨架记录保留")?; if let Some(receipt) = view_receipt { return Ok(receipt); } } else if method == "slot-transform-image" { - let record = jiansun_image_transform::stage_candidate(&dir, state, input, source)?; + let record = jiansun_image_transform::stage_candidate(&dir, state, input, source, project_scoped_image || view_scoped)?; if project_scoped_image { return Ok(candidate_receipt(&record)); } @@ -5421,7 +5509,7 @@ impl Backend { let _ = events.send(Event::Preview(reference, preview)); } let receipt = candidate_receipt(&record); - if let Ok(snapshot) = self.canvas_workspace_result(doc, &dir) { + if let Ok(snapshot) = self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped) { let _ = events.send(Event::Json("slot-append".into(), Ok(operation_receipt(snapshot, Some(receipt.clone()), None)))); } ctx.request_repaint(); @@ -5449,8 +5537,8 @@ impl Backend { let output = output.clone(); let preparing = method == "slot-prepare-image"; if import { - let record = import_local_candidate(&dir, state, &output, &field, &id, &variant_id, input)?; - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); + let record = import_local_candidate(&dir, state, &output, &field, &id, &variant_id, input, project_scoped_image || view_scoped)?; + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&record)), None)); } let instructions = input["instructions"].as_str().or_else(|| local.then_some("产品原图")) .filter(|value| !value.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))) @@ -5481,7 +5569,7 @@ impl Backend { if used >= max { let limit = candidate_limit_receipt(&slot, used, max); if project_scoped_image { return Ok(limit); } - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(limit), None)); + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(limit), None)); } Some(lock) } else { None }; @@ -5498,7 +5586,7 @@ impl Backend { binding["referenceCropMode"] = json!(mode); } } - let record = original_product_candidate(&dir, state, binding, &images, index, &field["frame"], project_scoped_image)?; + let record = original_product_candidate(&dir, state, binding, &images, index, &field["frame"], project_scoped_image || view_scoped)?; if project_scoped_image { return Ok(candidate_receipt(&record)); } @@ -5507,7 +5595,7 @@ impl Backend { let _ = events.send(Event::Preview(reference, preview)); ctx.request_repaint_of(egui::ViewportId::ROOT); } - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&record)), None)); } let attachment_refs = input.get("attachments").cloned().unwrap_or_else(|| json!([])); if !attachment_refs.as_array().is_none_or(Vec::is_empty) && input["projectId"].as_str() != self.locations.get(&doc).map(String::as_str) { @@ -5548,7 +5636,7 @@ impl Backend { }; if !preparing && candidate_path(&dir, &candidate)?.exists() { let original = read_candidate(&dir, &candidate)?; - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&original)), None)); + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&original)), None)); } let prefer_2k = input["prefer2k"] == true; let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, instructions); @@ -5589,22 +5677,22 @@ impl Backend { if receipt["status"] == "failed" { operation_error = receipt["message"].as_str().map(str::to_owned); } candidate_result = Some(receipt); } else if method == "slot-reuse" { - let record = reuse_archived_candidate(&dir, state, input, None)?; + let record = reuse_archived_candidate_scoped(&dir, state, input, None, view_scoped)?; if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) { reference["purpose"] = json!("template-candidate"); let _ = events.send(Event::Preview(reference, preview)); ctx.request_repaint_of(egui::ViewportId::ROOT); } - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&record)), None)); } else if method == "slot-recover" { let candidate = uuid(input.get("candidateId").filter(|value| !value.is_null()).unwrap_or(&input["taskId"]), "原候选")?; let record = read_candidate(&dir, &candidate)?; checked_binding(&dir, &record["binding"], true)?; if matches!(record["sourceType"].as_str(), Some("product-reference" | "local-import")) || record["canvasTransform"].is_object() { - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&record)), None)); } let Some(_dispatch) = lock_candidate_dispatch(&dir, &candidate)? else { - return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, + return Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(candidate_receipt(&pending_candidate(&record))), None)); }; // This enters the existing immutable protocol/key-scoped GET-only recovery path. @@ -5703,7 +5791,7 @@ impl Backend { } else { return Err("原生画布操作未开放".into()); } - Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, candidate_result, operation_error)) + Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, candidate_result, operation_error)) } } @@ -9292,6 +9380,121 @@ mod tests { assert!(unfinished.join("detail.jpg").is_file()); assert!(!unfinished.join("manifest.json").exists()); } + + #[test] + fn product_view_action_adopts_and_preps_edit_on_viewed_output_without_mutating_active_output() { + let fixture = fixture(); + let mut backend = Backend::new(fixture.dir.join("profile")).unwrap(); + let doc = 1; + backend.bind_new(doc); + let dir = backend.project_dir(doc).unwrap(); + write_json(&dir.join("context.json"), &json!({"doc":doc,"revision":1})).unwrap(); + let mut creation = creation::load(&dir).unwrap(); + let mut state = load(&fixture.dir).unwrap(); + let variant_id = state["activeVariantId"].as_str().unwrap().to_owned(); + creation["brief"]["outputVariantIds"] = json!({"sku_images": [variant_id.clone()], "main_images": [variant_id.clone()]}); + write_json(&dir.join("creation.json"), &creation).unwrap(); + + let mut sku = pack(); + sku["outputs"][0]["id"] = json!("K01"); + sku["outputs"][0]["component"] = json!("sku_images"); + sku["outputs"][0]["slots"][0]["fieldId"] = json!("K01-I01"); + sku["contentHash"] = json!(template_slots::pack_hash(&sku).unwrap()); + + let mut main = pack(); + main["outputs"][0]["id"] = json!("M01"); + main["outputs"][0]["component"] = json!("main_images"); + main["outputs"][0]["slots"][0]["fieldId"] = json!("M01-I01"); + main["contentHash"] = json!(template_slots::pack_hash(&main).unwrap()); + + state["activeOutput"] = json!("sku_images"); + state["activeMapping"] = json!(mapping_key(&variant_id, "sku_images", None)); + state["template"] = sku.clone(); + state["structureHash"] = json!(hash(&json!([sku["contentHash"], state["width"]]).to_string())); + state["productTemplates"] = json!({"sku_images": sku.clone(), "main_images": main.clone()}); + state["brief"] = creation["brief"].clone(); + + let main_slot = slot_id(&main["contentHash"], &variant_id, "M01-I01"); + let main_key = mapping_key(&variant_id, "main_images", None); + let sku_key = mapping_key(&variant_id, "sku_images", None); + state["mappings"] = json!({ + sku_key: {"version": 1, "variantId": variant_id, "component": "sku_images", "outputs": []}, + main_key: { + "version": 1, + "variantId": variant_id, + "component": "main_images", + "templateHash": main["contentHash"], + "outputs": [{ + "mapping": { + "fields": [{ + "fieldId": "M01-I01", + "slotId": main_slot, + "kind": "image", + "nativeLayerId": 42, + "frame": {"x": 0, "y": 0, "width": 1440, "height": 1440} + }] + } + }] + } + }); + let saved = persist(&dir, state, 0).unwrap(); + + let (events, receiver) = mpsc::channel(); + let ctx = egui::Context::default(); + let view_receipt = backend.canvas_workspace_action("slot-product-view", &json!({ + "doc": doc, "baseRevision": 1, "workspaceId": saved["id"], + "outputId": "main_images", "variantId": variant_id, "productViewId": 1, + }), &events, &ctx).unwrap(); + assert_eq!(view_receipt["outputId"], "main_images"); + assert_eq!(load(&dir).unwrap()["activeOutput"], "sku_images"); + + // Import a real 4x4 PNG candidate into the viewed output (main_images) while disk activeOutput remains sku_images. + let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgba, vec![210; 64]).unwrap(); + let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let local_file = dir.join("sample-import.png"); + fs::write(&local_file, &png).unwrap(); + let import_receipt = backend.canvas_workspace_action("slot-import-local", &json!({ + "doc": doc, "baseRevision": 1, "slotRevision": saved["revision"], + "slotId": main_slot, "variantId": variant_id, "localPath": local_file, + "viewOutputId": "main_images", "viewVariantId": variant_id, "viewTemplateHash": main["contentHash"], + }), &events, &ctx).unwrap(); + assert_eq!(import_receipt["workflow"]["outputId"], "main_images"); + let candidate_id = import_receipt["candidateResult"]["id"].as_str().unwrap().to_owned(); + let post_import = load(&dir).unwrap(); + assert_eq!(post_import["activeOutput"], "sku_images", "viewed-output import must not rewrite disk activeOutput"); + + // Trigger slot-adopt-prep and slot-edit-prep from the viewed main_images canvas. + let prep_receipt = backend.canvas_workspace_action("slot-adopt-prep", &json!({ + "doc": doc, "baseRevision": 1, "slotRevision": post_import["revision"], + "slotId": main_slot, "candidateId": candidate_id, "variantId": variant_id, "nativeLayerId": 42, + "viewOutputId": "main_images", "viewVariantId": variant_id, "viewTemplateHash": main["contentHash"], + }), &events, &ctx).unwrap(); + assert_eq!(prep_receipt["workflow"]["outputId"], "main_images"); + let adopt_meta = receiver.try_iter().filter_map(|event| match event { + Event::SlotAdopt { meta, .. } => Some(meta), + _ => None, + }).last().unwrap(); + assert_eq!(adopt_meta["templateHash"], main["contentHash"]); + assert_eq!(adopt_meta["outputId"], "main_images"); + + let mut ack = adopt_meta.clone(); + ack["beforeRevision"] = json!(1); + ack["afterRevision"] = json!(2); + ack["slotRevision"] = post_import["revision"].clone(); + ack["viewOutputId"] = json!("main_images"); + ack["viewVariantId"] = json!(variant_id.clone()); + ack["viewTemplateHash"] = main["contentHash"].clone(); + let adopted_receipt = backend.canvas_workspace_action("slot-adopted", &ack, &events, &ctx).unwrap(); + assert_eq!(adopted_receipt["workflow"]["outputId"], "main_images"); + + let edit_receipt = backend.canvas_workspace_action("slot-edit-prep", &json!({ + "doc": doc, "baseRevision": 1, "slotRevision": post_import["revision"], + "slotId": main_slot, "candidateId": candidate_id, "variantId": variant_id, "nativeLayerId": 42, + "viewOutputId": "main_images", "viewVariantId": variant_id, "viewTemplateHash": main["contentHash"], + }), &events, &ctx).unwrap(); + assert_eq!(edit_receipt["workflow"]["outputId"], "main_images"); + assert_eq!(load(&dir).unwrap()["activeOutput"], "sku_images"); + } } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs index 9d6abf98..7ea2e9c1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs @@ -195,7 +195,7 @@ pub(super) fn adopted_source(dir: &Path, state: &Value, input: &Value, variant: Err(format!("来源图位「{source}」{reason}。匹配图位的已完成候选:{}。{hint}", json!(sources())).into()) } -pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value, source: Option) -> R { +pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value, source: Option, project_scoped: bool) -> R { let slot = input["slotId"].as_str().ok_or("缺少目标图位")?; let variant = uuid(&input["variantId"], "花色")?; let (output, field) = definition(&state, slot, &variant)?; @@ -307,7 +307,7 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value, source: O "references":references,"requestId":null,"artifact":artifact,"createdAt":now(), "parentCandidateId":edit["sourceCandidateId"],"canvasTransform":edit, "materialTaskId":original_task,"sourceRequestId":original_request,"reusedFrom":ancestry}); - reserve_candidate(dir, state, &record, input["projectScopedImage"] == true)?; + reserve_candidate(dir, state, &record, project_scoped || input["projectScopedImage"] == true)?; Ok(record) } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs index 79431f12..6b435080 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -842,4 +842,67 @@ mod tests { assert!(fs::read(outputs.join("当前画布.psd")).unwrap().starts_with(b"8BPS")); assert!(fs::read(outputs.join("当前画布.jpg")).unwrap().starts_with(&[0xff,0xd8])); } + + #[test] + fn bound_rebase_preserves_legacy_enterprise_hashes_for_all_product_templates() { + let test = tempfile::tempdir().unwrap(); + let old = test.path().join("old-root"); + let new = test.path().join("new-root"); + let make_pack = |component: &str| -> Value { + let mapping = old.join("projects/p1/agent/acct/p1/files").join(component).join("字段映射.json"); + let inventory = old.join("projects/p1/agent/acct/p1/files").join(component).join("完整图层清单.json"); + let mut pack = json!({ + "schemaVersion": 1, + "id": "SFY-CHAIR-001", + "version": "2026-11-30.1", + "name": "测试", + "brandId": "brand", + "categoryId": "cat", + "outputs": [{ + "id": component, + "component": component, + "name": component, + "width": 1440, + "height": 1440, + "slots": [] + }], + "enterprise": { + "sourceKind": "xiaoyi-release", + "snapshotVersion": "2026-11-30.1", + "manifestRevision": "a".repeat(64), + "originalSha256": "b".repeat(64), + "mappingPath": mapping, + "inventoryPath": inventory + } + }); + let without_hash = { + let mut clone = pack.clone(); + clone.as_object_mut().unwrap().remove("contentHash"); + clone + }; + pack["contentHash"] = json!(super::super::hash(&without_hash.to_string())); + pack + }; + let detail = make_pack("detail"); + let main = make_pack("main_images"); + let sku = make_pack("sku_images"); + let mut workspace = json!({ + "template": sku.clone(), + "productTemplates": { + "detail": detail, + "main_images": main, + "sku_images": sku, + } + }); + rebase_project_json(&mut workspace, &old, &new, true); + super::super::template_slots::validate_pack(&workspace["template"]).unwrap(); + assert!(workspace["template"]["enterprise"]["mappingPath"].as_str().unwrap().starts_with(&new.to_string_lossy().into_owned())); + assert!(workspace["template"][super::super::template_slots::LEGACY_ENTERPRISE_PATHS].is_object()); + for component in ["detail", "main_images", "sku_images"] { + let migrated = &workspace["productTemplates"][component]; + super::super::template_slots::validate_pack(migrated).unwrap(); + assert!(migrated["enterprise"]["mappingPath"].as_str().unwrap().starts_with(&new.to_string_lossy().into_owned())); + assert!(migrated[super::super::template_slots::LEGACY_ENTERPRISE_PATHS].is_object()); + } + } } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs index f3a9ab81..68ae6dc0 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_projects.rs @@ -4,6 +4,8 @@ use super::{json, Value, R, Uuid, Path, PathBuf, fs, read_json, sync, Document, use photocraft_doc::LayerContent; use photocraft_geom::Rect; +const COVER_CACHE: &str = "cover-v1.png"; + fn project_id(input: &Value) -> R<&str> { input["id"].as_str().filter(|s| Uuid::parse_str(s).is_ok() || s.parse::().is_ok()).ok_or("项目编号无效".into()) } @@ -229,6 +231,66 @@ fn first_screen(doc: &Document) -> R { Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels)) } +fn write_cover_image(dir: &Path, image: &egui::ColorImage) { + let Ok(width) = u32::try_from(image.width()) else { return }; + let Ok(height) = u32::try_from(image.height()) else { return }; + let mut raw = Vec::with_capacity(image.pixels.len().saturating_mul(4)); + for pixel in &image.pixels { + raw.extend_from_slice(&pixel.to_array()); + } + let Ok(encoded_input) = photocraft_codecs::Image::from_raw( + width, + height, + photocraft_codecs::ChannelLayout::Rgba, + photocraft_codecs::SampleType::U8, + raw, + ) else { + return; + }; + let Ok(png) = photocraft_codecs::encode(&encoded_input, photocraft_codecs::Format::Png, &Default::default()) else { + return; + }; + let _ = photocraft_format::atomic_write(&dir.join(COVER_CACHE), &png); +} + +pub(super) fn write_cover_cache(dir: &Path, doc: &Document) { + if let Ok(image) = first_screen(doc) { + write_cover_image(dir, &image); + } +} + +fn read_cover_cache(dir: &Path) -> Option { + let cache = dir.join(COVER_CACHE); + let cache_meta = fs::symlink_metadata(&cache).ok()?; + if !cache_meta.file_type().is_file() || cache_meta.file_type().is_symlink() { + return None; + } + let draft = dir.join("canvas.pcraft"); + if let Ok(draft_meta) = fs::symlink_metadata(&draft) { + let cache_mtime = cache_meta.modified().ok()?; + let draft_mtime = draft_meta.modified().ok()?; + if cache_mtime < draft_mtime { + return None; + } + } + let bytes = fs::read(&cache).ok()?; + let image = photocraft_codecs::decode_with( + &bytes, + &photocraft_codecs::DecodeOptions { + limits: photocraft_codecs::Limits { + max_width: 1024, + max_height: 1024, + max_pixels: 1_048_576, + max_alloc: 8 * 1024 * 1024, + }, + ..Default::default() + }, + ) + .ok()? + .convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); + Some(egui::ColorImage::from_rgba_unmultiplied([image.width() as usize, image.height() as usize], image.data())) +} + /// Only references on the first screen are downloaded. Facts-only projects have no cover. fn screen_sources(screen: &Value, web: bool) -> Vec { let mut sources = Vec::new(); @@ -311,13 +373,18 @@ impl Backend { let id = project_id(input)?; if input["source"] == "native" { let dir = local_path(&self.dir().join("projects"), id)?; + if let Some(cached) = read_cover_cache(&dir) { + return Ok(cached); + } let file = dir.join("canvas.pcraft"); if !photocraft_format::draft_fits(&file, &super::draft_objects(&dir), 256 * 1024 * 1024) .map_err(|_| "本机项目无法读取")? { return Err("项目较大,请打开后查看".into()); } let doc = super::load_draft(&dir, &file).map_err(|_| "本机封面读取失败,项目文件已保留")?; - return first_screen(&doc); + let cover = first_screen(&doc)?; + write_cover_image(&dir, &cover); + return Ok(cover); } self.validate()?; let source = input["source"].as_str().filter(|s| ["web", "desktop"].contains(s)).ok_or("项目来源无效")?; @@ -794,4 +861,37 @@ mod tests { assert!(b.delete_project(&json!({"source":"web","id":id,"revision":7})).unwrap_err().contains("新版本")); server.join().unwrap(); } + #[test] + fn native_cover_cache_serves_large_projects_and_invalidates_after_newer_draft() { + let mut b = fixture(); + let (doc, item) = create(&mut b); + let dir = b.project_dir(doc.id.0).unwrap(); + // Write non-draft bytes first, then newer cover-v1.png: valid cache must bypass draft_fits/load_draft. + fs::write(dir.join("canvas.pcraft"), b"oversized-or-unopened-draft").unwrap(); + std::thread::sleep(Duration::from_millis(40)); + let red = crate::jiansun_document::import( + &json!({"name":"封面","screens":[{"width":120,"height":180,"background":"#cc2222","layers":[]}]}), + &HashMap::new(), + ) + .unwrap(); + write_cover_cache(&dir, &red); + assert!(dir.join(COVER_CACHE).is_file()); + let cover = b.project_cover(&item).unwrap(); + assert_eq!(cover.size, [120, 180]); + assert!(cover.pixels[0].r() > 180); + + // Overwrite canvas.pcraft later so its mtime exceeds cover-v1.png; invalid cache falls back to live draft. + std::thread::sleep(Duration::from_millis(40)); + let blue = crate::jiansun_document::import( + &json!({"name":"更新后","screens":[{"width":100,"height":100,"background":"#2244cc","layers":[]}]}), + &HashMap::new(), + ) + .unwrap(); + let bytes = b.serialize_draft(&dir, &blue).unwrap(); + photocraft_format::atomic_write(&dir.join("canvas.pcraft"), &bytes).unwrap(); + let updated = b.project_cover(&item).unwrap(); + assert_eq!(updated.size, [100, 100]); + assert!(updated.pixels[0].b() > 180); + fs::remove_dir_all(&b.root).unwrap(); + } } diff --git a/apps/detail-photocraft/client-version.txt b/apps/detail-photocraft/client-version.txt index aa390d14..343536e0 100644 --- a/apps/detail-photocraft/client-version.txt +++ b/apps/detail-photocraft/client-version.txt @@ -1 +1 @@ -1.2612.109 +1.2612.110 diff --git a/apps/detail-photocraft/crates/ui-egui/src/canvas/background_redraw/tests.rs b/apps/detail-photocraft/crates/ui-egui/src/canvas/background_redraw/tests.rs index d126810a..54a41316 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/canvas/background_redraw/tests.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/canvas/background_redraw/tests.rs @@ -732,3 +732,28 @@ fn a_flipped_view_records_why_it_draws_on_the_cpu() { g.harness.run_steps(3); assert!(on_gpu_canvas(&g), "back on the GPU"); } + +#[test] +fn product_view_redraw_uses_progressive_gpu_blocks_before_cpu_fallback() { + let _guard = photocraft_testkit::gpu_lock(); + let Some(mut g) = gpu_app() else { return }; + { + let app = g.harness.state_mut(); + app.run("file.new", json!({"width": 1600, "height": 2800, "background": "#336699"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#cc8844"})).unwrap(); + app.run("layer.layerStyle.blendingOptions", json!({"opacity": 60, "blend": "multiply"})).unwrap(); + let id = app.session.active().unwrap().doc.id; + app.canvases.retain(|(doc_id, _), _| *doc_id != id); + app.product_view_redraw = Some(id); + } + let id = g.harness.state().session.active().unwrap().doc.id; + g.harness.step(); + assert!(g.harness.state().product_view_redraw.is_none()); + assert!(g.harness.state().gpu_redraws.contains_key(&id), "large switched product views should render progressively on the GPU"); + assert!(!g.harness.state().redraws.contains_key(&id), "compatible product views must not jump straight to background CPU redraw"); + settle(&mut g); + assert!(on_gpu_canvas(&g)); + assert!(g.harness.state().ui.notices.is_empty(), "GPU-capable switch must not post slow CPU refresh notices"); + assert_matches_synchronous(&mut g, id); +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs index 0046bdc3..198088b5 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -962,6 +962,10 @@ impl GpuCanvas { if u64::from(doc.size.width) * u64::from(doc.size.height) < DEFER_PX { return false; } if let Some(resources) = self.rs.renderer.write().callback_resources.get_mut::() { resources.docs.remove(&doc.id.0); + if let Some(compositor) = resources.compositor.as_mut() { + // Switched product outputs share the active DocId; drop stale layer caches before progressive GPU blocks run. + compositor.retain_docs(|id| id.0 != doc.id.0); + } } self.prepare_texture(doc.id.0, doc).is_some() } diff --git a/apps/detail-photocraft/crates/ui-egui/src/canvas/textures.rs b/apps/detail-photocraft/crates/ui-egui/src/canvas/textures.rs index ce6c6028..30bcffbc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/canvas/textures.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/canvas/textures.rs @@ -621,10 +621,14 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz let region = if partial { damage } else { None }; let refresh_bounds = region.unwrap_or(doc.bounds()).intersect(&doc.bounds()); let refresh_pixels = u64::from(refresh_bounds.width()) * u64::from(refresh_bounds.height()); - if defer && !product_view && (!partial || !app.redraws.contains_key(&id)) + if defer && (!partial || !app.redraws.contains_key(&id)) && refresh_pixels >= crate::gpu_canvas::DEFER_PX - && gpu.prepare_texture(id.0, &doc).is_some() + && if product_view { gpu.prepare_product_view(&doc) } else { gpu.prepare_texture(id.0, &doc).is_some() } { + if product_view { + app.product_view_redraw = None; + app.product_cpu_texture = None; + } // A new full refresh supersedes pending pixels. A second large edit can overlap prior // work, so redraw the combined region against the latest document. let region = if let (Some(region), Some(previous)) = (region, app.gpu_redraws.get(&id)) { @@ -640,11 +644,7 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz return crate::background_redraw::poll_gpu(app, ctx, &gpu, doc, display, visible); } let _timing = crate::operation_timer::OperationTimer::new("canvas.gpu_refresh", Some(&doc), true); - let r = if product_view && !present && defer && gpu.prepare_product_view(&doc) { - crate::gpu_canvas::Refresh { kind: crate::gpu_canvas::REFRESH_DEFERRED, ..Default::default() } - } else { - gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer) - }; + let r = gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer); app.perf.gpu_layer_fit = gpu.layer_fit(); if r.kind == "lost" || r.kind == crate::gpu_canvas::REFRESH_OVER_BUDGET { // The device is gone (`gpu_status` then drops the GPU canvas) or the canvas is over the diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index a0361565..837c0a1a 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -187,6 +187,27 @@ fn slot_action_allowed(workflow: &Value, unknown: bool, method: &str) -> bool { } } +pub(super) fn attach_view_scope(workflow: &Value, input: &mut Value) { + if input["detailBatch"] == true { + return; + } + if input.get("viewOutputId").is_none() + && let Some(output) = workflow["outputId"].as_str().filter(|output| !output.is_empty()) + { + input["viewOutputId"] = json!(output); + } + if input.get("viewVariantId").is_none() + && let Some(variant) = workflow["variantId"].as_str().filter(|variant| !variant.is_empty()) + { + input["viewVariantId"] = json!(variant); + } + if input.get("viewTemplateHash").is_none() + && let Some(hash) = workflow["templateHash"].as_str().filter(|hash| !hash.is_empty()) + { + input["viewTemplateHash"] = json!(hash); + } +} + /// Startup may resume only an account-owned local row; it must never navigate for an /// already active editor or a person who has started another task. fn resume_candidate(value: &Value, account: &Value, origin: &str, projects: &[Value], quiet: bool) -> Option { @@ -1325,6 +1346,9 @@ impl Workspace { input["baseRevision"] = json!(st.revision); input["slotRevision"] = self.template_workflow["revision"].as_u64().map(Value::from).unwrap_or(json!(0)); input["imageModel"] = json!(self.image_model); + if !matches!(method, "slot-skeleton" | "slot-templates" | "slot-product-export") { + attach_view_scope(&self.template_workflow, &mut input); + } if input["continueProduct"] == true && self.pi_request_scope["writeEpoch"].is_u64() { input["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone(); } @@ -6528,6 +6552,26 @@ mod tests { } } + #[test] + fn slot_action_attaches_active_view_scope_except_for_detail_batch() { + let (mut w, app, requests, _) = slot_workspace(); + w.template_workflow["outputId"] = json!("main_images"); + w.template_workflow["variantId"] = json!("variant-a"); + w.template_workflow["templateHash"] = json!("hash-main"); + w.template_workflow["capabilities"] = json!({"localApplyAllowed": true}); + w.busy = None; + w.slot_action(&app, "slot-adopt-prep", json!({"slotId": "s1", "candidateId": "c1", "variantId": "variant-a", "nativeLayerId": 7})).unwrap(); + let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("action required") }; + assert_eq!(method, "slot-adopt-prep"); + assert_eq!(input["viewOutputId"], "main_images"); + assert_eq!(input["viewVariantId"], "variant-a"); + assert_eq!(input["viewTemplateHash"], "hash-main"); + + let mut batch_input = json!({"detailBatch": true}); + attach_view_scope(&w.template_workflow, &mut batch_input); + assert!(batch_input.get("viewOutputId").is_none()); + } + #[test] fn late_image_receipt_cannot_accept_a_second_turn_before_the_original_pi_end() { let (mut w,mut app,requests,events) = slot_workspace(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index 96ba369c..af021849 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -1952,6 +1952,9 @@ impl Workspace { ack["beforeRevision"] = json!(before_revision); ack["afterRevision"] = json!(app.session.active().map(|s| s.revision)); ack["slotRevision"] = self.template_workflow["revision"].clone(); + if !batch { + super::attach_view_scope(&self.template_workflow, &mut ack); + } if self.tx.send(Request::Action("slot-adopted".into(), ack)).is_err() { self.error = "图片已在本机采纳;记录尚未保存,请保留工程".into(); } else { self.note("已采纳图片,可撤销"); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/professional_mode.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/professional_mode.rs index 3fb2c87d..7fe3d29f 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/professional_mode.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/professional_mode.rs @@ -136,8 +136,9 @@ impl Workspace { let edit = ImageEdit { parent:current.doc.id.0, child:None, revision:current.revision, layer:original, account:self.account["id"].clone(), origin:self.origin.clone(), template:template_scope(&self.template_workflow), target:target.clone() }; if target["kind"] == "candidate" { - let input = json!({"doc":edit.parent,"baseRevision":edit.revision,"slotRevision":self.template_workflow["revision"], + let mut input = json!({"doc":edit.parent,"baseRevision":edit.revision,"slotRevision":self.template_workflow["revision"], "slotId":target["slotId"],"candidateId":target["candidateId"],"variantId":self.canvas_workspace.variant,"nativeLayerId":layer}); + super::attach_view_scope(&self.template_workflow, &mut input); self.tx.send(Request::Action("slot-edit-prep".into(), input)).map_err(|_| "本地图片读取连接已关闭")?; self.professional_edit = Some(edit); self.busy = Some("slot-edit-prep".into()); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs index 2ff86b08..f7ad546b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_browser.rs @@ -4,10 +4,43 @@ use super::{json, Value, Tokens, Workspace, PhotocraftApp, Ui, stitch_ui, agent_ use crate::{icons, theme::agent_scale::Type, widgets}; use egui::{Align, Frame, Layout, Sense, Stroke, pos2, vec2}; +const CARD_COVER_ASPECT: f32 = 1.0; +const CARD_FOOTER_HEIGHT: f32 = 82.0; +const CARD_ROW_GAP: f32 = 16.0; + fn key(item: &Value) -> String { format!("{}|{}|{}|{}", item["source"].as_str().unwrap_or(""), item["id"].as_str().unwrap_or(""), item["revision"], item["updatedAt"]) } +/// Cover-fit UV coordinates that keep horizontal centering while pinning tall portrait +/// covers to the top edge so headers and hero subjects are never cropped away. +fn cover_uv(rect_size: egui::Vec2, image_size: egui::Vec2) -> egui::Rect { + if rect_size.x <= 0.0 || rect_size.y <= 0.0 || image_size.x <= 0.0 || image_size.y <= 0.0 { + return egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + } + let factor = (rect_size.x / image_size.x).max(rect_size.y / image_size.y); + let uv_size = rect_size / (image_size * factor); + let uv_min = pos2( + ((1.0 - uv_size.x) * 0.5).clamp(0.0, 1.0), + if uv_size.y < 1.0 { 0.0 } else { ((1.0 - uv_size.y) * 0.5).clamp(0.0, 1.0) }, + ); + egui::Rect::from_min_size(uv_min, uv_size) +} + +fn cover_placeholder_text(loading: bool, has_screen: bool, error: Option<&str>) -> &'static str { + if loading { + "加载封面…" + } else if error.is_some_and(|s| s == "尚无画布内容" || s == "尚未生成页面") { + "待生成" + } else if let Some(message) = error { + if message == "项目较大,请打开后查看" { "打开后生成封面" } else { "封面暂不可用" } + } else if has_screen { + "首屏预览" + } else { + "待生成" + } +} + fn same(a: &Value, b: &Value) -> bool { a["id"] == b["id"] && a["source"] == b["source"] } @@ -425,14 +458,15 @@ impl Workspace { } }); } - // Reserve the scrollbar before sizing a portrait grid so the - // last preview never extends underneath the native sidebar. + // Reserve the scrollbar before sizing the grid so card edges and rows + // align uniformly without extending underneath the native sidebar. let grid_width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(1.0); - let cols = ((grid_width + 16.0) / 218.0).floor().max(1.0) as usize; - let tile_width = ((grid_width - (cols.saturating_sub(1)) as f32 * 16.0) / cols as f32).clamp(1.0, 280.0); - let row_height = tile_width * 1.6 + 74.0; + let cols = ((grid_width + CARD_ROW_GAP) / 218.0).floor().max(1.0) as usize; + let tile_width = ((grid_width - (cols.saturating_sub(1)) as f32 * CARD_ROW_GAP) / cols as f32).clamp(1.0, 280.0); + let row_height = tile_width * CARD_COVER_ASPECT + CARD_FOOTER_HEIGHT; let rows = items.len().div_ceil(cols); egui::ScrollArea::vertical().id_salt("jiansun-project-grid").auto_shrink([false, false]).show_rows(ui, row_height, rows, |ui, range| { + ui.spacing_mut().item_spacing.y = CARD_ROW_GAP; // Reserve visible preview surfaces behind their real media // and widgets. Each surface keeps its own hover phase. let first = range.start * cols; @@ -440,7 +474,7 @@ impl Workspace { let backgrounds: Vec<_> = (first..end).map(|_| agent_motion::reserve_background(ui)).collect(); for row in range { ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = 16.0; + ui.spacing_mut().item_spacing.x = CARD_ROW_GAP; for (column, item) in items.iter().skip(row * cols).take(cols).enumerate() { let background = backgrounds[row * cols + column - first]; ui.push_id((item["source"].as_str(), item["id"].as_str()), |ui| self.project_tile(app, ui, item, tile_width, background, &multi_vm)); @@ -463,9 +497,8 @@ impl Workspace { let native = item["source"] == "native"; let cloud = cloud_present(item); let has_screen = native || item["screenCount"].as_u64().unwrap_or(0) > 0; - let unavailable = !self.project_covers.contains_key(&k) && (!has_screen || self.cover_errors.contains_key(&k)); - let preview_height = width * if unavailable { 0.85 } else { 1.6 }; - let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 82.0), Sense::hover()); + let preview_height = width * CARD_COVER_ASPECT; + let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + CARD_FOOTER_HEIGHT), Sense::hover()); let rect = egui::Rect::from_min_size(shell.min, vec2(width, preview_height)); let response = ui.interact(shell, ui.scope_id().with("project-open"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); let enabled = self.busy.is_none() || self.product_production.is_some(); @@ -474,16 +507,15 @@ impl Workspace { let stroke_width = if cloud { 2.0 / ui.ctx().pixels_per_point() } else { 1.0 / ui.ctx().pixels_per_point() }; stitch_ui::material_over(ui, ui.scope_id().with("project-material"), shell, 16.0, hover * 0.35, background, t.card, t.card_border); if let Some(texture) = self.project_covers.get(&k) { - let size = texture.size_vec2(); - let factor = (rect.width()/size.x).max(rect.height()/size.y); - let uv = egui::Rect::from_center_size(pos2(0.5,0.5),rect.size()/(size*factor)); + let uv = cover_uv(rect.size(), texture.size_vec2()); egui::Image::new(texture).uv(uv).corner_radius(egui::CornerRadius {nw:16,ne:16,sw:0,se:0}).paint_at(ui,rect); } else { ui.painter().rect_filled(rect, egui::CornerRadius { nw: 16, ne: 16, sw: 0, se: 0 }, t.field); - let error = self.cover_errors.get(&k); - let empty = error.is_some_and(|s|s=="尚无画布内容" || s=="尚未生成页面"); - let text = if self.cover_loading.contains(&k) {"加载封面…"} else if empty {"待生成"} else if error.is_some() {"封面暂不可用"} else if has_screen {"首屏预览"} else {"待生成"}; - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, text, Type::Meta.font_id(), t.text_dim); + let error = self.cover_errors.get(&k).map(String::as_str); + let text = cover_placeholder_text(self.cover_loading.contains(&k), has_screen, error); + let icon_box = egui::Rect::from_center_size(rect.center() - vec2(0.0, 12.0), vec2(20.0, 20.0)); + icons::paint(ui, icon_box, "image", 20.0, t.text_dim.gamma_multiply(0.55)); + ui.painter().text(rect.center() + vec2(0.0, 10.0), egui::Align2::CENTER_CENTER, text, Type::Meta.font_id(), t.text_dim); if let Some(error) = error { response.clone().on_hover_text(error); } if has_screen && error.is_none() && !self.cover_loading.contains(&k) && self.cover_loading.len() < 2 && ui.is_rect_visible(rect) { self.cover_loading.insert(k); @@ -1149,14 +1181,15 @@ mod tests { assert!(r[0].as_f64().unwrap() + r[2].as_f64().unwrap() <= width as f64); assert!(r[3].as_f64().unwrap() <= 36.0, "filter labels must not stack vertically"); } - for tile in w.project_geometry["tiles"].as_array().unwrap() { + let tiles = w.project_geometry["tiles"].as_array().unwrap(); + let first_card = tiles[0]["card"].as_array().unwrap(); + for tile in tiles { let preview = tile["open"].as_array().unwrap(); let aspect = preview[3].as_f64().unwrap() / preview[2].as_f64().unwrap(); - if tile["id"] == "one" { - assert!(aspect > 1.5, "leave room for the portrait cover"); - } else { - assert!(aspect < 1.0, "keep coverless project details near the top"); - } + assert!((aspect - f64::from(CARD_COVER_ASPECT)).abs() < 0.01, "all cards share uniform square preview aspect: {aspect}"); + let card = tile["card"].as_array().unwrap(); + assert!((card[2].as_f64().unwrap() - first_card[2].as_f64().unwrap()).abs() < 0.5); + assert!((card[3].as_f64().unwrap() - first_card[3].as_f64().unwrap()).abs() < 0.5, "cards with and without covers must stay equal height"); for action in ["open", "menu"] { let r = tile[action].as_array().unwrap(); let x = r[0].as_f64().unwrap(); @@ -1168,7 +1201,6 @@ mod tests { assert!(y >= 0.0, "tall previews may extend below the scrolling viewport"); } } - let tiles = w.project_geometry["tiles"].as_array().unwrap(); for pair in tiles.windows(2) { let a = pair[0]["card"].as_array().unwrap(); let b = pair[1]["card"].as_array().unwrap(); @@ -1289,4 +1321,23 @@ mod tests { assert!(app.session.documents().is_empty(), "clicking new project must not spawn an empty 1440x1800 canvas tab"); assert_eq!(workspace.agent_page(&app), "brief"); } + + #[test] + fn portrait_covers_crop_from_top_and_large_project_errors_prompt_to_open() { + let portrait = cover_uv(vec2(200.0, 200.0), vec2(288.0, 360.0)); + assert_eq!(portrait.min.y, 0.0); + assert!((portrait.max.y - 0.8).abs() < 0.001); + assert_eq!(portrait.min.x, 0.0); + assert!((portrait.max.x - 1.0).abs() < 0.001); + + let landscape = cover_uv(vec2(200.0, 200.0), vec2(400.0, 200.0)); + assert_eq!(landscape.min.y, 0.0); + assert!((landscape.min.x - 0.25).abs() < 0.001); + assert!((landscape.max.x - 0.75).abs() < 0.001); + + assert_eq!(cover_placeholder_text(false, true, Some("项目较大,请打开后查看")), "打开后生成封面"); + assert_eq!(cover_placeholder_text(false, true, Some("尚无画布内容")), "待生成"); + assert_eq!(cover_placeholder_text(false, true, Some("其他错误")), "封面暂不可用"); + assert_eq!(cover_placeholder_text(true, true, Some("项目较大,请打开后查看")), "加载封面…"); + } }