refactor(xiaoyi): split canvas_workspace and jiansun_canvas_workspace into cohesive submodules (#131)
This commit is contained in:
parent
bcb1f27c67
commit
3b81e6f449
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,182 @@
|
||||
use super::super::{Backend, Event, R, Value, images, json, mpsc, original_project_present};
|
||||
use super::{acknowledge_adoption, candidate_matches_slot, completed_candidate, export_product_stage, jiansun_image_transform, load, load_detail_workspace, mapping, operation_receipt, production_image_target, read_candidate, revision, scope_state_for_view, uuid, variant};
|
||||
|
||||
pub(super) struct ActionScope<'a> {
|
||||
pub(crate) method: &'a str,
|
||||
pub(crate) input: &'a Value,
|
||||
pub(crate) import: bool,
|
||||
pub(crate) historical_adoption: bool,
|
||||
pub(crate) manual_adoption: bool,
|
||||
pub(crate) user_scope: Option<&'a Value>,
|
||||
pub(super) source: Option<super::jiansun_image_transform::SlotSource>,
|
||||
pub(crate) local: bool,
|
||||
pub(crate) batch: bool,
|
||||
pub(crate) state: Value,
|
||||
pub(crate) browsing: bool,
|
||||
pub(crate) user_target: Option<&'a Value>,
|
||||
pub(crate) view_scoped: bool,
|
||||
pub(crate) project_scoped_image: bool,
|
||||
pub(crate) handoff: bool,
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
self.canvas_workspace_action_with_source(method, input, events, ctx, None)
|
||||
}
|
||||
|
||||
pub(super) fn canvas_workspace_action_with_source(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>,
|
||||
ctx: &egui::Context, source: Option<jiansun_image_transform::SlotSource>,
|
||||
) -> R<Value> {
|
||||
let import = method == "slot-import-local" || method == "slot-append" && input["localPath"].is_string();
|
||||
let historical_adoption = method == "slot-adopt-prep" && input["historicalCandidate"] == true
|
||||
&& input["detailBatch"] != true && input["workflowOperationId"].is_null();
|
||||
let manual_adoption = method == "slot-adopt-prep" && input["manualAdoption"] == true
|
||||
&& input["detailBatch"] != true && input["workflowOperationId"].is_null() && input["workflowRun"].is_null();
|
||||
let user_scope = photocraft_ui_egui::jiansun::user_slot_scope(input);
|
||||
let local = manual_adoption || import || method == "slot-append" && input["useProductReference"] == true
|
||||
|| photocraft_ui_egui::jiansun::local_user_slot(method, input);
|
||||
if (!local || (method == "slot-append" && input["manualImage"] == true && input["useProductReference"] != true))
|
||||
&& !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted")
|
||||
{
|
||||
self.check_dispatch()?;
|
||||
}
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
original_project_present(&dir)?;
|
||||
if !matches!(method, "slot-read" | "slot-templates") && input["baseRevision"].as_u64().is_none() {
|
||||
return Err("无法确认当前画布,项目内容已保留".into());
|
||||
}
|
||||
if method == "slot-read" && !input["previewCandidateId"].is_null() {
|
||||
let id = uuid(&input["previewCandidateId"], "候选")?;
|
||||
let (scoped, view) = scope_state_for_view(load(&dir)?, input)?;
|
||||
let state = if view { scoped } else { self.opened_workspace_state(doc, scoped)?.0 };
|
||||
let record = read_candidate(&dir, &id)?;
|
||||
let pack = &state["template"];
|
||||
let variant = state["activeVariantId"].as_str().ok_or("当前花色缺失")?;
|
||||
let mapping = &state["mappings"][state["activeMapping"].as_str().unwrap_or_default()];
|
||||
let matches = pack["outputs"].as_array().into_iter().flatten()
|
||||
.filter(|output| output["component"] == state["activeOutput"]
|
||||
&& (mapping["outputId"].is_null() || mapping["outputId"] == output["id"]))
|
||||
.any(|output| output["slots"].as_array().into_iter().flatten().any(|field|
|
||||
field["kind"] == "image" && candidate_matches_slot(&record, &state, pack, output, field, variant)));
|
||||
if !matches {
|
||||
return Err("候选预览不属于当前画布".into());
|
||||
}
|
||||
let indexed = state["candidates"].as_array().is_some_and(|ids| ids.contains(&json!(id)));
|
||||
let (_, pixels) = completed_candidate(&dir, &state, record, indexed).ok_or("候选预览不可读取")?;
|
||||
let preview = super::images::decode_agent_image(&pixels)?;
|
||||
let reference = json!({"purpose":"template-candidate","doc":doc,"taskId":id,
|
||||
"accountId":self.auth["account"]["id"],"origin":self.origin});
|
||||
events.send(Event::Preview(reference, preview)).map_err(|_| "画布已关闭")?;
|
||||
return Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin}));
|
||||
}
|
||||
if method == "slot-read" {
|
||||
let workflow = self.opened_workspace_snapshot(doc, &dir)?;
|
||||
return self.canvas_result_with_workflow(doc, &dir, workflow);
|
||||
}
|
||||
if method == "slot-templates" {
|
||||
self.validate()?;
|
||||
let brand = uuid(&input["brandId"], "品牌")?;
|
||||
let category = uuid(&input["categoryId"], "品类")?;
|
||||
let pack = self.template_pack(&brand, &category, false)?;
|
||||
return Ok(
|
||||
json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"catalog":{"items":[{"id":pack["id"],"name":pack["name"],"version":pack["version"],"contentHash":pack["contentHash"],"brandId":pack["brandId"],"categoryId":pack["categoryId"]}]}}),
|
||||
);
|
||||
}
|
||||
if method == "slot-skeleton" && input["brief"].is_object() {
|
||||
self.install_brief_template(doc, &dir, input)?;
|
||||
}
|
||||
let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep" | "slot-transform-image");
|
||||
let state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? };
|
||||
let browsing = method == "slot-product-view";
|
||||
let user_target = user_scope.filter(|_| matches!(method,
|
||||
"slot-append" | "slot-import-local" | "slot-reuse" | "slot-edit-prep" | "slot-adopt-prep"
|
||||
| "slot-recover" | "slot-product-export" | "slot-skeleton"));
|
||||
let (mut state, view_scoped) = if !batch && !browsing && method != "slot-skeleton" {
|
||||
scope_state_for_view(state, input)?
|
||||
} else {
|
||||
(state, false)
|
||||
};
|
||||
if let Some(scope) = user_target {
|
||||
if scope["workspaceId"] != state["id"] {
|
||||
return Err("当前项目已切换,请回到原项目后再操作。".into());
|
||||
}
|
||||
let visible = (method == "slot-skeleton" && input["viewOutputId"].is_string())
|
||||
.then(|| scope_state_for_view(state.clone(), input)).transpose()?;
|
||||
let current = visible.as_ref().map_or(&state, |(scoped, _)| scoped);
|
||||
if scope["templateHash"] != current["template"]["contentHash"]
|
||||
|| scope["variantId"] != current["activeVariantId"] || scope["outputId"] != current["activeOutput"]
|
||||
{
|
||||
return Err("成品、花色或模板已切换,请回到原画布后再操作。".into());
|
||||
}
|
||||
}
|
||||
let project_scoped_image = batch && input["projectScopedImage"] == true;
|
||||
if project_scoped_image {
|
||||
state = production_image_target(state, &input["detailWorkspace"])?;
|
||||
}
|
||||
if batch && input["detailWorkspace"] != json!({"id":state["id"],"templateHash":state["template"]["contentHash"],
|
||||
"structureHash":state["structureHash"],"outputId":state["activeOutput"],"variantId":state["activeVariantId"]})
|
||||
{
|
||||
return Err("本轮图位的模板、输出或花色已变化,原候选保留".into());
|
||||
}
|
||||
// Sibling candidates change the workspace revision, not this document or slot.
|
||||
// The mapped layer and candidate are checked again below before reading any pixels.
|
||||
// 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
|
||||
&& input["workspaceId"].is_string() && input["workspaceId"] == state["id"];
|
||||
if !matches!(method, "slot-read" | "slot-recover" | "slot-adopted" | "slot-product-view")
|
||||
&& input["slotRevision"].as_u64() != Some(revision(&state))
|
||||
&& !manual_adoption && user_target.is_none() && !batch && !handoff && !(method == "slot-skeleton" && input["brief"].is_object()) {
|
||||
return Err("项目内容在操作期间有改动,请确认当前画布后重试。候选图片已保留。".into());
|
||||
}
|
||||
if method == "slot-product-export" {
|
||||
return export_product_stage(&dir, doc, &state, input, &self.scope());
|
||||
}
|
||||
let mut candidate_result = None;
|
||||
let mut operation_error = None;
|
||||
let mut scope = ActionScope {
|
||||
method,
|
||||
input,
|
||||
import,
|
||||
historical_adoption,
|
||||
manual_adoption,
|
||||
user_scope,
|
||||
source,
|
||||
local,
|
||||
batch,
|
||||
state,
|
||||
browsing,
|
||||
user_target,
|
||||
view_scoped,
|
||||
project_scoped_image,
|
||||
handoff,
|
||||
};
|
||||
if method == "slot-skeleton" || browsing {
|
||||
if let Some(early) = self.action_skeleton_or_view(&mut scope, doc, &dir, events, ctx, &mut candidate_result, &mut operation_error)? {
|
||||
return Ok(early);
|
||||
}
|
||||
} else if method == "slot-transform-image" || import || matches!(method, "slot-prepare-image" | "slot-append") {
|
||||
if let Some(early) = self.action_transform_image(&mut scope, doc, &dir, events, &mut candidate_result, ctx, &mut operation_error)? {
|
||||
return Ok(early);
|
||||
}
|
||||
} else if method == "slot-reuse" {
|
||||
let result = self.production_image_request(doc, input, events, ctx, None)?;
|
||||
if result["candidateId"].is_string() {
|
||||
candidate_result = Some(result);
|
||||
}
|
||||
} else if matches!(method, "slot-recover" | "slot-adopt-prep" | "slot-edit-prep" | "slot-import-local") {
|
||||
if let Some(early) = self.action_recover_or_slot(&mut scope, doc, &dir, events, ctx, &mut candidate_result, &mut operation_error)? {
|
||||
return Ok(early);
|
||||
}
|
||||
} else if method == "slot-adopted" {
|
||||
acknowledge_adoption(&dir, &scope.state, input)?;
|
||||
// The live document metadata is the only selected/applied authority.
|
||||
// Audit acknowledgements never undo the native undo/redo history.
|
||||
} else {
|
||||
return Err("原生画布操作未开放".into());
|
||||
}
|
||||
Ok(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, candidate_result, operation_error))
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,208 @@
|
||||
use super::action::ActionScope;
|
||||
use super::super::{Backend, Event, Path, R, Uuid, Value, json, mpsc, production_profile, read_json, template_slots, write_json};
|
||||
use super::{approved_structure_guides, candidate_pixels, candidate_receipt, checked_binding, definition, load, lock_candidate_dispatch, mapped_slot, mount_historical_adoption, operation_receipt, pending_candidate, placement_pixels, production_audit, production_placement_fit, read_candidate, reconcile_candidate, recover_candidate_without_task, revision, slot_frame, uuid};
|
||||
use photocraft_ui_egui::jiansun::production_facts::product_brief::{adoption_variant_brief};
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn action_recover_or_slot(
|
||||
&mut self,
|
||||
scope: &mut ActionScope<'_>,
|
||||
doc: u64,
|
||||
dir: &Path,
|
||||
events: &mpsc::Sender<Event>,
|
||||
ctx: &egui::Context,
|
||||
candidate_result: &mut Option<Value>,
|
||||
operation_error: &mut Option<String>,
|
||||
) -> R<Option<Value>> {
|
||||
let state = &mut scope.state;
|
||||
let input = scope.input;
|
||||
let method = scope.method;
|
||||
let batch = scope.batch;
|
||||
let manual_adoption = scope.manual_adoption;
|
||||
let historical_adoption = scope.historical_adoption;
|
||||
let _project_scoped_image = scope.project_scoped_image;
|
||||
let user_scope = scope.user_scope;
|
||||
let user_target = scope.user_target;
|
||||
let view_scoped = scope.view_scoped;
|
||||
let _ = (user_scope, user_target);
|
||||
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 user_target.is_some() && input["slotId"].is_string()
|
||||
&& (record["binding"]["slotId"] != input["slotId"]
|
||||
|| record["binding"]["variantId"] != state["activeVariantId"]
|
||||
|| record["binding"]["templateHash"] != state["template"]["contentHash"])
|
||||
{
|
||||
return Err("这项请求不属于当前花色和图位,请回到原图位查找。".into());
|
||||
}
|
||||
if matches!(record["sourceType"].as_str(), Some("product-reference" | "local-import")) || record["canvasTransform"].is_object() {
|
||||
return Ok(Some(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(Some(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.
|
||||
let file = dir.join("image-jobs").join(&candidate).join("task.json");
|
||||
match read_json(&file) {
|
||||
Ok(mut journal) if journal["phase"] == "prepared" && record["requestId"].is_null()
|
||||
&& journal["requestId"].is_null() && journal["upstreamTaskId"].is_null() => {
|
||||
if journal["id"] != candidate || journal["slotBinding"] != record["binding"] {
|
||||
return Err(format!("候选 {candidate} 与原请求 task.json 身份不一致"));
|
||||
}
|
||||
journal["notDispatched"] = json!(true);
|
||||
journal["message"] = json!("原图片请求未提交");
|
||||
*candidate_result = Some(candidate_receipt(&reconcile_candidate(&dir, &journal)?));
|
||||
}
|
||||
Ok(_) => {
|
||||
let call = self.image_job(None, &json!({"doc":doc,"taskId":candidate,"recoveryBudgetMs":input["recoveryBudgetMs"]}), true, events, ctx);
|
||||
let journal = read_json(&file)?;
|
||||
*candidate_result = Some(candidate_receipt(&reconcile_candidate(&dir, &journal)?));
|
||||
*operation_error = call.err();
|
||||
}
|
||||
Err(error) => {
|
||||
if file.try_exists().map_err(|_| error.clone())? { return Err(error); }
|
||||
let original = recover_candidate_without_task(&dir, &record)?;
|
||||
if original["phase"] == "unknown" {
|
||||
*operation_error = original["message"].as_str().map(str::to_owned);
|
||||
}
|
||||
*candidate_result = Some(candidate_receipt(&original));
|
||||
}
|
||||
}
|
||||
} else if matches!(method, "slot-adopt-prep" | "slot-edit-prep") {
|
||||
let variant_id = uuid(&input["variantId"], "花色")?;
|
||||
let id = input["slotId"].as_str().ok_or("请选择图片目标")?;
|
||||
let source_id = uuid(&input["candidateId"], "候选")?;
|
||||
let mut record = read_candidate(&dir, &source_id)?;
|
||||
if historical_adoption {
|
||||
record = mount_historical_adoption(&dir, &state, input, &record, view_scoped)?;
|
||||
let current = load(&dir)?;
|
||||
state["candidates"] = current["candidates"].clone();
|
||||
state["revision"] = current["revision"].clone();
|
||||
}
|
||||
let (output, field) = definition(&state, id, &variant_id)?;
|
||||
let candidate = uuid(&record["id"], "候选")?;
|
||||
if record["phase"] != "complete" {
|
||||
let phase = record["phase"].as_str().unwrap_or("unknown");
|
||||
return Err(format!("候选 {candidate} 尚未完成(当前状态 phase={phase}),未采纳"));
|
||||
}
|
||||
if !record["retirement"].is_null() {
|
||||
return Err(format!("候选 {candidate} 已退回或作废,未采纳"));
|
||||
}
|
||||
if !state["candidates"].as_array().is_some_and(|ids| ids.contains(&json!(candidate))) {
|
||||
return Err(format!("候选 {candidate} 未登记在当前工作区候选列表中(若需复用历史候选请传 historicalCandidate=true),未采纳"));
|
||||
}
|
||||
if record["binding"]["workspaceId"] != state["id"] {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定工作区 {:?} 与当前工作区 {:?} 不一致,未采纳",
|
||||
record["binding"]["workspaceId"].as_str().unwrap_or(""),
|
||||
state["id"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["variantId"] != variant_id {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定花色 variantId={:?} 与当前目标 variantId={variant_id} 不一致,未采纳",
|
||||
record["binding"]["variantId"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["slotId"] != id {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定图位 slotId={:?} 与当前目标 slotId={id} 不一致(如需跨图位复用请使用 transform_slot_image 或 stage_archived_image),未采纳",
|
||||
record["binding"]["slotId"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["outputId"] != output["id"]
|
||||
|| (record["binding"]["component"].is_string() && record["binding"]["component"] != output["component"])
|
||||
{
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定成品 outputId={:?}/component={:?} 与当前画布 outputId={:?}/component={:?} 不一致,未采纳",
|
||||
record["binding"]["outputId"].as_str().unwrap_or(""),
|
||||
record["binding"]["component"].as_str().unwrap_or(""),
|
||||
output["id"].as_str().unwrap_or(""),
|
||||
output["component"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["fieldId"] != field["fieldId"] {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定图位字段 fieldId={:?} 与当前目标 fieldId={:?} 不一致,未采纳",
|
||||
record["binding"]["fieldId"].as_str().unwrap_or(""),
|
||||
field["fieldId"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["templateHash"] != state["template"]["contentHash"] {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定模板版本 templateHash={:?} 与当前模板 {:?} 不一致,未采纳",
|
||||
record["binding"]["templateHash"].as_str().unwrap_or(""),
|
||||
state["template"]["contentHash"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
if record["binding"]["structureHash"] != state["structureHash"] {
|
||||
return Err(format!(
|
||||
"候选 {candidate} 绑定结构版本 structureHash={:?} 与当前画布结构 {:?} 不一致(若需挂载历史候选请传 historicalCandidate=true),未采纳",
|
||||
record["binding"]["structureHash"].as_str().unwrap_or(""),
|
||||
state["structureHash"].as_str().unwrap_or("")
|
||||
));
|
||||
}
|
||||
let journal = read_json(&dir.join("image-jobs").join(&candidate).join("task.json"))?;
|
||||
let artifact = template_slots::artifact(&dir, &candidate, &journal)?;
|
||||
if artifact != record["artifact"] {
|
||||
return Err("原候选像素记录不一致,未采纳".into());
|
||||
}
|
||||
let layer = input["nativeLayerId"].as_u64().filter(|v| *v > 0).ok_or("原生图片图层身份缺失")?;
|
||||
let mapped = mapped_slot(&state, id, &variant_id).filter(|row| row["nativeLayerId"] == layer)
|
||||
.ok_or("原生图层不属于此花色和图片目标,未采纳")?;
|
||||
let frame = slot_frame(field, Some(mapped)).ok_or("当前图片图层缺少已核对的范围,未采纳")?;
|
||||
let bytes = candidate_pixels(&dir, &artifact)?;
|
||||
let fit = production_placement_fit(&record, field, &input["fit"], input["detailBatch"] == true);
|
||||
let meta = json!({"canvasFirst":true,"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"baseRevision":input["baseRevision"],"workspaceRevision":state["revision"],"workspaceId":state["id"],"templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"outputId":output["component"],"documentId":output["id"],"slotId":id,"variantId":variant_id,"candidateId":candidate,"taskId":candidate,"nativeLayerId":layer,"sha256":artifact["sha256"],"fit":fit,"frame":frame});
|
||||
let mut meta = meta;
|
||||
if mapped["embeddedTarget"].is_object() {
|
||||
meta["embeddedTarget"] = mapped["embeddedTarget"].clone();
|
||||
}
|
||||
if photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(field)
|
||||
|| photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(mapped)
|
||||
{
|
||||
meta["requireOpaque"] = json!(true);
|
||||
}
|
||||
if manual_adoption { meta["manualAdoption"] = json!(true); }
|
||||
if historical_adoption { meta["sourceCandidateId"] = json!(source_id); }
|
||||
if input["previewExport"] == true && !batch { meta["previewExport"] = json!(true); }
|
||||
meta["fitRequested"] = json!(input["fit"].is_string());
|
||||
if batch {
|
||||
meta["detailBatch"] = json!(true);
|
||||
meta["variantBrief"] = adoption_variant_brief(&state["brief"], &variant_id,
|
||||
output["component"].as_str().unwrap_or_default());
|
||||
}
|
||||
if method == "slot-adopt-prep" && state["productTemplates"].is_object()
|
||||
&& let Some(component) = output["component"].as_str()
|
||||
&& let Some(profile) = production_profile::select(&state["template"], component)?
|
||||
&& let Some(field) = field["fieldId"].as_str()
|
||||
&& let Some(recipe) = profile["imageRules"][field].get("structureGuides")
|
||||
{
|
||||
let audit = production_audit(&dir, &state, component, &variant_id, &self.scope())?;
|
||||
if let Some(guides) = approved_structure_guides(recipe, &audit["items"][id], &candidate)? {
|
||||
meta["structureGuides"] = guides;
|
||||
}
|
||||
}
|
||||
let (bytes, sizing) = if method == "slot-adopt-prep" && state["productTemplates"].is_object() {
|
||||
placement_pixels(bytes)?
|
||||
} else { (bytes,Value::Null) };
|
||||
if sizing.is_object() { meta["sourceSizing"] = sizing; }
|
||||
if method == "slot-edit-prep" {
|
||||
meta["purpose"] = json!("professional-edit");
|
||||
events.send(Event::SlotAdopt { bytes, meta }).map_err(|_| "工作台已关闭,原候选和采用准备保留")?;
|
||||
} else {
|
||||
let adoption = Uuid::new_v4().to_string();
|
||||
meta["adoptionId"] = json!(adoption);
|
||||
if let Some(operation) = input.get("workflowOperationId") {
|
||||
meta["workflowOperationId"] = operation.clone();
|
||||
meta["workflowRun"] = input["workflowRun"].clone();
|
||||
}
|
||||
write_json(&dir.join("template-outputs").join(format!("canvas-adoption-{adoption}.json")), &json!({"phase":"prepared","meta":meta}))?;
|
||||
events.send(Event::SlotAdopt { bytes, meta }).map_err(|_| "工作台已关闭,原候选和采用准备保留")?;
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,348 @@
|
||||
use super::action::ActionScope;
|
||||
use super::super::{Backend, Event, Path, R, Uuid, Value, creation, hash, images, json, load_draft, mpsc, production_profile, read_json, slot_canvas, sync, template_slots, write_json};
|
||||
use super::{MAPPING, SUPPORTED_PRODUCTION_OUTPUTS, activate_edited_output_with_knowledge, apply_locked_production_profiles, blocked_production_stages, canvas_template, clear_sample_copy, exists, generation_references_for_output, load, mapping, mapping_key, missing_ending_pages, original_preview_path, output_variant, pending, pending_summary, persist, persist_locked, prepare_product_template, product_view_variant, production_stages, read_production_settings, references, resumable_stages, revision, runnable_stages, save_production_settings, skeleton_component, snapshot_for_view, template_fidelity, text, variant, variants};
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn install_brief_template(&mut self, doc: u64, dir: &Path, input: &Value) -> R<()> {
|
||||
self.creation_guard(doc, &dir)?;
|
||||
let previous = if exists(&dir) { Some(load(&dir)?) } else { None };
|
||||
if input["generateProduct"] == true && previous.as_ref().is_some_and(|old| old["activeMapping"].is_string()) {
|
||||
return Err("请在新项目中一键生成整套详情页,当前画布与编辑已保留".into());
|
||||
}
|
||||
if previous.is_some() && !pending_summary(&dir)?.is_empty() {
|
||||
return Err("原候选仍待核查,未覆盖其产品资料与参考图".into());
|
||||
}
|
||||
if previous.is_none() && dir.join("template-slots.json").exists() && template_slots::load(&dir)?["template"].is_object() {
|
||||
return Err("旧图位项目仍保留原A/B候选和编辑稿,请新建画布项目选择模板".into());
|
||||
}
|
||||
let expected = previous.as_ref().map_or(0, revision);
|
||||
if previous.is_some() && input["slotRevision"].as_u64() != Some(expected) {
|
||||
return Err("准备模板期间项目内容有改动,原画布已保留。".into());
|
||||
}
|
||||
let mut common = creation::validated_brief(&input["brief"])?;
|
||||
references(&dir, &common["images"])?;
|
||||
self.validate()?;
|
||||
let production = input["generateProduct"] == true;
|
||||
let brand = common["brandId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品牌")?;
|
||||
let category = common["categoryId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品类")?;
|
||||
let new_release = production && previous.is_none() && input["template"]["enterprise"].is_object();
|
||||
let release_packs = if new_release {
|
||||
let project = self.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
let session = dir.join("agent").join(self.scope()).join(project).join("conversation-v1");
|
||||
let template_id = input["template"]["id"].as_str().ok_or("企业模板编号缺失")?;
|
||||
let mut request = json!({"action":"xiaoyi-pack","templateId":template_id,
|
||||
"name":input["template"]["name"],"brandId":brand,"categoryId":category,
|
||||
"projectDir":session,"cache":self.dir().join("xiaoyi-blobs")});
|
||||
if input["template"]["enterprise"]["sourceKind"] == "xiaoyi-release" {
|
||||
let version = input["template"]["version"].as_str().ok_or("模板版本缺失")?;
|
||||
request["knowledgeVersion"] = json!(format!("{template_id}@{version}"));
|
||||
}
|
||||
let result = self.enterprise_template_request(request)?;
|
||||
let mut packs = result["packs"].as_object().cloned().ok_or("小壹清单没有可用组件")?;
|
||||
for (component, pack) in &mut packs {
|
||||
production_profile::add_image_fields(pack, component)?;
|
||||
pack["contentHash"] = json!(template_slots::pack_hash(pack)?);
|
||||
template_slots::validate_pack(pack)?;
|
||||
}
|
||||
Some(packs)
|
||||
} else { None };
|
||||
let pack = if let Some(packs) = &release_packs {
|
||||
let component = input["template"]["enterprise"]["component"].as_str().unwrap_or("detail");
|
||||
packs.get(component).cloned().ok_or("所选组件未在小壹知识包发布")?
|
||||
} else {
|
||||
canvas_template(previous.as_ref(), &input["template"], brand, category,
|
||||
|| self.selected_template_pack(&input["template"], brand, category))?
|
||||
};
|
||||
let width = pack["enterprise"]["canvas"][0].as_u64().or_else(|| {
|
||||
let outputs = pack["outputs"].as_array()?;
|
||||
outputs.iter().find(|output| output["component"] == input["outputId"])
|
||||
.or_else(|| outputs.first())?["width"].as_u64()
|
||||
}).ok_or("模板画布宽度缺失")?;
|
||||
let variants = variants(&dir, &common, previous.as_ref())?;
|
||||
// Persist the generated default identity with the product brief on
|
||||
// the first install, so later material selections append to it.
|
||||
common["variants"] = json!(variants);
|
||||
let active = input["variantId"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| previous.as_ref().and_then(|p| p["activeVariantId"].as_str().map(str::to_owned)))
|
||||
.unwrap_or_else(|| variants[0]["id"].as_str().unwrap_or("").to_owned());
|
||||
if !variants.iter().any(|variant| variant["id"] == active) {
|
||||
return Err("当前花色不属于所填产品资料".into());
|
||||
}
|
||||
let c = creation::load(&dir)?;
|
||||
let mut changes = json!({"doc":doc,"revision":c["revision"],"brief":common,"width":width});
|
||||
if let Some(path) = input.get("deliveryDir") {
|
||||
changes["deliveryDir"] = path.clone();
|
||||
}
|
||||
let release_pack = pack.get("xiaoyi").map(|_| &pack);
|
||||
self.save_creation_brief(doc, &dir, &changes, release_pack)?;
|
||||
let c = creation::load(&dir)?;
|
||||
let mut next = previous.unwrap_or_else(
|
||||
|| json!({"version":1,"canvasFirst":true,"id":Uuid::new_v4().to_string(),"revision":0,
|
||||
"candidates":[],"mappings":{},"adoptions":[],"omitSampleCopy":true}),
|
||||
);
|
||||
next["brief"] = c["brief"].clone();
|
||||
next["width"] = c["width"].clone();
|
||||
next["variants"] = json!(variants);
|
||||
next["activeVariantId"] = json!(active);
|
||||
if production {
|
||||
if let Some(packs) = release_packs {
|
||||
next["productTemplates"] = Value::Object(packs);
|
||||
next["productTemplateIssues"] = json!({});
|
||||
} else if !next["productTemplates"].is_object() {
|
||||
let mut packs = serde_json::Map::new();
|
||||
for component in SUPPORTED_PRODUCTION_OUTPUTS {
|
||||
if pack["outputs"].as_array().into_iter().flatten().any(|output| output["component"] == component) {
|
||||
let mut component_pack = pack.clone();
|
||||
production_profile::add_image_fields(&mut component_pack, component)?;
|
||||
packs.insert(component.into(), component_pack);
|
||||
}
|
||||
}
|
||||
next["productTemplates"] = Value::Object(packs);
|
||||
next["productTemplateIssues"] = json!({});
|
||||
}
|
||||
for stage in runnable_stages(&next, production_stages(&next)) {
|
||||
generation_references_for_output(&dir, &next,
|
||||
stage["variantId"].as_str().ok_or("制作款式缺失")?,
|
||||
stage["outputId"].as_str().ok_or("制作成品缺失")?)?;
|
||||
}
|
||||
}
|
||||
next["template"] = pack;
|
||||
next["structureHash"] = json!(hash(&json!([next["template"]["contentHash"], next["width"]]).to_string()));
|
||||
persist(&dir, next, expected)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn action_skeleton_or_view(
|
||||
&mut self,
|
||||
scope: &mut ActionScope<'_>,
|
||||
doc: u64,
|
||||
dir: &Path,
|
||||
events: &mpsc::Sender<Event>,
|
||||
ctx: &egui::Context,
|
||||
_candidate_result: &mut Option<Value>,
|
||||
_operation_error: &mut Option<String>,
|
||||
) -> R<Option<Value>> {
|
||||
let state = &mut scope.state;
|
||||
let input = scope.input;
|
||||
let _method = scope.method;
|
||||
let browsing = scope.browsing;
|
||||
let _import = scope.import;
|
||||
let user_scope = scope.user_scope;
|
||||
let user_target = scope.user_target;
|
||||
let handoff = scope.handoff;
|
||||
let view_scoped = scope.view_scoped;
|
||||
let _ = (user_scope, user_target, view_scoped);
|
||||
if browsing && (!state["productTemplates"].is_object() || input["workspaceId"] != state["id"]) {
|
||||
return Err("产品画布已变化,未切换查看".into());
|
||||
}
|
||||
let start_product = !browsing && (input["generateProduct"] == true || input["resumeProduct"] == true);
|
||||
if start_product {
|
||||
let stages = resumable_stages(&dir, &state, &creation::load(&dir)?["revision"], true);
|
||||
if stages.iter().any(|stage| stage["outputId"] == "detail") {
|
||||
creation::require_detail_barcode(&state["brief"])?;
|
||||
}
|
||||
if stages.is_empty() {
|
||||
let blocked = blocked_production_stages(&state);
|
||||
if blocked.is_empty() { return Err("已选成品均已在项目中保存".into()); }
|
||||
let reasons = blocked.iter().filter_map(|stage| stage["reason"].as_str())
|
||||
.collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>().join("。");
|
||||
return Err(format!("所选模板暂无可制作的输出。{reasons}。请核对模板资源后选用新版本。"));
|
||||
}
|
||||
if input["resumeProduct"] == true && let Some(path) = input.get("deliveryDir") {
|
||||
creation::save_delivery_directory(&dir, path)?;
|
||||
}
|
||||
if input["generateProduct"] == true || input["refinement"].is_boolean() {
|
||||
let refinement = input["refinement"].as_bool()
|
||||
.unwrap_or(read_production_settings(&dir)?["refinement"] == true);
|
||||
save_production_settings(&dir, refinement)?;
|
||||
}
|
||||
let mut prepared = self.canvas_workspace_result(doc, &dir)?;
|
||||
prepared["workflow"]["productionStages"] = json!(stages);
|
||||
prepared["productionPreparation"] = json!(true);
|
||||
prepared["baseRevision"] = input["baseRevision"].clone();
|
||||
return Ok(Some(prepared));
|
||||
}
|
||||
if let Some(refinement) = input["refinement"].as_bool() {
|
||||
save_production_settings(&dir, refinement)?;
|
||||
}
|
||||
let component = skeleton_component(&state, input)?.to_owned();
|
||||
let component = component.as_str();
|
||||
let stale_issue = state["productTemplateIssues"][component].as_str().map(str::to_owned);
|
||||
if !state["productTemplates"][component].is_object() {
|
||||
if let Some(reason) = &stale_issue { return Err(reason.clone()); }
|
||||
if state["productTemplates"].is_object() {
|
||||
return Err("当前项目没有所选输出的固定模板".into());
|
||||
}
|
||||
}
|
||||
let select_variant = if browsing { product_view_variant } else { output_variant };
|
||||
let variant_id = select_variant(&state, component, input["variantId"].as_str())?.to_owned();
|
||||
if handoff { apply_locked_production_profiles(state, &input["knowledge"])?; }
|
||||
if let Some(pack) = state["productTemplates"].get(component) {
|
||||
if handoff && !input["knowledge"].is_null() && pack["xiaoyi"] != input["knowledge"] {
|
||||
return Err("所选组件不属于本轮锁定的小壹模板".into());
|
||||
}
|
||||
template_slots::validate_pack(pack)?;
|
||||
state["template"] = pack.clone();
|
||||
state["structureHash"] = json!(hash(&json!([state["template"]["contentHash"],state["width"]]).to_string()));
|
||||
}
|
||||
let document = input["documentId"].as_str();
|
||||
let key = mapping_key(&variant_id, component, document);
|
||||
let edited = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
let previous_view = (input["continueProduct"] == true).then(|| state["activeMapping"].as_str())
|
||||
.flatten().map(|key| dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")));
|
||||
let report = |mut value: Value| {
|
||||
value["doc"] = json!(doc);
|
||||
value["accountId"] = self.auth["account"]["id"].clone();
|
||||
value["origin"] = json!(self.origin);
|
||||
let event = if browsing {
|
||||
value["workspaceId"] = input["workspaceId"].clone();
|
||||
value["productViewId"] = input["productViewId"].clone();
|
||||
"slot-product-view-progress"
|
||||
} else {
|
||||
"template-progress"
|
||||
};
|
||||
let _ = events.send(Event::Json(event.into(), Ok(value)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
};
|
||||
let has_edit = edited.is_file();
|
||||
if browsing {
|
||||
report(json!({"phase":if has_edit {"view-open"} else {"metadata"}}));
|
||||
}
|
||||
let mut saved_view_can_be_reused = false;
|
||||
let mut native = if has_edit {
|
||||
let mut saved = super::load_draft(&dir, &edited).map_err(|_| "原生编辑稿无法读取,未用空骨架覆盖")?;
|
||||
saved_view_can_be_reused = browsing && missing_ending_pages(&saved).is_empty();
|
||||
self.repair_template_ending(&dir, &mut saved, report)?;
|
||||
saved
|
||||
} else if state["template"]["enterprise"].is_object() {
|
||||
self.enterprise_template_canvas(&state["template"], component, document, &variant_id, report)?
|
||||
} else {
|
||||
slot_canvas::skeleton(&state["template"], component, document, &variant_id)?
|
||||
};
|
||||
let product_copy = state["productTemplates"].is_object() && !has_edit;
|
||||
if !has_edit && state["productTemplates"].is_object()
|
||||
&& let Some(name) = state["brief"]["name"].as_str().filter(|name| !name.is_empty()) {
|
||||
native.name = name.into();
|
||||
}
|
||||
native.id = photocraft_doc::DocId(doc);
|
||||
let mut meta = mapping(&native).ok_or("模板骨架缺少真实图层映射")?;
|
||||
if meta["templateHash"] != state["template"]["contentHash"] || meta["variantId"] != variant_id || meta["component"] != component {
|
||||
return Err("原生骨架与项目花色或模板不一致,未打开".into());
|
||||
}
|
||||
meta["workspaceId"] = state["id"].clone();
|
||||
if !has_edit {
|
||||
meta["originalLayerIds"] = json!(native.walk().iter().map(|(_,_,layer)| layer.id.0).collect::<Vec<_>>());
|
||||
}
|
||||
if !has_edit && state["template"]["enterprise"].is_object()
|
||||
&& let Err(error) = production_profile::select(&state["template"], component)
|
||||
.and_then(|profile| template_fidelity::capture(&dir, &native, &meta, profile))
|
||||
{
|
||||
log::warn!("无法保存模板原屏快照:{error}");
|
||||
}
|
||||
let original_preview_path = original_preview_path(&dir, &key);
|
||||
let mut original_preview = (product_copy && state["template"]["enterprise"].is_object())
|
||||
.then(|| photocraft_ui_egui::jiansun::template_preview::OriginalPreview::capture(&native, &meta))
|
||||
.flatten();
|
||||
let legacy_empty_copy = !state["productTemplates"].is_object() && component == "detail" && state["omitSampleCopy"] == true;
|
||||
if legacy_empty_copy && !has_edit {
|
||||
clear_sample_copy(&mut native.layers);
|
||||
}
|
||||
if legacy_empty_copy {
|
||||
meta["omitSampleCopy"] = json!(true);
|
||||
if !has_edit {
|
||||
for page in meta["outputs"].as_array_mut().into_iter().flatten() {
|
||||
for field in page["mapping"]["fields"].as_array_mut().into_iter().flatten() {
|
||||
if field["kind"] == "text" {
|
||||
field["originalText"] = json!("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if product_copy {
|
||||
prepare_product_template(&mut native, &mut meta, &state["template"], component)?;
|
||||
}
|
||||
let original_preview = if let Some(preview) = &mut original_preview {
|
||||
preview.keep_preview_changes(&native);
|
||||
if preview.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let value = serde_json::to_value(preview).map_err(|_| "原稿预览无法保存")?;
|
||||
write_json(&original_preview_path, &value)?;
|
||||
Some(value)
|
||||
}
|
||||
} else if component == "detail" && has_edit && original_preview_path.is_file() {
|
||||
read_json(&original_preview_path).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (name, text) in &mut native.metadata.text {
|
||||
if name == MAPPING {
|
||||
*text = meta.to_string();
|
||||
}
|
||||
}
|
||||
state["activeVariantId"] = json!(variant_id);
|
||||
state["activeOutput"] = json!(component);
|
||||
state["activeMapping"] = json!(key);
|
||||
state["mappings"][&key] = meta;
|
||||
if stale_issue.is_some() && let Some(issues) = state["productTemplateIssues"].as_object_mut() {
|
||||
issues.remove(component);
|
||||
}
|
||||
let mut result = if browsing {
|
||||
if let Some(reason) = stale_issue.as_deref() {
|
||||
let _guard = sync::context_guard();
|
||||
let mut current = load(&dir)?;
|
||||
if current["id"] != state["id"]
|
||||
|| current["productTemplates"][component]["contentHash"] != state["template"]["contentHash"]
|
||||
{
|
||||
return Err("产品模板已变化,未切换查看".into());
|
||||
}
|
||||
if current["productTemplateIssues"][component] == reason
|
||||
&& let Some(issues) = current["productTemplateIssues"].as_object_mut()
|
||||
{
|
||||
issues.remove(component);
|
||||
let expected = revision(¤t);
|
||||
persist_locked(&dir, &mut current, expected)?;
|
||||
}
|
||||
state["productTemplateIssues"] = current["productTemplateIssues"].clone();
|
||||
}
|
||||
let workflow = snapshot_for_view(&dir, Some(state.clone()), false)?;
|
||||
json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,
|
||||
"pending":workflow["pending"],"workflow":workflow,"canvasFirst":true})
|
||||
} else {
|
||||
if input["continueProduct"] == true {
|
||||
let _guard = sync::context_guard();
|
||||
// 载入草稿期间可能新增候选预留,交接时读取最新工作区。
|
||||
activate_edited_output_with_knowledge(&dir, &native, &input["knowledge"], false)?;
|
||||
} else {
|
||||
let previous = revision(&state);
|
||||
persist(&dir, state.clone(), previous)?;
|
||||
}
|
||||
self.access.opened_doc_scopes.lock().unwrap().remove(&doc);
|
||||
self.canvas_workspace_result(doc, &dir)?
|
||||
};
|
||||
result["baseRevision"] = input["baseRevision"].clone();
|
||||
result["writeEpoch"] = input["writeEpoch"].clone();
|
||||
result["outputId"] = json!(component);
|
||||
result["documentId"] = json!(document);
|
||||
result["variantId"] = json!(variant_id);
|
||||
result["canvasFirst"] = json!(true);
|
||||
result["workspaceId"] = result["workflow"]["workspaceId"].clone();
|
||||
result["continueProduct"] = input["continueProduct"].clone();
|
||||
if let Some(previous) = previous_view { result["previousViewPath"] = json!(previous); }
|
||||
if browsing {
|
||||
result["productViewId"] = input["productViewId"].clone();
|
||||
result["viewPath"] = json!(edited);
|
||||
result["canReuseSavedView"] = json!(saved_view_can_be_reused);
|
||||
}
|
||||
let view_receipt = browsing.then(|| result.clone());
|
||||
if let Some(original_preview) = original_preview {
|
||||
result["originalPreview"] = original_preview;
|
||||
}
|
||||
events.send(Event::SlotCanvas(Box::new(native), result)).map_err(|_| "工作台已关闭,模板骨架记录保留")?;
|
||||
if let Some(receipt) = view_receipt { return Ok(Some(receipt)); }
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,233 @@
|
||||
use super::action::ActionScope;
|
||||
use super::super::{Arc, Backend, Event, Path, R, Uuid, Value, creation, fs, hash, images, json, mpsc, now, read_json, template_slots};
|
||||
use super::{build_manual_image_fact_context, candidate_limit_receipt, candidate_limits, candidate_path, candidate_receipt, candidate_uses_current_inputs, definition, exists, generation_references_for_output, import_local_candidate, input_hash, jiansun_image_transform, load, lock_slot_dispatch, mapped_slot, new_binding, operation_receipt, original_product_candidate, output_uses_variant, product_crop_mode, read_candidate, references, resolve_product_reference_index, revision, slot_dispatch_usage, slot_frame, snapshot, specified_image_ratio, text, uuid};
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn action_transform_image(
|
||||
&mut self,
|
||||
scope: &mut ActionScope<'_>,
|
||||
doc: u64,
|
||||
dir: &Path,
|
||||
events: &mpsc::Sender<Event>,
|
||||
candidate_result: &mut Option<Value>,
|
||||
ctx: &egui::Context,
|
||||
operation_error: &mut Option<String>,
|
||||
) -> R<Option<Value>> {
|
||||
let state = &mut scope.state;
|
||||
let input = scope.input;
|
||||
let batch = scope.batch;
|
||||
let _manual_adoption = scope.manual_adoption;
|
||||
let project_scoped_image = scope.project_scoped_image;
|
||||
let _user_scope = scope.user_scope;
|
||||
let user_target = scope.user_target;
|
||||
let local = scope.local;
|
||||
let source = scope.source.take();
|
||||
let import = scope.import;
|
||||
let view_scoped = scope.view_scoped;
|
||||
let method = scope.method;
|
||||
if method == "slot-transform-image" {
|
||||
let record = jiansun_image_transform::stage_candidate(&dir, state.clone(), input, source, project_scoped_image || view_scoped)?;
|
||||
let id = record["id"].as_str().ok_or("生成图片任务编号无效")?;
|
||||
let task = read_json(&candidate_path(&dir, id)?.with_file_name("task.json"))?;
|
||||
self.retain_generated_image(doc, &dir, &task, Some((events, ctx)));
|
||||
if project_scoped_image {
|
||||
return Ok(Some(candidate_receipt(&record)));
|
||||
}
|
||||
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));
|
||||
}
|
||||
let receipt = candidate_receipt(&record);
|
||||
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();
|
||||
return Ok(Some(receipt));
|
||||
} else if import || matches!(method, "slot-prepare-image" | "slot-append") {
|
||||
let variant_id = uuid(&input["variantId"], "花色")?;
|
||||
let id = input["slotId"].as_str().ok_or("请选择图片目标")?.to_owned();
|
||||
let (output, field) = definition(&state, &id, &variant_id)?;
|
||||
if user_target.is_some()
|
||||
&& (output["component"] != state["activeOutput"] || state["activeVariantId"] != variant_id
|
||||
|| mapped_slot(&state, &id, &variant_id).is_none_or(|mapped|
|
||||
input["nativeLayerId"].is_number() && input["nativeLayerId"] != mapped["nativeLayerId"]))
|
||||
{
|
||||
return Err("所选图片图位不在当前画布,请重新选择图位。".into());
|
||||
}
|
||||
let retry_of = input.get("retryOf").filter(|value| !value.is_null()).map(|value| uuid(value, "原生图候选")).transpose()?;
|
||||
if let Some(previous) = retry_of.as_deref() {
|
||||
let failed = read_candidate(&dir, previous)?;
|
||||
if input["detailBatch"] != true || failed["phase"] != "failed" || failed["retryableFailure"] != true
|
||||
|| failed["binding"]["slotId"] != id || failed["binding"]["variantId"] != variant_id
|
||||
|| failed["binding"]["templateHash"] != state["template"]["contentHash"]
|
||||
|| !candidate_uses_current_inputs(&dir, &state, &failed, &variant_id)?
|
||||
{ return Err("原生图失败尚未确认可重试,候选已保留".into()); }
|
||||
}
|
||||
if !output_uses_variant(&state["brief"], output["component"].as_str().unwrap_or("detail"), &variant_id) {
|
||||
return Err("此颜色未选入当前图类,请在产品资料调整出图颜色".into());
|
||||
}
|
||||
let mut field = field.clone();
|
||||
let image_ratio = specified_image_ratio(&field);
|
||||
field["frame"] = slot_frame(&field, mapped_slot(&state, &id, &variant_id))
|
||||
.ok_or("请先打开对应模板画布,核对图片图层范围")?.clone();
|
||||
let output = output.clone();
|
||||
let preparing = method == "slot-prepare-image";
|
||||
if import {
|
||||
let record = import_local_candidate(&dir, state.clone(), &output, &field, &id, &variant_id, input, project_scoped_image || view_scoped)?;
|
||||
return Ok(Some(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')))
|
||||
.ok_or("图片要求须为文本且不能含控制字符")?;
|
||||
let parent = input.get("parentCandidateId").filter(|v| !v.is_null()).map(|value| uuid(value, "原候选")).transpose()?;
|
||||
let mut attachments = creation::composer_attachments::resolve(&dir, &input.get("attachments").cloned().unwrap_or_else(|| json!([])))?;
|
||||
if let Some(parent) = &parent {
|
||||
let previous = read_candidate(&dir, parent)?;
|
||||
if previous["binding"]["slotId"] != id
|
||||
|| previous["binding"]["variantId"] != variant_id
|
||||
|| previous["phase"] != "complete"
|
||||
{
|
||||
return Err("原候选仍未知或不属于此图片目标,未重新生成".into());
|
||||
}
|
||||
let journal = read_json(&dir.join("image-jobs").join(parent).join("task.json"))?;
|
||||
template_slots::artifact(&dir, parent, &journal)?;
|
||||
let bytes = fs::read(dir.join("image-jobs").join(parent).join("generated.png")).map_err(|_| "原候选底图不可读取,未发送修改")?;
|
||||
attachments.insert(0, (json!({"id":parent,"purpose":"selected-candidate-edit-base"}), bytes));
|
||||
}
|
||||
let mut creation = creation::load(&dir)?;
|
||||
let mut images = generation_references_for_output(&dir, &state, &variant_id,
|
||||
output["component"].as_str().unwrap_or("detail"))?;
|
||||
if input["useProductReference"] == true {
|
||||
let slot = json!({"slotId":id,"variantId":variant_id});
|
||||
let _admission = if batch {
|
||||
let lock = lock_slot_dispatch(&dir, &slot)?.ok_or("本图位已有生图批次正在处理")?;
|
||||
let (_, max, _) = candidate_limits(&dir, &state, output["component"].as_str().unwrap_or_default())?;
|
||||
let (used, _, _) = slot_dispatch_usage(&dir, &load(&dir)?, &slot, &[], None)?;
|
||||
if used >= max {
|
||||
let limit = candidate_limit_receipt(&slot, used, max);
|
||||
if project_scoped_image { return Ok(Some(limit)); }
|
||||
return Ok(Some(operation_receipt(self.canvas_workspace_result_for_view(doc, &dir, input, view_scoped)?, Some(limit), None)));
|
||||
}
|
||||
Some(lock)
|
||||
} else { None };
|
||||
if parent.is_some() || !attachments.is_empty() {
|
||||
return Err("使用产品原图只能添加新候选,请先关闭改图或清除临时参考图".into());
|
||||
}
|
||||
let candidate = Uuid::new_v4().to_string();
|
||||
let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, "产品原图");
|
||||
if batch { binding["detailBatch"] = json!(true); } else { binding["origin"] = json!("human"); }
|
||||
let index = resolve_product_reference_index(&images, &input["referenceIndex"], input.get("referencePath"))?;
|
||||
if let Some(crop) = input.get("referenceCrop").filter(|value| !value.is_null()) {
|
||||
binding["referenceCrop"] = crop.clone();
|
||||
if let Some(mode @ ("inside" | "cover")) = product_crop_mode(&state, &output, &field)? {
|
||||
binding["referenceCropMode"] = json!(mode);
|
||||
}
|
||||
}
|
||||
let mut record = original_product_candidate(&dir, state.clone(), binding, &images, index, &field["frame"], project_scoped_image || view_scoped)?;
|
||||
if input["adoptImmediately"] == true {
|
||||
record["adoptImmediately"] = json!(true);
|
||||
}
|
||||
if project_scoped_image {
|
||||
return Ok(Some(candidate_receipt(&record)));
|
||||
}
|
||||
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":candidate})) {
|
||||
reference["purpose"] = json!("template-candidate");
|
||||
let _ = events.send(Event::Preview(reference, preview));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(Some(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) {
|
||||
return Err("附件所属项目已变化,请重新选择".into());
|
||||
}
|
||||
if let Some(indices) = input["referenceIndexes"].as_array() {
|
||||
let selected = indices.iter().map(|value| {
|
||||
let index = value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("参考图编号无效")?;
|
||||
images.get(index).filter(|image| image["purpose"] == "product").cloned().ok_or("同款原图编号无效")
|
||||
}).collect::<Result<Vec<_>, _>>()?;
|
||||
if selected.is_empty() { return Err("正式生图至少需要一张同款产品参考图".into()); }
|
||||
images = json!(selected);
|
||||
}
|
||||
let use_template_base = input["useTemplateBase"] == true;
|
||||
if use_template_base {
|
||||
if !attachments.is_empty() { return Err("模板底图请求只接受本款实拍作为参考".into()); }
|
||||
images.as_array_mut().ok_or("本款实拍无效")?.retain(|item| item["purpose"] == "product");
|
||||
if images.as_array().is_none_or(Vec::is_empty) {
|
||||
return Err("模板底图请求至少需要一张本款实拍".into());
|
||||
}
|
||||
}
|
||||
creation["brief"]["images"] = images.clone();
|
||||
creation["generation"] = Value::Null; // Never inherit a different colour's legacy anchor.
|
||||
if use_template_base {
|
||||
let target = json!({"templateHash":state["template"]["contentHash"],"component":output["component"],
|
||||
"documentId":output["id"],"variantId":variant_id,"fieldId":field["fieldId"]});
|
||||
let base = self.template_edit_pixels(&dir, &target, &field["frame"])?;
|
||||
let source = format!("pinned-template:{}", field["fieldId"].as_str().ok_or("图位字段缺失")?);
|
||||
attachments.push((json!({"id":source,"purpose":"template-base"}), base));
|
||||
}
|
||||
let (references, mut layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?;
|
||||
let settings = self.settings()?;
|
||||
let model = settings["imageModel"].as_str().filter(|model| !model.is_empty()).ok_or("请先选择生图模型")?;
|
||||
let candidate = if input["workflowOperationId"].is_null() || preparing {
|
||||
Uuid::new_v4().to_string()
|
||||
} else {
|
||||
uuid(&input["workflowOperationId"], "原生图操作")?
|
||||
};
|
||||
if !preparing && candidate_path(&dir, &candidate)?.exists() {
|
||||
let original = read_candidate(&dir, &candidate)?;
|
||||
return Ok(Some(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);
|
||||
if input["detailBatch"] == true { binding["detailBatch"] = json!(true); }
|
||||
if preparing { binding["frozenImageRequest"] = json!(true); }
|
||||
if !batch && !preparing { binding["origin"] = json!("human"); }
|
||||
if !attachment_refs.as_array().is_none_or(Vec::is_empty) { binding["composerHash"] = json!(hash(&attachment_refs.to_string())); }
|
||||
let mut record = json!({"version":2,"id":candidate,"sequence":state["candidates"].as_array().ok_or("候选索引无效")?.len()+1,"binding":binding,"phase":"prepared","modelId":model,"inputHash":input_hash(&dir,&state,&variant_id)?,"prompt":instructions,"instructions":instructions,"parentCandidateId":parent,"references":images,"requestId":null,"createdAt":now()});
|
||||
if binding["origin"] == "human" { record["origin"] = json!("human"); }
|
||||
if let Some(previous) = retry_of { record["retryOf"] = json!(previous); }
|
||||
if !attachment_refs.as_array().is_none_or(Vec::is_empty) { record["composerAttachments"] = attachment_refs; }
|
||||
if let Some(operation) = input["workflowOperationId"].as_str() { record["workflowOperationId"] = json!(operation); }
|
||||
if let Some(previous) = input["reworkOf"].as_str() {
|
||||
let old = read_candidate(&dir, previous)?;
|
||||
if old["binding"]["slotId"] != id || old["binding"]["variantId"] != variant_id {
|
||||
return Err("返工候选不属于当前图位".into());
|
||||
}
|
||||
record["reworkOf"] = json!(previous);
|
||||
record["reworkChange"] = input["reworkChange"].clone();
|
||||
}
|
||||
let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height}));
|
||||
let mut origins = creation["brief"]["images"].as_array().cloned().unwrap_or_default();
|
||||
origins.extend(attachments.iter().map(|(asset,_)| json!({"source":asset["id"],"purpose":asset["purpose"].as_str().unwrap_or("approved-material")})));
|
||||
if use_template_base {
|
||||
layers.rotate_right(1);
|
||||
origins.rotate_right(1);
|
||||
record["templateBase"] = json!(true);
|
||||
}
|
||||
let final_prompt = if !preparing && input["manualImage"] == true {
|
||||
let fact_ctx = build_manual_image_fact_context(&state, &output, &field, &variant_id, instructions, &origins);
|
||||
let (compiled, compiled_by) = self.compile_manual_image_prompt(&fact_ctx);
|
||||
record["rawInstructions"] = json!(instructions);
|
||||
record["compiledPrompt"] = json!(compiled);
|
||||
record["promptCompiledBy"] = json!(compiled_by);
|
||||
record["referenceRoles"] = json!(fact_ctx.reference_roles);
|
||||
compiled
|
||||
} else {
|
||||
instructions.to_owned()
|
||||
};
|
||||
let image_input = json!({"doc":doc,"revision":input["baseRevision"],"model":model,
|
||||
"mode":if parent.is_some(){"refine"}else{"generate"},"text":final_prompt,"references":layers,
|
||||
"slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k,"referenceOrigins":origins,
|
||||
"candidateRecord":record,"outputScope":output["component"]});
|
||||
let draft = self.image_job(Some(Arc::new(references)), &image_input, false, events, ctx)?;
|
||||
if preparing { return Ok(Some(draft)); }
|
||||
// The native action is already confirmed by the operator.
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, &json!({"requestId":draft["requestId"],
|
||||
"expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx, None, &[])?;
|
||||
if receipt["status"] == "failed" { *operation_error = receipt["message"].as_str().map(str::to_owned); }
|
||||
*candidate_result = Some(receipt);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,397 @@
|
||||
use super::super::{Document, Path, PathBuf, R, READ_INTERRUPTED, READ_TIMEOUT, Value, creation, fs, hash, json, load_draft, now, read_json, sync, template_slots, template_workflow, write_json};
|
||||
use super::{MAPPING, bound_product_slot, candidate_needs_recovery, candidate_path, candidate_uses_current_inputs, clear_sample_copy, definition, exists, file_digest, image_output_state, load, product_slot_binding, read_candidate, records, text, uuid, variant};
|
||||
use photocraft_ui_egui::jiansun::production_facts::product_brief::{shared_variant_brief, variant_brief, variant_intake};
|
||||
|
||||
pub(crate) fn binding_is_canvas(binding: &Value) -> bool {
|
||||
binding["schemaVersion"] == 2 && binding["canvasFirst"] == true
|
||||
}
|
||||
pub(crate) fn checked_binding(dir: &Path, binding: &Value, reading_original: bool) -> R<(Value, Value)> {
|
||||
if !binding_is_canvas(binding) {
|
||||
return Err("原生画布任务绑定版本无效".into());
|
||||
}
|
||||
let state = load(dir)?;
|
||||
let id = uuid(&binding["candidateId"], "原候选")?;
|
||||
let record = read_candidate(dir, &id)?;
|
||||
let mismatch = "原候选绑定与当前画布项目不一致";
|
||||
if record["binding"] != *binding
|
||||
|| binding["workspaceId"] != state["id"]
|
||||
|| !state["candidates"].as_array().ok_or("候选索引无效")?.contains(&json!(id))
|
||||
{
|
||||
return Err(mismatch.into());
|
||||
}
|
||||
let variant_id = uuid(&binding["variantId"], "原花色")?;
|
||||
let active_pack = binding["templateHash"] == state["template"]["contentHash"] && binding["structureHash"] == state["structureHash"];
|
||||
if !active_pack {
|
||||
if !reading_original && binding["origin"] != "human" { return Err(mismatch.into()); }
|
||||
let component = bound_product_slot(&state, binding).ok_or(mismatch)?;
|
||||
let pack = &state["productTemplates"][component];
|
||||
let structure = hash(&json!([pack["contentHash"],state["width"]]).to_string());
|
||||
if binding["structureHash"] != structure { return Err(mismatch.into()); }
|
||||
} else {
|
||||
let (output, field) = definition(&state, binding["slotId"].as_str().ok_or("原图片目标缺失")?, &variant_id)?;
|
||||
if binding["outputId"] != output["id"] || binding["fieldId"] != field["fieldId"] { return Err(mismatch.into()); }
|
||||
}
|
||||
Ok((state, record))
|
||||
}
|
||||
pub(crate) fn validate_dispatch(dir: &Path, binding: &Value) -> R<()> {
|
||||
let (_, record) = checked_binding(dir, binding, false)?;
|
||||
if !matches!(record["phase"].as_str(), Some("prepared" | "dispatched"))
|
||||
|| dir.join("image-jobs").join(uuid(&binding["taskId"], "原请求")?).join("task.json").exists()
|
||||
{
|
||||
return Err("此候选已有原任务记录,只能查询原结果;不会重发".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn validate_journal_binding(dir: &Path, task: &Value) -> R<()> {
|
||||
let binding = &task["slotBinding"];
|
||||
let (state, record) = checked_binding(dir, binding, binding["detailBatch"] == true)?;
|
||||
if binding["detailBatch"] == true { image_output_state(state, binding)?; }
|
||||
let id = uuid(&record["id"], "候选")?;
|
||||
let saved = read_json(&dir.join("image-jobs").join(&id).join("task.json"))?;
|
||||
if task["id"] != id
|
||||
|| saved["id"] != id
|
||||
|| saved["slotBinding"] != task["slotBinding"]
|
||||
|| !matches!(record["phase"].as_str(), Some("prepared" | "dispatched"))
|
||||
|| !matches!(task["phase"].as_str(), Some("prepared" | "dispatched"))
|
||||
|| !matches!(saved["phase"].as_str(), Some("prepared" | "dispatched"))
|
||||
|| !task["requestId"].is_null()
|
||||
|| !saved["requestId"].is_null()
|
||||
|| !task["upstreamTaskId"].is_null()
|
||||
|| !saved["upstreamTaskId"].is_null()
|
||||
|| record["modelId"] != task["modelId"] && record["modelId"] != task["modelKey"]
|
||||
|| dir.join("image-jobs").join(&id).join("response.json").exists()
|
||||
|| dir.join("image-jobs").join(id).join("generated.png").exists()
|
||||
{
|
||||
return Err("原候选已返回结果或身份变化,未再次派发".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn validate_image_context(dir: &Path, except: Option<&Value>) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
check_image_context(dir, except, except.filter(|binding| binding["detailBatch"] == true || binding["origin"] == "human"))
|
||||
}
|
||||
pub(crate) fn check_image_context(dir: &Path, except: Option<&Value>, batch: Option<&Value>) -> R<()> {
|
||||
let state = load(dir)?;
|
||||
let creation = creation::load(dir)?;
|
||||
let live = &creation["brief"];
|
||||
let saved = &state["brief"];
|
||||
let current_variant = batch.and_then(|binding| binding["variantId"].as_str());
|
||||
if live != saved && !current_variant.is_some_and(|id| state["productTemplates"].is_object()
|
||||
&& shared_variant_brief(live) == shared_variant_brief(saved)
|
||||
&& variant_brief(live, id) == variant_brief(saved, id)
|
||||
&& creation::detail_barcode(live) == creation::detail_barcode(saved)
|
||||
&& variant_intake(live, id, "detail") == variant_intake(saved, id, "detail"))
|
||||
{
|
||||
return Err("商品或花色资料有改动,请确认当前资料。原请求已保留。".into());
|
||||
}
|
||||
if let Some(binding) = except {
|
||||
let (bound, record) = checked_binding(dir, binding, binding["detailBatch"] == true)?;
|
||||
let bound = if binding["detailBatch"] == true || binding["origin"] == "human" { image_output_state(bound, binding)? } else { bound };
|
||||
if !candidate_uses_current_inputs(dir, &bound, &record, binding["variantId"].as_str().ok_or("花色身份无效")?)? {
|
||||
return Err("产品、花色或规则已变化,未发送旧候选请求".into());
|
||||
}
|
||||
if binding["composerHash"].is_string() {
|
||||
let attachments = &record["composerAttachments"];
|
||||
if !attachments.is_array() || binding["composerHash"] != hash(&attachments.to_string()) {
|
||||
return Err("原请求附件快照已改变,未发送请求".into());
|
||||
}
|
||||
creation::composer_attachments::resolve(dir, attachments)?;
|
||||
} else if record.get("composerAttachments").is_some() {
|
||||
return Err("原请求附件绑定缺失,未发送请求".into());
|
||||
}
|
||||
}
|
||||
if pending(dir, &state, &creation, except, batch)? {
|
||||
return Err("存在原请求待核查,未发送新候选请求".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn pending(dir: &Path, state: &Value, creation: &Value, except: Option<&Value>, batch: Option<&Value>) -> R<bool> {
|
||||
let legacy = if dir.join("template-slots.json").exists() { template_slots::load(dir)? } else { json!({"slots":{}}) };
|
||||
if template_workflow::other_local_pending(dir, creation, &legacy, except.or(batch))? {
|
||||
return Ok(true);
|
||||
}
|
||||
local_pending(dir, state, except, batch)
|
||||
}
|
||||
|
||||
pub(crate) fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Option<&Value>) -> R<bool> {
|
||||
let manual = except.or(batch).filter(|binding| binding["origin"] == "human");
|
||||
if manual.is_none() && !creation::pending_text_tasks(dir)?.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
for record in records(dir, state)? {
|
||||
if manual.is_some_and(|target| record["binding"]["slotId"] != target["slotId"]
|
||||
|| record["binding"]["variantId"] != target["variantId"])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched")))
|
||||
&& !batch.is_some_and(|binding| {
|
||||
let sibling = &record["binding"];
|
||||
sibling["detailBatch"] == true && (sibling["slotId"] != binding["slotId"]
|
||||
|| sibling["frozenImageRequest"] == true && binding["frozenImageRequest"] == true
|
||||
&& sibling["taskId"] != binding["taskId"])
|
||||
&& (sibling["variantId"] == binding["variantId"] && sibling["templateHash"] == binding["templateHash"]
|
||||
|| product_slot_binding(state, binding) && product_slot_binding(state, sibling))
|
||||
}) && candidate_needs_recovery(dir, &record)?
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
pub(crate) fn transient_image_preflight(error: &str) -> bool {
|
||||
let Some(cause) = error.strip_prefix("本次生图未提交。") else { return false };
|
||||
let cause = cause.strip_prefix("模型权限检查失败:").unwrap_or(cause);
|
||||
matches!(cause, "服务连接中断" | "98k模型目录读取失败:服务连接中断" | "98k公开模型目录暂不可用")
|
||||
|| cause.strip_prefix("98k模型目录读取失败:").is_some_and(|error|
|
||||
matches!(error, super::READ_TIMEOUT | super::READ_INTERRUPTED))
|
||||
|| cause.starts_with("98k暂时无法连接(")
|
||||
|| [408, 429, 502, 503, 504].iter().any(|status| {
|
||||
cause == format!("98k公开模型目录暂不可用(HTTP {status})")
|
||||
|| cause == format!("个人Key校验失败(HTTP {status})")
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
|
||||
let _guard = sync::context_guard();
|
||||
let (_, record) = checked_binding(dir, &journal["slotBinding"], true)?;
|
||||
let mut projected = project_candidate(dir, &record, journal)?;
|
||||
if projected != record {
|
||||
projected["updatedAt"] = json!(now());
|
||||
write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &projected)?;
|
||||
}
|
||||
Ok(projected)
|
||||
}
|
||||
|
||||
pub(crate) fn project_candidate(dir: &Path, record: &Value, journal: &Value) -> R<Value> {
|
||||
if journal["id"] != record["id"] || record["requestId"].is_string() && journal["requestId"].is_string() && record["requestId"] != journal["requestId"] {
|
||||
return Err("原候选请求号不匹配,未修改记录".into());
|
||||
}
|
||||
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
|
||||
return Ok(record.clone());
|
||||
}
|
||||
let mut record = record.clone();
|
||||
let phase = match journal["phase"].as_str() {
|
||||
Some("prepared") if journal["notDispatched"] == true => "failed",
|
||||
Some("prepared" | "dispatched") => "dispatched",
|
||||
Some("running") => "running",
|
||||
Some("unknown") => "unknown",
|
||||
Some("failed") => "failed",
|
||||
Some("expired") => "expired",
|
||||
Some("complete" | "applied") => "complete",
|
||||
_ => return Err("原候选任务状态无效".into()),
|
||||
};
|
||||
if phase == "complete" {
|
||||
let artifact = template_slots::artifact(dir, record["id"].as_str().ok_or("原候选身份缺失")?, journal)?;
|
||||
record["artifact"] = artifact;
|
||||
}
|
||||
if let Some(submitted) = journal["submittedPromptHash"].as_str() {
|
||||
let prompt = journal["prompt"].as_str().ok_or("生图请求文本缺失")?;
|
||||
let saved = hash(record["prompt"].as_str().ok_or("候选提示词缺失")?);
|
||||
let headings = ["主体", "主体配饰", "镜头与构图", "场景", "风格"];
|
||||
let mut sections = Vec::new();
|
||||
for line in prompt.lines().map(str::trim) {
|
||||
if let Some(heading) = line.strip_suffix([':', ':']).filter(|heading| headings.contains(heading)) {
|
||||
sections.push(heading);
|
||||
}
|
||||
}
|
||||
use std::io::Read as _;
|
||||
let requested = &journal["slotFrame"];
|
||||
let actual = if phase == "complete" {
|
||||
let path = record["artifact"]["path"].as_str().ok_or("候选图片路径缺失")?;
|
||||
let mut header = [0; 24];
|
||||
fs::File::open(dir.join(path)).and_then(|mut file| file.read_exact(&mut header))
|
||||
.map_err(|_| "候选图片像素信息不可读取")?;
|
||||
Some(creation::png_size(&header)?)
|
||||
} else { None };
|
||||
let expected = requested["width"].as_f64().zip(requested["height"].as_f64());
|
||||
record["generationEvidence"] = json!({
|
||||
"modelId":journal["modelId"],"parameters":journal["protocol"]["parameters"],"requested2k":journal["prefer2k"],
|
||||
"actualPixels":actual.map(|(width,height)| json!({"width":width,"height":height})),
|
||||
"requestedImagePixels":journal["requestedImagePixels"],
|
||||
"matchesRequestedImagePixels":actual.filter(|_| journal["requestedImagePixels"].is_array())
|
||||
.map(|(width,height)| journal["requestedImagePixels"] == json!([width,height])),
|
||||
"actualRatio":actual.map(|(width,height)| format!("{width}:{height}")),
|
||||
"requestedRatio":expected.map(|(width,height)| format!("{width}:{height}")),
|
||||
"ratioMatches":actual.zip(expected).map(|((w,h),(ew,eh))| (w as f64 * eh - h as f64 * ew).abs() < ew.max(eh)),
|
||||
"promptSections":sections,"allPromptSectionsPresent":sections == headings,
|
||||
"savedPromptHash":saved,"submittedPromptHash":submitted,"promptHashMatches":saved == submitted
|
||||
});
|
||||
}
|
||||
record["phase"] = json!(phase);
|
||||
if journal["notDispatched"] == true {
|
||||
record["notDispatched"] = json!(true);
|
||||
}
|
||||
if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); }
|
||||
let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true
|
||||
&& journal["requestId"].is_null() && record["requestId"].is_null()
|
||||
&& journal["message"].as_str().is_some_and(transient_image_preflight);
|
||||
if phase == "failed" && (preflight_retry || journal["failureEvidence"].is_object() && journal["retryableFailure"] == true) {
|
||||
record["retryableFailure"] = json!(true);
|
||||
record["retryAfterSeconds"] = journal["retryAfterSeconds"].clone();
|
||||
}
|
||||
if journal["requestId"].is_string() || record["requestId"].is_null() {
|
||||
record["requestId"] = journal["requestId"].clone();
|
||||
}
|
||||
if journal["message"].is_string() {
|
||||
record["message"] = journal["message"].clone();
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
pub(crate) fn mapping_key(variant: &str, component: &str, document: Option<&str>) -> String {
|
||||
hash(&json!([variant, component, document]).to_string())
|
||||
}
|
||||
pub(crate) fn original_preview_path(dir: &Path, key: &str) -> PathBuf {
|
||||
dir.join("template-outputs").join(format!("canvas-{key}-original-preview.json"))
|
||||
}
|
||||
|
||||
pub(crate) fn original_preview_for_doc(dir: &Path, doc: &Document) -> Option<Value> {
|
||||
let meta = mapping(doc)?;
|
||||
if meta["component"] != "detail" { return None; }
|
||||
let key = mapping_key(meta["variantId"].as_str()?, "detail", meta["documentId"].as_str());
|
||||
let path = original_preview_path(dir, &key);
|
||||
path.is_file().then(|| read_json(&path).ok()).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn mapping(doc: &Document) -> Option<Value> {
|
||||
doc.metadata
|
||||
.text
|
||||
.iter()
|
||||
.find(|(key, _)| key == MAPPING)
|
||||
.and_then(|(_, value)| serde_json::from_str::<Value>(value).ok())
|
||||
.filter(|v| v["canvasFirst"] == true)
|
||||
}
|
||||
pub(crate) fn opened_document_scope(meta: &Value) -> Value {
|
||||
json!({"outputId":meta["component"],"component":meta["component"],"variantId":meta["variantId"],
|
||||
"workspaceId":meta["workspaceId"],"templateHash":meta["templateHash"],"mappingDocumentId":meta["outputId"],
|
||||
"templateId":meta["templateId"],"templateVersion":meta["templateVersion"]})
|
||||
}
|
||||
|
||||
pub(crate) fn document_mapping_key(meta: &Value) -> R<String> {
|
||||
let variant = meta["variantId"].as_str().ok_or("编辑稿花色缺失")?;
|
||||
let component = meta["component"].as_str().ok_or("编辑稿输出类型缺失")?;
|
||||
Ok(mapping_key(variant, component, meta["outputId"].as_str()))
|
||||
}
|
||||
|
||||
pub(crate) fn mapping_matches_active(meta: &Value, state: &Value) -> R<bool> {
|
||||
let key = document_mapping_key(meta)?;
|
||||
Ok(meta["workspaceId"] == state["id"]
|
||||
&& meta["component"] == state["activeOutput"]
|
||||
&& meta["variantId"] == state["activeVariantId"]
|
||||
&& meta["templateHash"] == state["template"]["contentHash"]
|
||||
&& state["activeMapping"].as_str().is_none_or(|active| active == key))
|
||||
}
|
||||
|
||||
pub(crate) fn document_matches_active(dir: &Path, doc: &Document) -> R<bool> {
|
||||
if !exists(dir) { return Ok(true); }
|
||||
let state = load(dir)?;
|
||||
match mapping(doc) {
|
||||
Some(meta) => mapping_matches_active(&meta, &state),
|
||||
None => Ok(!state["activeMapping"].is_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum OpenedDraft {
|
||||
Canonical,
|
||||
ScopedCanonical,
|
||||
ActiveEdit(String),
|
||||
}
|
||||
|
||||
pub(crate) fn verify_opened_edit(dir: &Path, doc: &Document, expected: &str) -> R<()> {
|
||||
let meta = mapping(doc).ok_or("编辑稿输出映射缺失")?;
|
||||
let key = document_mapping_key(&meta)?;
|
||||
let path = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
if !mapping_matches_active(&meta, &load(dir)?)? || !file_digest(&path).is_ok_and(|sha| sha == expected) {
|
||||
return Err("打开期间当前输出已变化,请重新打开".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_draft_for_workspace(dir: &Path) -> R<(Document, OpenedDraft)> {
|
||||
let canonical = load_draft(dir, &dir.join("canvas.pcraft")).map_err(|_| "原生草稿未能恢复;文件已保留")?;
|
||||
if !exists(dir) { return Ok((canonical, OpenedDraft::Canonical)); }
|
||||
let state = load(dir)?;
|
||||
let actual = mapping(&canonical);
|
||||
if let Some(meta) = &actual && mapping_matches_active(meta, &state)? {
|
||||
return Ok((canonical, OpenedDraft::Canonical));
|
||||
}
|
||||
// Mapping keys are SHA-256 digests. Never use a project-supplied path.
|
||||
if let Some(key) = state["activeMapping"].as_str().filter(|key| key.len() == 64 && key.bytes().all(|b| b.is_ascii_hexdigit())) {
|
||||
let path = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
if path.is_file() && let Ok(edited) = load_draft(dir, &path)
|
||||
&& let Some(meta) = mapping(&edited) && mapping_matches_active(&meta, &state)?
|
||||
{
|
||||
let digest = file_digest(&path).map_err(|_| "当前输出编辑稿无法核对")?;
|
||||
return Ok((edited, OpenedDraft::ActiveEdit(digest)));
|
||||
}
|
||||
}
|
||||
Ok((canonical, if actual.is_some() { OpenedDraft::ScopedCanonical } else { OpenedDraft::Canonical }))
|
||||
}
|
||||
|
||||
pub(crate) fn page_fields(meta: &Value) -> impl Iterator<Item = (&Value, &[Value])> {
|
||||
meta["outputs"].as_array().into_iter().flatten().filter_map(|page| {
|
||||
let fields = page["mapping"]["fields"].as_array()?.as_slice();
|
||||
(!fields.is_empty()).then_some((&page["documentId"], fields))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn page_has_layers(doc: &Document, fields: &[Value]) -> bool {
|
||||
fields.iter().any(|field| field["nativeLayerId"].as_u64().is_some_and(|id| doc.layer(photocraft_doc::LayerId(id)).is_some()))
|
||||
}
|
||||
|
||||
pub(crate) fn missing_ending_pages(doc: &Document) -> Vec<String> {
|
||||
let Some(meta) = mapping(doc).filter(|meta| meta["component"] == "detail" && meta["enterprise"].is_object()) else { return Vec::new() };
|
||||
let mut missing = Vec::new();
|
||||
for (page, fields) in page_fields(&meta) {
|
||||
if page_has_layers(doc, fields) {
|
||||
missing.clear();
|
||||
} else if let Some(page) = page.as_str() {
|
||||
missing.push(page.to_owned());
|
||||
}
|
||||
}
|
||||
missing
|
||||
}
|
||||
|
||||
/// Amend an incomplete copy using its fixed original. Keep the retained
|
||||
/// native layers and their IDs, including edited pixels and text.
|
||||
pub(crate) fn merge_missing_ending(doc: &mut Document, mut original: Document, meta: &Value) -> R<()> {
|
||||
let original_meta = mapping(&original).ok_or("固定原稿缺少图位映射")?;
|
||||
if doc.size != original.size
|
||||
|| doc.depth != original.depth
|
||||
|| doc.mode != original.mode
|
||||
|| meta["templateHash"] != original_meta["templateHash"]
|
||||
|| meta["variantId"] != original_meta["variantId"]
|
||||
|| doc.layers.is_empty() || doc.layers.len() >= original.layers.len()
|
||||
|| !doc.layers.iter().zip(&original.layers).all(|(saved, source)| {
|
||||
saved.psd_id == source.psd_id && (saved.psd_id.is_some() || saved.name == source.name)
|
||||
})
|
||||
{
|
||||
return Err("固定原稿与现有画布结构不同,原编辑已保留,未自动补回图层".into());
|
||||
}
|
||||
let missing = missing_ending_pages(doc);
|
||||
let restored: Vec<_> = page_fields(meta).filter(|(page, _)| page.as_str().is_some_and(|page| missing.iter().any(|name| name == page)))
|
||||
.flat_map(|(_, fields)| fields).collect();
|
||||
let first_missing_root = doc.layers.len();
|
||||
for saved_field in restored {
|
||||
let fixed = page_fields(&original_meta).flat_map(|(_, fields)| fields)
|
||||
.find(|field| field["fieldId"] == saved_field["fieldId"] && field["psdLayerId"] == saved_field["psdLayerId"])
|
||||
.ok_or("固定原稿缺少对应图位,未自动补回图层")?;
|
||||
let id = fixed["nativeLayerId"].as_u64().ok_or("固定原稿图位身份缺失")?;
|
||||
let old_id = saved_field["nativeLayerId"].as_u64().ok_or("保存的图位身份缺失")?;
|
||||
let layer_id = photocraft_doc::LayerId(id);
|
||||
if doc.layer(photocraft_doc::LayerId(old_id)).is_some()
|
||||
|| original.walk().into_iter().find(|(_, _, layer)| layer.id == layer_id)
|
||||
.is_none_or(|(path, _, _)| path[0] < first_missing_root)
|
||||
{
|
||||
return Err("图位映射与缺失区域不一致,未自动补回图层".into());
|
||||
}
|
||||
original.layer_mut(layer_id).ok_or("固定原稿图层缺失")?.id = photocraft_doc::LayerId(old_id);
|
||||
}
|
||||
if meta["omitSampleCopy"] == true {
|
||||
clear_sample_copy(&mut original.layers[first_missing_root..]);
|
||||
}
|
||||
doc.layers.extend(original.layers.drain(first_missing_root..));
|
||||
debug_assert!(missing_ending_pages(doc).is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -0,0 +1,850 @@
|
||||
use super::super::{Digest, Backend, Event, Path, R, Sha256, Uuid, Value, creation, delivery, fs, hash, images, json, mpsc, now, original_project_present, production_profile, read_json, sync, template_slots, write_json};
|
||||
use super::{FILE, binding_is_canvas, candidate_available, candidate_matches_slot, candidate_path, candidate_pixels, candidate_reviews, candidate_uses_current_inputs, checked_binding, completed_candidate, definition, exists, generation_references, image_output_component, input_hash, load, lock_candidate_dispatch, lock_slot_dispatch, mapped_slot, output_uses_variant, pending, product_crop_mode, production_output_state, read_candidate, read_production_settings, read_records, reconcile_candidate, records, references, reserve_candidate, slot_frame, slot_id, snapshot, uuid, variant};
|
||||
|
||||
pub(crate) fn pending_summary(dir: &Path) -> R<Vec<Value>> {
|
||||
if !exists(dir) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let state = load(dir)?;
|
||||
let mut pending = Vec::new();
|
||||
for record in records(dir, &state)? {
|
||||
if candidate_needs_recovery(dir, &record)? {
|
||||
pending.push(json!({"id":record["id"],"phase":record["phase"],"kind":"canvas-candidate"}));
|
||||
}
|
||||
}
|
||||
Ok(pending)
|
||||
}
|
||||
|
||||
pub(crate) fn bound_product_slot<'a>(state: &'a Value, binding: &Value) -> Option<&'a str> {
|
||||
if binding["workspaceId"] != state["id"] { return None; }
|
||||
let variant_id = binding["variantId"].as_str()?;
|
||||
let field_id = binding["fieldId"].as_str()?;
|
||||
variant(state, variant_id).ok()?;
|
||||
let component = image_output_component(state, binding)?;
|
||||
let pack = &state["productTemplates"][component];
|
||||
let matches = binding["slotId"] == slot_id(&pack["contentHash"], variant_id, field_id)
|
||||
&& pack["outputs"].as_array().into_iter().flatten().any(|output| output["component"] == component
|
||||
&& output["id"] == binding["outputId"] && output["slots"].as_array().into_iter().flatten()
|
||||
.any(|field| field["fieldId"] == field_id && field["kind"] == "image"));
|
||||
matches.then_some(component)
|
||||
}
|
||||
pub(crate) fn product_slot_binding(state: &Value, binding: &Value) -> bool {
|
||||
binding["detailBatch"] == true && bound_product_slot(state, binding).is_some()
|
||||
}
|
||||
pub(crate) fn publish_prepared(events: &mpsc::Sender<Event>, snapshot: Value) -> R<()> {
|
||||
events.send(Event::Json("slot-progress".into(), Ok(snapshot))).map_err(|_| "工作台已关闭,候选预留保留,未发送新图片请求".into())
|
||||
}
|
||||
pub(crate) fn new_binding(state: &Value, output: &Value, field: &Value, slot: &str, variant: &str, id: &str, prompt: &str) -> Value {
|
||||
json!({"schemaVersion":2,"canvasFirst":true,"workspaceId":state["id"],"templateId":state["template"]["id"],
|
||||
"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],
|
||||
"structureHash":state["structureHash"],"slotId":slot,"fieldId":field["fieldId"],"outputId":output["id"],"component":output["component"],
|
||||
"variantId":variant,"candidateId":id,"taskId":id,"promptHash":hash(prompt)})
|
||||
}
|
||||
|
||||
pub(crate) fn crop_frame_ratio(frame: &Value) -> Option<f64> {
|
||||
frame["width"].as_f64().zip(frame["height"].as_f64())
|
||||
.map(|(width, height)| width / height).filter(|ratio| ratio.is_finite() && *ratio > 0.0)
|
||||
}
|
||||
|
||||
pub(crate) fn inside_crop_in_frame(region: [u32; 4], frame: &Value) -> [u32; 4] {
|
||||
let Some(ratio) = crop_frame_ratio(frame) else { return region };
|
||||
let [left, top, right, bottom] = region;
|
||||
let (width, height) = (right - left, bottom - top);
|
||||
let fitted_width = ((height as f64 * ratio).round() as u32).clamp(1, width);
|
||||
let fitted_height = ((width as f64 / ratio).round() as u32).clamp(1, height);
|
||||
let x = left + (width - fitted_width) / 2;
|
||||
let y = top + (height - fitted_height) / 2;
|
||||
[x, y, x + fitted_width, y + fitted_height]
|
||||
}
|
||||
|
||||
pub(crate) fn preserve_crop_in_frame(
|
||||
region: [u32; 4],
|
||||
(source_width, source_height): (u32, u32),
|
||||
frame: &Value,
|
||||
) -> [u32; 4] {
|
||||
let Some(ratio) = crop_frame_ratio(frame) else { return region };
|
||||
let [left, top, right, bottom] = region;
|
||||
let (width, height) = (right - left, bottom - top);
|
||||
let mut fitted_width = width.max((height as f64 * ratio).round() as u32);
|
||||
let mut fitted_height = height.max((width as f64 / ratio).round() as u32);
|
||||
if fitted_width > source_width {
|
||||
fitted_width = source_width;
|
||||
fitted_height = ((source_width as f64 / ratio).round() as u32).clamp(1, source_height);
|
||||
} else if fitted_height > source_height {
|
||||
fitted_height = source_height;
|
||||
fitted_width = ((source_height as f64 * ratio).round() as u32).clamp(1, source_width);
|
||||
}
|
||||
let centered = |start: u32, extent: u32, fitted: u32, limit: u32| {
|
||||
if fitted >= extent {
|
||||
start.saturating_sub((fitted - extent) / 2).min(limit - fitted)
|
||||
} else {
|
||||
start + (extent - fitted) / 2
|
||||
}
|
||||
};
|
||||
let left = centered(left, width, fitted_width, source_width);
|
||||
let top = centered(top, height, fitted_height, source_height);
|
||||
[left, top, left + fitted_width, top + fitted_height]
|
||||
}
|
||||
|
||||
pub(crate) fn local_product_photo(dir: &Path, image: &Value) -> R<Vec<u8>> {
|
||||
let source = image["source"].as_str().and_then(|value| value.strip_prefix("local:")).ok_or("当前产品原图不在本机项目")?;
|
||||
fs::read(dir.join("creation-assets").join(format!("{source}.png"))).map_err(|_| "产品原图无法读取".into())
|
||||
}
|
||||
|
||||
pub(crate) fn product_crop_pixels(region: &Value, (w, h): (u32, u32), frame: &Value, inside: bool) -> R<[u32; 4]> {
|
||||
let [left, top, right, bottom]: [u32; 4] = serde_json::from_value(region.clone()).map_err(|_| "原图局部取景无效")?;
|
||||
if right > 1000 || bottom > 1000 || left >= right || top >= bottom {
|
||||
return Err("原图局部取景超出边界".into());
|
||||
}
|
||||
let region = [left*w/1000, top*h/1000, (right*w).div_ceil(1000), (bottom*h).div_ceil(1000)];
|
||||
Ok(if inside { inside_crop_in_frame(region, frame) } else { preserve_crop_in_frame(region, (w, h), frame) })
|
||||
}
|
||||
|
||||
pub(crate) fn outline_crop(mut source: egui::ColorImage, original: (u32, u32), crop: [u32; 4]) -> egui::ColorImage {
|
||||
let (width, height) = (source.width(), source.height());
|
||||
let [x0, y0, x1, y1] = crop.map(|value| value as usize);
|
||||
let left = x0 * width / original.0 as usize;
|
||||
let top = y0 * height / original.1 as usize;
|
||||
let right = (x1 * width).div_ceil(original.0 as usize);
|
||||
let bottom = (y1 * height).div_ceil(original.1 as usize);
|
||||
let thickness = width.max(height).div_ceil(768) * 2;
|
||||
let x0 = left.saturating_sub(thickness);
|
||||
let y0 = top.saturating_sub(thickness);
|
||||
let x1 = (right + thickness).min(width);
|
||||
let y1 = (bottom + thickness).min(height);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
if x < left || x >= right || y < top || y >= bottom {
|
||||
source[(x, y)] = egui::Color32::from_rgb(0, 111, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
source
|
||||
}
|
||||
|
||||
pub(crate) fn crop_product_image(image: &photocraft_codecs::Image, [x, y, end_x, end_y]: [u32; 4]) -> R<photocraft_codecs::Image> {
|
||||
let w = image.width();
|
||||
let pixel = image.data().len() / image.pixel_count();
|
||||
let rows = image.data().chunks_exact(w as usize * pixel).skip(y as usize).take((end_y-y) as usize);
|
||||
let data = rows.flat_map(|row| row[x as usize*pixel..end_x as usize*pixel].iter().copied()).collect();
|
||||
let mut crop = photocraft_codecs::Image::from_raw(end_x-x, end_y-y, image.layout(), image.sample_type(), data).map_err(|_| "原图局部读取失败")?;
|
||||
crop.icc.clone_from(&image.icc);
|
||||
crop.cicp = image.cicp;
|
||||
Ok(crop)
|
||||
}
|
||||
|
||||
pub(crate) fn crop_product_photo(bytes: &[u8], region: &Value, frame: &Value, inside: bool) -> R<Vec<u8>> {
|
||||
let image = photocraft_codecs::decode(bytes).map_err(|_| "产品原图无法解码")?;
|
||||
let bounds = product_crop_pixels(region, image.dimensions(), frame, inside)?;
|
||||
let crop = crop_product_image(&image, bounds)?;
|
||||
photocraft_codecs::encode(&crop, photocraft_codecs::Format::Png, &Default::default()).map_err(|_| "局部图无法编码".into())
|
||||
}
|
||||
|
||||
pub(crate) fn original_product_candidate(dir: &Path, state: Value, binding: Value, products: &Value, index: usize, frame: &Value, project_scoped: bool) -> R<Value> {
|
||||
let image = products.as_array().into_iter().flatten().filter(|row| row["purpose"] == "product")
|
||||
.nth(index).ok_or("当前花色没有所选产品原图。用 read_slot_images 查看当前图位的 productReferences,从清单中选择 reference(如 P01)。")?;
|
||||
let mut bytes = local_product_photo(dir, image)?;
|
||||
if let Some(region) = binding.get("referenceCrop") {
|
||||
let inside = matches!(binding["referenceCropMode"].as_str(), Some("inside" | "cover"));
|
||||
bytes = crop_product_photo(&bytes, region, frame, inside)?;
|
||||
}
|
||||
stage_local_image(dir, state, binding, "product-reference", json!([image]), &bytes, project_scoped)
|
||||
}
|
||||
|
||||
pub(crate) fn product_reference_index(value: &Value) -> R<usize> {
|
||||
if value.is_null() { return Ok(0); }
|
||||
value.as_u64().filter(|&index| index < 8).map(|index| index as usize)
|
||||
.ok_or_else(|| "所选商品原图编号无效".into())
|
||||
}
|
||||
|
||||
pub(crate) fn import_local_candidate(dir: &Path, state: Value, output: &Value, field: &Value, slot: &str, variant: &str, input: &Value, project_scoped: bool) -> R<Value> {
|
||||
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())
|
||||
.ok_or("请选择本机图片文件")?;
|
||||
let file = fs::File::open(path).map_err(|_| "本机图片无法读取")?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_IMPORT + 1).read_to_end(&mut bytes).map_err(|_| "本机图片无法读取")?;
|
||||
if bytes.len() as u64 > MAX_IMPORT { return Err("本机图片超过 64 MB".into()); }
|
||||
let image = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions {
|
||||
limits: photocraft_codecs::Limits { max_width: 8192, max_height: 8192, max_pixels: 24_000_000, max_alloc: 192 * 1024 * 1024 },
|
||||
..Default::default()
|
||||
}).map_err(|_| "本机图片无法解码或尺寸超过限制")?;
|
||||
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default())
|
||||
.map_err(|_| "本机图片无法保存为候选")?;
|
||||
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, project_scoped)
|
||||
}
|
||||
|
||||
pub(crate) fn stage_local_image(dir: &Path, state: Value, binding: Value, source: &str, references: Value, bytes: &[u8], project_scoped: bool) -> R<Value> {
|
||||
if bytes.len() > 20 * 1024 * 1024 {
|
||||
return Err("图片转为候选格式后超过 20 MB".into());
|
||||
}
|
||||
let id = uuid(&binding["candidateId"], "候选")?;
|
||||
let job = dir.join("image-jobs").join(&id);
|
||||
let journal = json!({"version":1,"id":id,"phase":"complete","slotBinding":binding,"requestId":null,
|
||||
"sourceType":source,"sha256":format!("{:x}", Sha256::digest(bytes))});
|
||||
// Stage a complete local artifact before publishing its candidate. This
|
||||
// branch never creates an upstream request or an unknown task.
|
||||
write_json(&job.join("task.json"), &journal)?;
|
||||
photocraft_format::atomic_write(&job.join("generated.png"), bytes).map_err(|_| "本机图片无法保存为候选")?;
|
||||
let artifact = template_slots::artifact(dir, &id, &journal)?;
|
||||
let variant_id = binding["variantId"].as_str().ok_or("花色身份无效")?;
|
||||
let sequence = state["candidates"].as_array().ok_or("候选索引无效")?.len() + 1;
|
||||
let label = if source == "local-import" { "本机导入" } else { "产品原图" };
|
||||
let mut record = json!({"version":2,"id":id,"sequence":sequence,"binding":binding,"phase":"complete",
|
||||
"sourceType":source,"modelId":null,"inputHash":input_hash(dir,&state,variant_id)?,
|
||||
"prompt":label,"instructions":label,"references":references,"requestId":null,"artifact":artifact,"createdAt":now()});
|
||||
if binding["origin"] == "human" { record["origin"] = json!("human"); }
|
||||
reserve_candidate(dir, state, &record, project_scoped)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
pub(crate) fn material_task_id(record: &Value) -> &Value {
|
||||
record.get("materialTaskId").filter(|id| id.is_string())
|
||||
.or_else(|| record["reusedFrom"].get("candidateId").filter(|id| id.is_string()))
|
||||
.unwrap_or(&record["id"])
|
||||
}
|
||||
pub(crate) fn production_image_presentation(doc: u64, binding: &Value, account: &Value, origin: &str) -> Value {
|
||||
json!({"productionRun":binding["run"],"taskId":binding["request"]["requestId"],
|
||||
"doc":doc,"accountId":account,"origin":origin,
|
||||
"slotId":binding["request"]["slotId"],"slotLabel":binding["slotLabel"],"imageFrame":binding["imageFrame"],
|
||||
"outputId":binding["scope"]["outputId"],"variantId":binding["scope"]["variantId"],
|
||||
"workerNumber":binding["request"]["workerNumber"]})
|
||||
}
|
||||
|
||||
pub(crate) fn emit_production_image_receipt(events: &mpsc::Sender<Event>, mut presentation: Value, receipt: &Value, cancelled: bool) {
|
||||
presentation["phase"] = if cancelled { json!("cancelled") } else { receipt["status"].clone() };
|
||||
presentation["isSlotCandidate"] = json!(true);
|
||||
let _ = events.send(Event::Json("image".into(), Ok(presentation)));
|
||||
}
|
||||
|
||||
pub(crate) fn production_image_target(state: Value, scope: &Value) -> R<Value> {
|
||||
let output = scope["outputId"].as_str().ok_or("成品编号缺失")?;
|
||||
let variant = scope["variantId"].as_str().ok_or("花色编号缺失")?;
|
||||
let state = production_output_state(state, output, variant)?;
|
||||
if state["id"] != scope["id"] || state["template"]["contentHash"] != scope["templateHash"] {
|
||||
return Err("生图请求的项目或模板已变化".into());
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_receipt(record: &Value) -> Value {
|
||||
let mut receipt = json!({"id":record["id"],"slotId":record["binding"]["slotId"],"variantId":record["binding"]["variantId"],
|
||||
"status":record["phase"],"message":record["message"]});
|
||||
if record["retirement"].is_object() {
|
||||
receipt["status"] = json!("retired");
|
||||
receipt["message"] = record["retirement"]["reason"].clone();
|
||||
}
|
||||
if record["origin"] == "human" { receipt["origin"] = json!("human"); }
|
||||
if record["phase"] == "complete" { receipt["materialTaskId"] = material_task_id(record).clone(); }
|
||||
if record["generationEvidence"].is_object() { receipt["generationEvidence"] = record["generationEvidence"].clone(); }
|
||||
if matches!(record["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
|
||||
receipt["dispatchState"] = json!("outcome_unknown");
|
||||
receipt["originalRequestId"] = record.get("requestId").filter(|id| id.is_string())
|
||||
.unwrap_or(&record["id"]).clone();
|
||||
} else if record["notDispatched"] == true {
|
||||
receipt["dispatchState"] = json!("not_dispatched");
|
||||
}
|
||||
if record["phase"] == "expired" {
|
||||
receipt["requestId"] = record["requestId"].clone();
|
||||
receipt["retryable"] = json!(false);
|
||||
receipt["resultExpiry"] = record["resultExpiry"].clone();
|
||||
}
|
||||
if record["retryableFailure"] == true {
|
||||
receipt["retryableFailure"] = json!(true);
|
||||
receipt["retryAfterSeconds"] = record["retryAfterSeconds"].clone();
|
||||
}
|
||||
if matches!(record["sourceType"].as_str(), Some("product-reference" | "archived-candidate" | "local-import")) {
|
||||
receipt["sourceType"] = record["sourceType"].clone();
|
||||
}
|
||||
if record["sourceType"] == "archived-candidate" {
|
||||
receipt["reusedFrom"] = record["reusedFrom"].clone();
|
||||
receipt["sourceRequestId"] = record["sourceRequestId"].clone();
|
||||
}
|
||||
if let Some(transform) = record["canvasTransform"].as_object() {
|
||||
receipt["canvasTransform"] = record["canvasTransform"].clone();
|
||||
for (key, value) in transform {
|
||||
receipt[key] = value.clone();
|
||||
}
|
||||
}
|
||||
receipt
|
||||
}
|
||||
// Every alias has its own renderable pixels. Keep a canonical source archive
|
||||
// while another live candidate in this account still cites that material.
|
||||
pub(crate) fn shared_candidate_material(dir: &Path, state: &Value, candidate: &str) -> R<bool> {
|
||||
let projects = dir.parent().ok_or("当前项目目录无效")?;
|
||||
for entry in fs::read_dir(projects).map_err(|error| error.to_string())? {
|
||||
let entry = entry.map_err(|error| error.to_string())?;
|
||||
if !entry.file_type().map_err(|error| error.to_string())?.is_dir() { continue; }
|
||||
let project = entry.path();
|
||||
if !project.join(FILE).is_file() { continue; }
|
||||
let previous = if project == dir { state.clone() } else { load(&project)? };
|
||||
if project != dir && !same_production_product(state, &previous) { continue; }
|
||||
for id in previous["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
if id == candidate { continue; }
|
||||
let record = read_candidate(&project, id)?;
|
||||
if candidate_available(&record) && material_task_id(&record) == candidate {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(crate) fn retire_candidate(dir: &Path, target: &Value, reason: &str) -> R<Value> {
|
||||
let id = uuid(&target["source"]["candidateId"], "原候选")?;
|
||||
let observed = read_candidate(dir, &id)?;
|
||||
let Some(_dispatch) = lock_candidate_dispatch(dir, &id)? else {
|
||||
return Ok(json!({"status":"pending","candidateId":id,"requestId":observed["requestId"]}));
|
||||
};
|
||||
let _guard = sync::context_guard();
|
||||
original_project_present(dir)?;
|
||||
let state = load(dir)?;
|
||||
let mut record = read_candidate(dir, &id)?;
|
||||
let binding = &record["binding"];
|
||||
if state["id"] != target["workspaceId"] || state["activeOutput"] != target["outputId"]
|
||||
|| state["activeVariantId"] != target["variantId"]
|
||||
|| state["template"]["contentHash"] != target["templateHash"]
|
||||
|| !product_slot_binding(&state, binding)
|
||||
|| binding["slotId"] != target["slotId"] || binding["variantId"] != target["variantId"]
|
||||
{
|
||||
return Err("原候选不属于本轮项目、花色或图位".into());
|
||||
}
|
||||
if record["phase"] == "expired" { return Ok(candidate_receipt(&record)); }
|
||||
if !matches!(record["phase"].as_str(), Some("complete" | "failed")) {
|
||||
return Ok(json!({"status":"pending","candidateId":id,"requestId":record["requestId"]}));
|
||||
}
|
||||
let file = candidate_path(dir, &id)?;
|
||||
let keep_generated = record["phase"] == "complete"
|
||||
&& (record["modelId"].is_string() || record["canvasTransform"].is_object());
|
||||
if keep_generated && !creation::load(dir)?["deliveryDir"].is_null() {
|
||||
let task = read_json(&file.with_file_name("task.json"))?;
|
||||
if task["id"] != record["id"] || !matches!(task["phase"].as_str(), Some("complete" | "applied"))
|
||||
|| !(task["modelId"].is_string() || task["canvasTransform"].is_object())
|
||||
|| record["artifact"]["sha256"].is_string() && task["sha256"] != record["artifact"]["sha256"]
|
||||
{
|
||||
return Err("原生成图记录与候选不一致,图片已保留,请恢复原生成图后重试。".into());
|
||||
}
|
||||
super::delivery::save_generated_image(dir, &task)?;
|
||||
}
|
||||
if record["retirement"].is_null() {
|
||||
record["retirement"] = json!({"reason":reason,"at":now()});
|
||||
// Persist retirement before touching bytes so an interrupted cleanup
|
||||
// cannot resurface a failed candidate or masquerade as an unknown request.
|
||||
write_json(&file, &record)?;
|
||||
}
|
||||
let cleanup = (|| -> R<bool> {
|
||||
let shared = material_task_id(&record).as_str() == Some(id.as_str()) && shared_candidate_material(dir, &state, &id)?;
|
||||
if !shared {
|
||||
let files = if keep_generated { &["response.json"][..] } else { &["generated.png", "response.json"][..] };
|
||||
for name in files {
|
||||
match fs::remove_file(file.with_file_name(name)) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
|
||||
Err(error) => return Err(format!("未清理 {name}:{error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(shared)
|
||||
})();
|
||||
let mut receipt = json!({"status":"retired","candidateId":id,"slotId":record["binding"]["slotId"],
|
||||
"requestId":record["requestId"].as_str().or_else(|| record["sourceRequestId"].as_str()),
|
||||
"reason":record["retirement"]["reason"],"canvasLayerId":target["canvasLayerId"]});
|
||||
match cleanup {
|
||||
Ok(shared) => {
|
||||
receipt["sharedSourcePreserved"] = json!(shared);
|
||||
receipt["generatedImagePreserved"] = json!(keep_generated && file.with_file_name("generated.png").is_file());
|
||||
}
|
||||
Err(error) => receipt["cleanupError"] = json!(error),
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub(crate) fn same_production_product(current: &Value, source: &Value) -> bool {
|
||||
current["brief"]["identifier"].as_str().is_some_and(|id| !id.is_empty())
|
||||
&& ["identifier","identifierType","brandId"].iter().all(|key| current["brief"][*key] == source["brief"][*key])
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_projection_task(dir: &Path, record: &Value) -> R<Option<Value>> {
|
||||
let generated = record["sourceType"].is_null() && record["reusedFrom"].is_null();
|
||||
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))
|
||||
&& !(generated && record["phase"] == "failed") {
|
||||
return Ok(None);
|
||||
}
|
||||
let task = dir.join("image-jobs").join(uuid(&record["id"], "候选")?).join("task.json");
|
||||
if task.is_file() {
|
||||
let mut task = read_json(&task)?;
|
||||
super::images::reopen_ambiguous_expiry(&mut task);
|
||||
Ok(Some(task))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
// A prepared task must be durably replaced by a dispatched task before POST.
|
||||
// A stale candidate projection alone cannot establish that POST was attempted.
|
||||
pub(crate) fn settle_prepared_candidate(dir: &Path, record: &Value, task: &Value) -> R<Option<Value>> {
|
||||
if record["phase"] != "dispatched" || task["phase"] != "prepared"
|
||||
|| !record["requestId"].is_null() || !task["requestId"].is_null() || !task["upstreamTaskId"].is_null()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let id = uuid(&record["id"], "原候选")?;
|
||||
let Some(_dispatch) = lock_candidate_dispatch(dir, &id)? else { return Ok(None); };
|
||||
let Some(mut current) = candidate_projection_task(dir, record)? else { return Ok(None); };
|
||||
if current["phase"] != "prepared" || !current["requestId"].is_null() || !current["upstreamTaskId"].is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
if current["id"] != id || current["slotBinding"] != record["binding"] {
|
||||
return Err(format!("候选 {id} 与原请求 task.json 身份不一致"));
|
||||
}
|
||||
current["notDispatched"] = json!(true);
|
||||
current["message"] = json!("原图片请求未提交");
|
||||
reconcile_candidate(dir, ¤t).map(Some)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_needs_recovery(dir: &Path, record: &Value) -> R<bool> {
|
||||
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
|
||||
return Ok(false);
|
||||
}
|
||||
let task = candidate_projection_task(dir, record)?;
|
||||
Ok(!task.is_some_and(|task|
|
||||
matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired"))))
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_limits(dir: &Path, state: &Value, output: &str) -> R<(u64, u64, u64)> {
|
||||
let profile = production_profile::select(&state["template"], output)?.unwrap_or(&Value::Null);
|
||||
let positive = |key: &str| profile[key].as_u64().filter(|&value| value > 0);
|
||||
let refinement = read_production_settings(dir)?["refinement"] == true;
|
||||
let mode = if refinement { "fine" } else { "fast" };
|
||||
let configured = &profile["maxCandidatesPerSlot"];
|
||||
let candidate_override = configured.as_u64().or_else(|| configured[mode].as_u64()).filter(|&value| value > 0);
|
||||
let cap = candidate_override.unwrap_or(if refinement { 4 } else { 2 });
|
||||
let generation_cap = candidate_override.or_else(|| positive("maxGenerationAttempts")).unwrap_or(4);
|
||||
Ok((positive("candidatesPerSlot").unwrap_or(2), cap, generation_cap))
|
||||
}
|
||||
|
||||
pub(crate) fn slot_dispatch_usage(dir: &Path, state: &Value, slot: &Value, batch: &[String], current: Option<&str>) -> R<(u64, u64, Option<Value>)> {
|
||||
let mut used = 0;
|
||||
let mut generations = 0;
|
||||
let mut pending = None;
|
||||
for record in records(dir, state)? {
|
||||
if record["binding"]["slotId"] != slot["slotId"] || record["binding"]["variantId"] != slot["variantId"] {
|
||||
continue;
|
||||
}
|
||||
let task = candidate_projection_task(dir, &record)?;
|
||||
let dispatched = generation_was_dispatched(&record, task.as_ref());
|
||||
generations += u64::from(dispatched && record["origin"] != "human");
|
||||
if automated_candidate(&record) && (dispatched || local_candidate(&record)) { used += 1; }
|
||||
if record["id"].as_str() != current && !batch.iter().any(|id| record["id"] == id.as_str())
|
||||
&& candidate_needs_recovery(dir, &record)? {
|
||||
pending = Some(record["id"].clone());
|
||||
}
|
||||
}
|
||||
Ok((used, generations, pending))
|
||||
}
|
||||
|
||||
pub(crate) fn automated_candidate(record: &Value) -> bool {
|
||||
record["origin"] != "human" && record["retirement"].is_null()
|
||||
}
|
||||
|
||||
pub(crate) fn local_candidate(record: &Value) -> bool {
|
||||
!record["sourceType"].is_null() || !record["reusedFrom"].is_null()
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_limit_receipt(slot: &Value, used: u64, max: u64) -> Value {
|
||||
let reason = format!("本图位已用 {used} 张候选,上限 {max} 张。请从已有候选中选最合适的一张采用。");
|
||||
json!({"slotId":slot["slotId"],"variantId":slot["variantId"],"status":"candidate_limit_reached","phase":"candidate_limit_reached",
|
||||
"limitReached":true,"candidateCount":used,"maxCandidatesPerSlot":max,"candidatesRemaining":0,
|
||||
"message":reason,"reason":reason})
|
||||
}
|
||||
|
||||
pub(crate) fn generation_limit_receipt(slot: &Value, count: u64, cap: u64, generations: u64, generation_cap: u64) -> Value {
|
||||
let mut receipt = candidate_limit_receipt(slot, count, cap);
|
||||
receipt["phase"] = json!("draw_limit_reached");
|
||||
receipt["status"] = json!("draw_limit_reached");
|
||||
receipt["candidateCount"] = json!(count);
|
||||
receipt["candidatesRemaining"] = json!(cap.saturating_sub(count));
|
||||
receipt["generationAttempts"] = json!(generations);
|
||||
receipt["maxGenerationAttempts"] = json!(generation_cap);
|
||||
receipt["remainingGenerationAttempts"] = json!(0);
|
||||
receipt["drawLimitReached"] = json!(true);
|
||||
let reason = format!("本图位已用 {generations} 次生图,上限 {generation_cap} 次。候选已用 {count} 张,上限 {cap} 张。请从已有候选中选最合适的一张采用。");
|
||||
receipt["message"] = json!(reason);
|
||||
receipt["reason"] = json!(reason);
|
||||
receipt
|
||||
}
|
||||
|
||||
pub(crate) fn generation_was_dispatched(record: &Value, task: Option<&Value>) -> bool {
|
||||
record["sourceType"].is_null() && record["reusedFrom"].is_null()
|
||||
&& task.map_or_else(|| matches!(record["phase"].as_str(), Some("complete" | "expired")),
|
||||
|task| task["phase"] != "prepared")
|
||||
&& task.unwrap_or(record)["resultExpiry"]["source"] != "request_not_found"
|
||||
}
|
||||
|
||||
pub(crate) fn project_image_index(dir: &Path, filter: &Value) -> R<Value> {
|
||||
use std::io::Read as _;
|
||||
|
||||
let (state, records) = {
|
||||
let _guard = sync::context_guard();
|
||||
let state = load(dir)?;
|
||||
if !state["productTemplates"].is_object() || state["id"] != filter["workspaceId"] {
|
||||
return Err("本轮原生候选范围已变化".into());
|
||||
}
|
||||
let candidates = records(dir, &state)?;
|
||||
(state, candidates)
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
let mut adopted = std::collections::HashSet::new();
|
||||
let audits = dir.join("template-outputs");
|
||||
if audits.is_dir() {
|
||||
for entry in fs::read_dir(audits).map_err(|_| "无法读取采纳记录目录")? {
|
||||
let entry = entry.map_err(|_| "无法读取采纳记录目录项")?;
|
||||
if !entry.file_name().to_str().is_some_and(|name| name.starts_with("canvas-adoption-") && name.ends_with(".json")) {
|
||||
continue;
|
||||
}
|
||||
let audit = read_json(&entry.path())?;
|
||||
if audit["phase"] == "acknowledged" && audit["meta"]["workspaceId"] == state["id"]
|
||||
&& let Some(id) = audit["meta"]["candidateId"].as_str() {
|
||||
adopted.insert(id.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut generation_attempts = std::collections::HashMap::new();
|
||||
for record in &records {
|
||||
let binding = &record["binding"];
|
||||
if let Some(slot) = binding["slotId"].as_str()
|
||||
&& generation_was_dispatched(record, candidate_projection_task(dir, record)?.as_ref()) {
|
||||
*generation_attempts.entry(slot).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
let mut review_index = std::collections::HashMap::new();
|
||||
for record in records.iter().filter(|record| candidate_available(record)) {
|
||||
let binding = &record["binding"];
|
||||
let Some(output) = image_output_component(&state, binding) else { continue; };
|
||||
let Some(color) = binding["variantId"].as_str() else { continue; };
|
||||
if binding["workspaceId"] != state["id"] || !output_uses_variant(&state["brief"], output, color)
|
||||
|| (!filter["outputId"].is_null() && filter["outputId"] != output)
|
||||
|| (!filter["variantId"].is_null() && filter["variantId"] != color) {
|
||||
continue;
|
||||
}
|
||||
let id = record["id"].as_str().ok_or("候选编号缺失")?;
|
||||
let relative = format!("image-jobs/{id}/generated.png");
|
||||
if record["artifact"]["path"] != relative { continue; }
|
||||
let mut header = [0; 24];
|
||||
let Ok(()) = fs::File::open(dir.join(&relative)).and_then(|mut file| file.read_exact(&mut header)) else { continue; };
|
||||
let Ok((width, height)) = creation::png_size(&header) else { continue; };
|
||||
let reviews = review_index.entry((output, color))
|
||||
.or_insert_with(|| candidate_reviews(dir, &state["productTemplates"][output], output, color));
|
||||
rows.push(json!({"outputId":output,"variantId":color,"slotId":binding["slotId"],"fieldId":binding["fieldId"],
|
||||
"candidateId":id,"phase":"complete","width":width,"height":height,"reviewDecision":reviews[id]["decision"],
|
||||
"adoptionRecorded":adopted.contains(id),"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],
|
||||
"sourceRequestId":record["sourceRequestId"].as_str().or_else(|| record["requestId"].as_str()),
|
||||
"generationAttempts":generation_attempts.get(binding["slotId"].as_str().unwrap_or_default()).copied().unwrap_or(0)}));
|
||||
}
|
||||
Ok(json!(rows))
|
||||
}
|
||||
|
||||
pub(crate) fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope: &str, same_product_only: bool) -> R<Value> {
|
||||
let Some(account_projects) = dir.parent() else { return Err("当前项目目录无效".into()) };
|
||||
let selected = variant(state, variant_id)?;
|
||||
let references = generation_references(dir, state, variant_id)?;
|
||||
let template = &state["template"]["contentHash"];
|
||||
let component = state["activeOutput"].as_str().ok_or("当前输出类型无效")?;
|
||||
let mut preferred_sources = std::collections::HashSet::new();
|
||||
let mut result = Vec::new();
|
||||
for entry in fs::read_dir(account_projects).map_err(|_| "本机项目目录无法读取")? {
|
||||
let entry = entry.map_err(|_| "本机项目目录读取中断")?;
|
||||
let source = entry.path();
|
||||
if source == dir || !entry.file_type().is_ok_and(|kind| kind.is_dir()) { continue; }
|
||||
let project = entry.file_name().to_string_lossy().into_owned();
|
||||
if Uuid::parse_str(&project).is_err() || !source.join(FILE).is_file() { continue; }
|
||||
let Ok(previous) = load(&source) else { continue };
|
||||
if !same_production_product(state, &previous) { continue; }
|
||||
let review_path = source.join("agent").join(scope).join(&project).join("conversation-v1");
|
||||
let mut reviews = std::collections::HashMap::new();
|
||||
for id in previous["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
let Ok(record) = read_candidate(&source, id) else { continue };
|
||||
if record["retirement"].is_object() { continue; }
|
||||
let binding = &record["binding"];
|
||||
let archived = record["sourceType"] == "archived-candidate";
|
||||
let product_crop = record["sourceType"] == "product-reference" && binding["referenceCrop"].is_array();
|
||||
if !product_slot_binding(&previous, binding) || !product_crop && record["sourceType"].is_string() && !archived {
|
||||
continue;
|
||||
}
|
||||
let Some(old_variant) = binding["variantId"].as_str().and_then(|id| variant(&previous, id).ok()) else { continue };
|
||||
let Some(source_field) = binding["fieldId"].as_str() else { continue };
|
||||
let slot = slot_id(template, variant_id, source_field);
|
||||
let exact = binding["templateHash"] == *template
|
||||
&& ["colorName","colorMaterialId","dimensions"].iter().all(|key| old_variant[*key] == selected[*key])
|
||||
&& (product_crop || record["references"] == references);
|
||||
let target = exact.then(|| definition(state, &slot, variant_id).ok()).flatten()
|
||||
.filter(|(output, _)| output["component"] == state["activeOutput"] && output["id"] == binding["outputId"]);
|
||||
if target.is_none() && !same_product_only { continue; }
|
||||
// The previous review only determines what to inspect first.
|
||||
let preferred = target.is_some() && record["phase"] == "complete" && old_variant["id"].as_str().is_some_and(|previous_id| {
|
||||
let journal = reviews.entry(previous_id).or_insert_with(|| {
|
||||
let file = review_path.join(format!("production-{component}-{previous_id}.json"));
|
||||
let receipt = read_json(&file).unwrap_or_default();
|
||||
if receipt["binding"] == json!([template, previous_id]).to_string() { receipt } else { Value::Null }
|
||||
});
|
||||
let Some(previous_slot) = binding["slotId"].as_str() else { return false };
|
||||
let item = &journal["items"][previous_slot];
|
||||
item["state"] == "applied" && item["adoption"] == "automatic" && item["candidateId"] == id
|
||||
&& item["approvals"].as_array().into_iter().flatten().any(|approval|
|
||||
approval["candidateId"] == id && approval["decision"] == "pass")
|
||||
});
|
||||
if product_crop {
|
||||
let Some((output, field)) = target.filter(|_| preferred) else { continue };
|
||||
let Ok(mode) = product_crop_mode(state, output, field) else { continue };
|
||||
if binding["referenceCropMode"].as_str() != mode { continue; }
|
||||
let Some(source) = record["references"][0]["source"].as_str() else { continue };
|
||||
let Some(index) = references.as_array().into_iter().flatten()
|
||||
.filter(|row| row["purpose"] == "product").take(8).position(|row| row["source"] == source)
|
||||
else { continue };
|
||||
result.push((project.clone(), id.to_owned(), json!({"slotId":slot,"projectId":project,
|
||||
"candidateId":id,"phase":"product-crop","referenceIndex":index,
|
||||
"referenceCrop":binding["referenceCrop"],"createdAt":record["createdAt"]})));
|
||||
continue;
|
||||
}
|
||||
if archived {
|
||||
let original = &record["reusedFrom"];
|
||||
if preferred && let (Some(project), Some(candidate)) = (original["projectId"].as_str(), original["candidateId"].as_str()) {
|
||||
preferred_sources.insert((project.to_owned(), candidate.to_owned()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let file = source.join("image-jobs").join(id).join("task.json");
|
||||
let Ok(task) = read_json(&file) else { continue };
|
||||
if task["id"] != id || task["slotBinding"] != *binding { continue; }
|
||||
let phase = match task["phase"].as_str() {
|
||||
Some("complete") if record["phase"] == "complete" && record["requestId"].is_string()
|
||||
&& record["requestId"] == task["requestId"] => "complete",
|
||||
Some("failed") if record["phase"] == "failed" => "failed",
|
||||
Some("expired") => "expired",
|
||||
Some("dispatched" | "running" | "unknown" | "complete" | "failed") => "unknown",
|
||||
_ => continue,
|
||||
};
|
||||
if phase == "complete" && preferred {
|
||||
preferred_sources.insert((project.clone(), id.to_owned()));
|
||||
}
|
||||
if target.is_none() && phase != "complete" { continue; }
|
||||
let mut row = json!({
|
||||
"slotId":target.is_some().then_some(slot),"projectId":project,"candidateId":id,"phase":phase,
|
||||
"requestId":task["requestId"],"createdAt":record["createdAt"],"originalFieldId":source_field,
|
||||
"originalOutputId":binding["outputId"],"originalTemplateHash":binding["templateHash"],
|
||||
"originalColor":old_variant["colorName"]});
|
||||
if phase == "expired" {
|
||||
row["retryable"] = json!(false);
|
||||
row["resultExpiry"] = task["resultExpiry"].clone();
|
||||
}
|
||||
result.push((project.clone(), id.to_owned(), row));
|
||||
}
|
||||
}
|
||||
let mut result: Vec<_> = result.into_iter().map(|(project, id, row)| {
|
||||
let preferred = row["phase"] == "complete" && preferred_sources.contains(&(project, id));
|
||||
(preferred, row)
|
||||
}).collect();
|
||||
result.sort_by(|(left_preferred, left), (right_preferred, right)| right_preferred.cmp(left_preferred)
|
||||
.then_with(|| right["createdAt"].as_u64().cmp(&left["createdAt"].as_u64())));
|
||||
Ok(Value::Array(result.into_iter().map(|(_, row)| row).collect()))
|
||||
}
|
||||
|
||||
pub(crate) fn reuse_archived_candidate(dir: &Path, state: Value, input: &Value, preflight: Option<&Backend>) -> R<Value> {
|
||||
reuse_archived_candidate_scoped(dir, state, input, preflight, false)
|
||||
}
|
||||
|
||||
pub(crate) fn reuse_archived_candidate_scoped(dir: &Path, state: Value, input: &Value, preflight: Option<&Backend>, project_scoped: bool) -> R<Value> {
|
||||
let local = input["sourceProjectId"].is_null();
|
||||
let project = if local {
|
||||
uuid(&json!(dir.file_name().and_then(|name| name.to_str())), "当前项目")?
|
||||
} else {
|
||||
uuid(&input["sourceProjectId"], "原项目")?
|
||||
};
|
||||
let candidate = uuid(&input["sourceCandidateId"], "原候选")?;
|
||||
let variant_id = uuid(&input["variantId"], "花色")?;
|
||||
let slot = input["slotId"].as_str().ok_or("请选择图片目标")?;
|
||||
let (output, field) = definition(&state, slot, &variant_id)?;
|
||||
let origin = json!({"projectId":project,"candidateId":candidate});
|
||||
if !state["productTemplates"].is_object() || state["activeVariantId"] != variant_id
|
||||
|| state["activeOutput"] != output["component"] || !output_uses_variant(&state["brief"], state["activeOutput"].as_str().unwrap_or(""), &variant_id)
|
||||
{
|
||||
return Err("请打开要复用候选的产品画布".into());
|
||||
}
|
||||
let target_input = input_hash(dir, &state, &variant_id)?;
|
||||
{
|
||||
let _guard = sync::context_guard();
|
||||
// The supplied view can predate a sibling reservation.
|
||||
let current = load(dir)?;
|
||||
for prior in records(dir, ¤t)?.into_iter()
|
||||
.filter(|row| candidate_available(row) && row["binding"]["slotId"] == slot && row["reusedFrom"] == origin)
|
||||
{
|
||||
if candidate_uses_current_inputs(dir, &state, &prior, &variant_id)? {
|
||||
return Ok(prior);
|
||||
}
|
||||
}
|
||||
}
|
||||
let source = if local {
|
||||
dir.to_owned()
|
||||
} else {
|
||||
let projects = dir.parent().ok_or("当前项目目录无效")?;
|
||||
let source = projects.join(&project);
|
||||
let root = fs::canonicalize(projects).map_err(|_| "当前项目目录不可读取")?;
|
||||
if source == dir || fs::canonicalize(&source).ok().as_deref().and_then(Path::parent) != Some(root.as_path()) {
|
||||
return Err("历史候选须属于当前账户的另一本机项目".into());
|
||||
}
|
||||
source
|
||||
};
|
||||
read_candidate(&source, &candidate)?;
|
||||
let _source = lock_candidate_dispatch(&source, &candidate)?.ok_or("原候选尚在处理,请稍后读取")?;
|
||||
let source_record = read_candidate(&source, &candidate)?;
|
||||
let (source_state, _) = checked_binding(&source, &source_record["binding"], true)?;
|
||||
let archived_binding = &source_record["binding"];
|
||||
let original_refs = generation_references(dir, &state, &variant_id)?;
|
||||
let scope_matches = if local {
|
||||
archived_binding["variantId"] == variant_id
|
||||
&& source_record["references"].as_array().is_some_and(|refs| !refs.is_empty()
|
||||
&& refs.iter().all(|reference| original_refs.as_array().is_some_and(|current|
|
||||
current.iter().any(|image| image["source"] == reference["source"]))))
|
||||
} else {
|
||||
same_production_product(&state, &source_state)
|
||||
&& (input["forReview"] == true || (
|
||||
archived_binding["templateHash"] == state["template"]["contentHash"]
|
||||
&& archived_binding["fieldId"] == field["fieldId"] && archived_binding["outputId"] == output["id"]
|
||||
&& source_record["references"] == original_refs))
|
||||
&& source_record["requestId"].is_string()
|
||||
};
|
||||
if !scope_matches || !candidate_available(&source_record) {
|
||||
return Err("原候选未完成或不属于同款商品,请查看同款的已完成候选".into());
|
||||
}
|
||||
let source_task = read_json(&source.join("image-jobs").join(&candidate).join("task.json"))?;
|
||||
if source_task["phase"] != "complete" || source_task["id"] != candidate
|
||||
|| source_task["requestId"] != source_record["requestId"] || source_task["slotBinding"] != *archived_binding
|
||||
{
|
||||
return Err("历史候选没有已确认完成的原请求".into());
|
||||
}
|
||||
let artwork = template_slots::artifact(&source, &candidate, &source_task)?;
|
||||
if artwork != source_record["artifact"] { return Err("历史候选像素与记录不一致".into()); }
|
||||
let file = source.join(artwork["path"].as_str().ok_or("历史图片路径无效")?);
|
||||
let mut pixels = Vec::new();
|
||||
std::io::Read::read_to_end(&mut std::io::Read::take(fs::File::open(file).map_err(|_| "历史图片无法读取")?,20*1024*1024+1), &mut pixels)
|
||||
.map_err(|_| "历史图片无法读取")?;
|
||||
if pixels.len() > 20*1024*1024 || artwork["sha256"] != format!("{:x}", Sha256::digest(&pixels)) {
|
||||
return Err("历史候选像素已变化".into());
|
||||
}
|
||||
if local && archived_binding["slotId"] == slot && candidate_uses_current_inputs(dir, &state, &source_record, &variant_id)? {
|
||||
return Ok(source_record);
|
||||
}
|
||||
if let Some(backend) = preflight {
|
||||
let edges = backend.archived_text_obstructions(&state, field, slot, &variant_id, &pixels)?;
|
||||
if !edges.is_empty() {
|
||||
return Ok(json!({"status":"skipped","hardEdges":edges}));
|
||||
}
|
||||
}
|
||||
let slot_key = json!({"slotId":slot,"variantId":variant_id});
|
||||
let _admission = if input["detailBatch"] == true {
|
||||
let lock = lock_slot_dispatch(dir, &slot_key)?.ok_or("本图位已有生图批次正在处理")?;
|
||||
let (_, max, _) = candidate_limits(dir, &state, output["component"].as_str().unwrap_or_default())?;
|
||||
let (used, _, _) = slot_dispatch_usage(dir, &load(dir)?, &slot_key, &[], None)?;
|
||||
if used >= max { return Ok(candidate_limit_receipt(&slot_key, used, max)); }
|
||||
Some(lock)
|
||||
} else { None };
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let mut binding = new_binding(&state,output,field,slot,&variant_id,&id,"历史同款候选");
|
||||
if input["detailBatch"] == true { binding["detailBatch"] = json!(true); }
|
||||
if photocraft_ui_egui::jiansun::user_slot_scope(input).is_some() { binding["origin"] = json!("human"); }
|
||||
let source_request = source_task.get("requestId").filter(|id| id.is_string())
|
||||
.unwrap_or(&source_record["sourceRequestId"]);
|
||||
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete",
|
||||
"reusedFrom":origin,"materialTaskId":material_task_id(&source_record),"sourceRequestId":source_request,"requestId":null,
|
||||
"inputHash":target_input,"references":original_refs,
|
||||
"prompt":source_record.get("prompt").filter(|prompt| prompt.is_string()).unwrap_or(&source_task["prompt"]),
|
||||
"instructions":"历史候选,等待当前图位验收","createdAt":now()});
|
||||
mount_archived_candidate(dir, state, record, artwork["sha256"].clone(), &pixels, project_scoped)
|
||||
}
|
||||
|
||||
pub(crate) fn mount_archived_candidate(dir: &Path, state: Value, mut record: Value, digest: Value, pixels: &[u8], project_scoped: bool) -> R<Value> {
|
||||
let id = uuid(&record["id"], "候选")?;
|
||||
let job = dir.join("image-jobs").join(&id);
|
||||
record["sourceType"] = json!("archived-candidate");
|
||||
let journal = json!({"id":id,"version":1,"slotBinding":record["binding"],"phase":"complete","requestId":null,
|
||||
"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"materialTaskId":record["materialTaskId"],
|
||||
"sourceRequestId":record["sourceRequestId"],"sha256":digest});
|
||||
write_json(&job.join("task.json"), &journal)?;
|
||||
photocraft_format::atomic_write(&job.join("generated.png"), pixels).map_err(|_| "历史候选无法保存")?;
|
||||
record["artifact"] = template_slots::artifact(dir, &id, &journal)?;
|
||||
reserve_candidate(dir, state, &record, project_scoped)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
pub(crate) fn historical_candidate_pixels(dir: &Path, state: &Value, record: &Value) -> R<Vec<u8>> {
|
||||
let id = &record["id"];
|
||||
if record["artifact"]["taskId"] != *id || !binding_is_canvas(&record["binding"]) {
|
||||
return Err("历史候选记录不一致,无法采纳".into());
|
||||
}
|
||||
if state["candidates"].as_array().is_some_and(|ids| ids.contains(id)) {
|
||||
return candidate_pixels(dir, &record["artifact"])
|
||||
.map_err(|error| format!("历史图片无法采纳:{error}"));
|
||||
}
|
||||
completed_candidate(dir, state, record.clone(), false).map(|(_, pixels)| pixels)
|
||||
.ok_or_else(|| "历史图片已缺失或校验失败,无法采纳".into())
|
||||
}
|
||||
|
||||
pub(crate) fn mount_historical_adoption(dir: &Path, state: &Value, input: &Value, record: &Value, project_scoped: bool) -> R<Value> {
|
||||
let variant = uuid(&input["variantId"], "花色")?;
|
||||
let slot = input["slotId"].as_str().ok_or("请选择图片目标")?;
|
||||
let (output, field) = definition(state, slot, &variant)?;
|
||||
if !candidate_available(record) || state["activeVariantId"] != variant || state["activeOutput"] != output["component"]
|
||||
|| !candidate_matches_slot(record, state, &state["template"], output, field, &variant)
|
||||
{
|
||||
return Err("历史候选不属于当前画布的图位和花色,未采纳".into());
|
||||
}
|
||||
let layer = input["nativeLayerId"].as_u64().filter(|&id| id > 0).ok_or("原生图片图层身份缺失")?;
|
||||
let mapped = mapped_slot(state, slot, &variant).filter(|row| row["nativeLayerId"] == layer)
|
||||
.ok_or("原生图层不属于此花色和图片目标,未采纳")?;
|
||||
slot_frame(field, Some(mapped)).ok_or("当前图片图层缺少已核对的范围,未采纳")?;
|
||||
let source_id = uuid(&record["id"], "历史候选")?;
|
||||
let _source = lock_candidate_dispatch(dir, &source_id)?.ok_or("历史候选正在处理,请稍后采纳")?;
|
||||
let record = &read_candidate(dir, &source_id)?;
|
||||
if !candidate_available(record) || !candidate_matches_slot(record, state, &state["template"], output, field, &variant) {
|
||||
return Err("历史候选已不可用,未采纳".into());
|
||||
}
|
||||
let pixels = historical_candidate_pixels(dir, state, record)?;
|
||||
let project = uuid(&json!(dir.file_name().and_then(|name| name.to_str())), "当前项目")?;
|
||||
let origin = json!({"projectId":project,"candidateId":record["id"]});
|
||||
let target_input = input_hash(dir, state, &variant)?;
|
||||
let current = load(dir)?;
|
||||
for prior in read_records(dir, ¤t, true)?.into_iter().filter(|prior|
|
||||
candidate_available(prior) && prior["unindexed"].is_null()
|
||||
&& prior["binding"]["slotId"] == slot && prior["inputHash"] == target_input
|
||||
&& prior["reusedFrom"] == origin && prior["artifact"]["sha256"] == record["artifact"]["sha256"]
|
||||
) {
|
||||
let id = uuid(&prior["id"], "候选")?;
|
||||
if read_json(&dir.join("image-jobs").join(&id).join("task.json")).is_ok_and(|task|
|
||||
task["slotBinding"] == prior["binding"]
|
||||
&& template_slots::artifact(dir, &id, &task).is_ok_and(|artifact| artifact == prior["artifact"]))
|
||||
{
|
||||
return Ok(prior);
|
||||
}
|
||||
}
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let binding = new_binding(state, output, field, slot, &variant, &id, "历史候选");
|
||||
let source_request = record.get("requestId").filter(|id| id.is_string()).unwrap_or(&record["sourceRequestId"]);
|
||||
let mounted = json!({"version":2,"id":id,"binding":binding,"phase":"complete","origin":"human",
|
||||
"reusedFrom":origin,"materialTaskId":material_task_id(record),"sourceRequestId":source_request,"requestId":null,
|
||||
"inputHash":target_input,"references":record["references"],"prompt":record["prompt"],
|
||||
"instructions":"历史候选","createdAt":now()});
|
||||
mount_archived_candidate(dir, state.clone(), mounted, record["artifact"]["sha256"].clone(), &pixels, project_scoped)
|
||||
}
|
||||
pub(crate) fn operation_receipt(mut canonical: Value, candidate: Option<Value>, error: Option<String>) -> Value {
|
||||
if let Some(candidate) = candidate {
|
||||
canonical["candidateResult"] = candidate;
|
||||
}
|
||||
if let Some(error) = error {
|
||||
canonical["error"] = json!(error);
|
||||
}
|
||||
canonical
|
||||
}
|
||||
@ -0,0 +1,508 @@
|
||||
use super::super::{Backend, Document, Event, Path, PathBuf, R, Value, fs, hash, images, json, mpsc, production_profile, read_json};
|
||||
use super::{SUPPORTED_PRODUCTION_OUTPUTS, adopted_review_image, cached_prompt_mapping, candidate_available, candidate_receipt, compare_text_region_edges, contain_review_preview, cover_review_preview, crop_product_image, definition, editable_image_prompt, generation_references_for_output, jiansun_image_transform, load, load_detail_workspace, local_candidate, local_product_photo, lock_candidate_dispatch, mapped_slot, mapping, merge_missing_ending, missing_ending_pages, outline_crop, output_state_inner, page_fields, pending_candidate, pending_production_image, product_crop_mode, product_crop_pixels, product_slot_binding, production_image_history, production_output_state, project_candidate, project_image_index, publish_prepared, read_candidate, reconcile_candidate, recover_candidate_without_task, references, render_template_edit, retire_candidate, reuse_archived_candidate, review_region_preview, revision, slot_frame, slot_id, slot_text_regions, snapshot_for_view, specified_image_ratio, swatch_has_white_backdrop, uuid, variant, verify_adopted_source};
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn detail_layout_bytes(&self, field: &Value) -> R<Option<Vec<u8>>> {
|
||||
let reference = &field["previewReference"];
|
||||
if !reference.is_object() {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(bytes) = self.cached_detail_layout_bytes(field)? {
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
let result = self.enterprise_template_request(json!({"action":"field-preview",
|
||||
"fileId":reference["fileId"],"revision":reference["revision"]}))?;
|
||||
let folder = self.dir().join("enterprise-templates").join("resource-previews");
|
||||
let path = result["imagePath"].as_str().map(PathBuf::from).filter(|path| path.parent() == Some(folder.as_path()))
|
||||
.ok_or("当前图位原参考没有实际画面")?;
|
||||
fs::read(path).map(Some).map_err(|_| "图位原参考无法读取".into())
|
||||
}
|
||||
|
||||
pub(crate) fn cached_detail_layout_bytes(&self, field: &Value) -> R<Option<Vec<u8>>> {
|
||||
use std::io::Read as _;
|
||||
let reference = &field["previewReference"];
|
||||
let (Some(id), Some(revision)) = (reference["fileId"].as_str(), reference["revision"].as_str())
|
||||
else { return Ok(None); };
|
||||
// Same cache key as the enterprise field-preview reader.
|
||||
let key = serde_json::to_string(&(id, revision)).map_err(|_| "图位原参考身份无效")?;
|
||||
let path = self.dir().join("enterprise-templates").join("resource-previews")
|
||||
.join(format!("{}.image", hash(&key)));
|
||||
let file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(_) => return Err("图位原参考缓存无法读取".into()),
|
||||
};
|
||||
const PREVIEW_LIMIT: usize = 8 * 1024 * 1024;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(PREVIEW_LIMIT as u64 + 1).read_to_end(&mut bytes)
|
||||
.map_err(|_| "图位原参考缓存无法读取")?;
|
||||
if bytes.len() > PREVIEW_LIMIT { return Err("图位原参考缓存过大".into()); }
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
fn cached_detail_layout_frame(&self, field: &Value, frame: &Value) -> R<Option<egui::ColorImage>> {
|
||||
let Some(bytes) = self.cached_detail_layout_bytes(field)? else { return Ok(None); };
|
||||
cover_review_preview(super::images::decode_agent_image(&bytes)?, frame).map(Some)
|
||||
}
|
||||
|
||||
pub(crate) fn archived_text_obstructions(&self, state: &Value, field: &Value, slot: &str, variant_id: &str, pixels: &[u8]) -> R<Vec<Value>> {
|
||||
let regions = slot_text_regions(state, slot, variant_id);
|
||||
if regions.is_empty() { return Ok(Vec::new()); }
|
||||
let frame = slot_frame(field, mapped_slot(state, slot, variant_id)).ok_or("历史候选缺少当前图框")?;
|
||||
let Some(reference) = self.cached_detail_layout_frame(field, frame)? else { return Ok(Vec::new()); };
|
||||
let preview = cover_review_preview(super::images::decode_agent_image(pixels)?, frame)?;
|
||||
compare_text_region_edges(&preview, &reference, ®ions)
|
||||
}
|
||||
|
||||
pub(crate) fn detail_archive(&mut self, doc: u64, target: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
if target["projectImages"] == true {
|
||||
return project_image_index(&dir, target);
|
||||
}
|
||||
let mut state = load_detail_workspace(&dir)?;
|
||||
if !state["productTemplates"].is_object() || state["id"] != target["workspaceId"] {
|
||||
return Err("本轮原生候选范围已变化".into());
|
||||
}
|
||||
let variant_id = uuid(&target["variantId"], "花色")?;
|
||||
if target["projectPlan"] == true {
|
||||
let output = target["outputId"].as_str().ok_or("成品编号缺失")?;
|
||||
let scoped = production_output_state(state, output, &variant_id)?;
|
||||
let mut facts = snapshot_for_view(&dir, Some(scoped), true)?;
|
||||
facts["productVariantId"] = json!(variant_id);
|
||||
facts["productEvidence"] = target["productEvidence"].clone();
|
||||
facts["revisions"] = target["revisions"].clone();
|
||||
return Ok(facts);
|
||||
}
|
||||
let project_scope = target["projectScope"] == true && target["source"]["recover"] == true;
|
||||
if project_scope {
|
||||
let output = target["outputId"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id))
|
||||
.ok_or("原请求制作输出无效")?;
|
||||
state = production_output_state(state, output, &variant_id)?;
|
||||
} else if state["activeOutput"] != target["outputId"] || state["activeVariantId"] != variant_id
|
||||
|| state["template"]["contentHash"] != target["templateHash"] {
|
||||
return Err("本轮原生候选范围已变化".into());
|
||||
}
|
||||
if target["source"].is_null() {
|
||||
return production_image_history(&dir, &state, &variant_id, &self.scope(), target["sameProductOnly"] == true);
|
||||
}
|
||||
if target["source"]["recover"] == true {
|
||||
let candidate = uuid(&target["source"]["candidateId"], "原候选")?;
|
||||
let (source_dir, source_doc, local_candidate) = if target["source"]["projectId"].is_null() {
|
||||
let record = read_candidate(&dir, &candidate)?;
|
||||
if !product_slot_binding(&state, &record["binding"]) || record["binding"]["slotId"] != target["slotId"]
|
||||
|| record["binding"]["variantId"] != variant_id
|
||||
|| project_scope && !definition(&state, target["slotId"].as_str().unwrap_or_default(), &variant_id)
|
||||
.is_ok_and(|(output, _)| output["component"] == target["outputId"] && output["id"] == record["binding"]["outputId"])
|
||||
{
|
||||
return Err("原候选不属于本轮图位".into());
|
||||
}
|
||||
(dir.clone(), doc, Some(record))
|
||||
} else {
|
||||
let local = uuid(&target["source"]["projectId"], "历史原项目")?;
|
||||
let history = production_image_history(&dir, &state, &variant_id, &self.scope(), false)?;
|
||||
if !history.as_array().into_iter().flatten().any(|item|
|
||||
item["slotId"] == target["slotId"] && item["projectId"] == local && item["candidateId"] == candidate
|
||||
&& matches!(item["phase"].as_str(), Some("unknown" | "complete" | "failed" | "expired")))
|
||||
{
|
||||
return Err("历史候选不属于同款图位".into());
|
||||
}
|
||||
let path = dir.parent().ok_or("原项目目录无效")?.join(&local);
|
||||
let ephemeral = photocraft_doc::DocId::fresh().0;
|
||||
self.owners.insert(ephemeral, self.scope());
|
||||
self.locations.insert(ephemeral, local);
|
||||
(path, ephemeral, None)
|
||||
};
|
||||
let result = (|| {
|
||||
let file = source_dir.join("image-jobs").join(&candidate).join("task.json");
|
||||
// A live dispatcher may have saved task.json without sending the
|
||||
// POST yet. It owns recovery until it releases the dispatch lock.
|
||||
let _dispatch = if let Some(record) = local_candidate.as_ref() {
|
||||
let Some(dispatch) = lock_candidate_dispatch(&source_dir, &candidate)? else {
|
||||
return Ok((pending_candidate(record), false));
|
||||
};
|
||||
if !file.try_exists().map_err(|error| error.to_string())? {
|
||||
return recover_candidate_without_task(&source_dir, record).map(|record| (record, true));
|
||||
}
|
||||
Some(dispatch)
|
||||
} else { None };
|
||||
let mut original = read_json(&file)?;
|
||||
super::images::reopen_ambiguous_expiry(&mut original);
|
||||
if original["id"] != candidate {
|
||||
return Err("原候选任务身份已变化".into());
|
||||
}
|
||||
if let Some(record) = local_candidate.as_ref()
|
||||
&& original["outputScope"].is_string() && original["slotBinding"]["detailBatch"] == true {
|
||||
if original["slotBinding"] != record["binding"] {
|
||||
return Err("原候选任务与图位记录不一致".into());
|
||||
}
|
||||
if pending_production_image(record, &original)?.is_some() {
|
||||
self.image_job(None, &json!({"doc":source_doc,"taskId":candidate,"recoveryBudgetMs":9000}), true, events, ctx)?;
|
||||
original = read_json(&file)?;
|
||||
}
|
||||
return project_candidate(&source_dir, record, &original).map(|record| (record, false));
|
||||
}
|
||||
let record = reconcile_candidate(&source_dir, &original)?;
|
||||
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
|
||||
return Ok((record, true));
|
||||
}
|
||||
// Query the saved task by its original request information.
|
||||
self.image_job(None, &json!({"doc":source_doc,"taskId":candidate,"recoveryBudgetMs":9000}), true, events, ctx)?;
|
||||
reconcile_candidate(&source_dir, &read_json(&file)?).map(|record| (record, true))
|
||||
})();
|
||||
if doc != source_doc {
|
||||
self.owners.remove(&source_doc);
|
||||
self.locations.remove(&source_doc);
|
||||
}
|
||||
let (record, refresh) = result?;
|
||||
if refresh && doc == source_doc {
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(candidate_receipt(&record));
|
||||
}
|
||||
if let Some(reason) = target["source"]["retireReason"].as_str() {
|
||||
let receipt = retire_candidate(&dir, target, reason)?;
|
||||
if receipt["status"] == "retired" {
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(receipt);
|
||||
}
|
||||
let preflight = (target["source"]["forReview"] != true).then_some(&*self);
|
||||
let record = reuse_archived_candidate(&dir, state, &json!({"slotId":target["slotId"],"variantId":variant_id,
|
||||
"sourceProjectId":target["source"]["projectId"],"sourceCandidateId":target["source"]["candidateId"],
|
||||
"forReview":target["source"]["forReview"],"detailBatch":true}), preflight)?;
|
||||
if matches!(record["status"].as_str(), Some("skipped" | "candidate_limit_reached")) {
|
||||
return Ok(record);
|
||||
}
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
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);
|
||||
Ok(candidate_receipt(&record))
|
||||
}
|
||||
|
||||
pub(crate) fn read_detail_review_images(&self, doc: u64, target: &Value, adopted_canvas: Option<&Document>) -> R<Value> {
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
let state = load_detail_workspace(&dir)?;
|
||||
let variant_id = uuid(&target["variantId"], "花色")?;
|
||||
let invalid_slot = "图片目标不属于当前模板和花色";
|
||||
variant(&state, &variant_id).map_err(|_| invalid_slot)?;
|
||||
let scoped = target["projectScope"] == true;
|
||||
let component = target["outputId"].as_str().ok_or("成品编号缺失")?;
|
||||
let state = if scoped {
|
||||
if target["workspaceId"] != state["id"] { return Err("制作项目已变化".into()); }
|
||||
production_output_state(state, component, &variant_id)?
|
||||
} else if state["productTemplates"][component].is_object()
|
||||
&& (state["activeOutput"] != component || state["activeVariantId"] != variant_id)
|
||||
{
|
||||
// The bridge binds this read to the opened canvas. Another canvas
|
||||
// can have changed the project's active output since it was opened.
|
||||
output_state_inner(state, component, &variant_id, false)?
|
||||
} else { state };
|
||||
let reference = target["slotId"].as_str().ok_or("图片图位缺失")?;
|
||||
let resolved;
|
||||
let slot = if scoped && definition(&state, reference, &variant_id).is_err() {
|
||||
let mut fields = state["template"]["outputs"].as_array().into_iter().flatten()
|
||||
.filter(|page| page["component"] == component)
|
||||
.flat_map(|page| page["slots"].as_array().into_iter().flatten())
|
||||
.filter(|field| field["kind"] == "image" && field["fieldId"] == reference);
|
||||
if fields.next().is_none() { return Err(invalid_slot.into()); }
|
||||
if fields.next().is_some() { return Err("图片图位编号重复,请使用完整图位编号".into()); }
|
||||
resolved = slot_id(&state["template"]["contentHash"], &variant_id, reference);
|
||||
&resolved
|
||||
} else { reference };
|
||||
let (output, field) = definition(&state, slot, &variant_id)?;
|
||||
if output["component"] != component { return Err(invalid_slot.into()); }
|
||||
if state["activeOutput"] != component
|
||||
|| (!scoped && target["templateHash"] != state["template"]["contentHash"])
|
||||
|| state["activeVariantId"].as_str() != Some(variant_id.as_str()) {
|
||||
return Err("当前模板、输出或花色已变化".into());
|
||||
}
|
||||
let scoped_adopted_canvas = if scoped && target["adopted"] == true {
|
||||
jiansun_image_transform::source_canvas(&dir, &state, &variant_id, component, &state["template"]["contentHash"], adopted_canvas)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let scoped_adopted_id = if scoped && target["adopted"] == true {
|
||||
let Some(placed) = jiansun_image_transform::adopted_candidate(scoped_adopted_canvas.as_deref(), &variant_id, slot) else {
|
||||
let candidates: Vec<_> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
|
||||
.filter_map(|id| read_candidate(&dir, id).ok()
|
||||
.filter(|row| row["binding"]["slotId"] == slot && row["binding"]["variantId"] == variant_id)
|
||||
.map(|row| json!({"id":id,"status":if row["phase"] == "complete" { "complete" } else { row["phase"].as_str().unwrap_or("unknown") }})))
|
||||
.collect();
|
||||
return Ok(json!({"slotId":slot,"outputId":component,"variantId":variant_id,
|
||||
"adopted":false,"candidateId":null,"candidateReady":false,"candidates":candidates,"images":[]}));
|
||||
};
|
||||
if target["candidateId"].as_str().is_some_and(|id| id != placed) {
|
||||
return Err("当前图位已改变,保留编辑,未记录旧候选验图".into());
|
||||
}
|
||||
Some(placed.to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let adopted_canvas = scoped_adopted_canvas.as_deref().or(adopted_canvas);
|
||||
let candidate_id = scoped_adopted_id.as_deref().or_else(|| target["candidateId"].as_str());
|
||||
let candidate_record = candidate_id.map(|id| {
|
||||
read_candidate(&dir, id).map_err(|error| {
|
||||
let valid: Vec<_> = state["candidates"].as_array().into_iter().flatten().filter_map(Value::as_str)
|
||||
.filter(|candidate| read_candidate(&dir, candidate).is_ok_and(|record|
|
||||
record["binding"]["slotId"] == slot && record["binding"]["variantId"] == variant_id))
|
||||
.collect();
|
||||
format!("{error}。candidateId 收到「{id}」。图位 {} 的有效候选号:{}。", field["fieldId"], json!(valid))
|
||||
})
|
||||
}).transpose()?;
|
||||
if let Some((candidate, record)) = candidate_id.zip(candidate_record.as_ref()) {
|
||||
if record["binding"]["variantId"] != variant_id {
|
||||
return Err("候选图属于其他花色,不能放进本图位".into());
|
||||
}
|
||||
if !candidate_available(record) {
|
||||
return Ok(json!({"candidateId":candidate,"candidateReady":false,"phase":record["phase"],
|
||||
"retired":!record["retirement"].is_null(),"candidateSlotId":record["binding"]["slotId"]}));
|
||||
}
|
||||
}
|
||||
let references = generation_references_for_output(&dir, &state, &variant_id, component)?;
|
||||
let mut images = Vec::new();
|
||||
let reference_limit = if state["productTemplates"].is_object() { 8 } else { 3 };
|
||||
let originals: Vec<_> = references.as_array().into_iter().flatten()
|
||||
.filter(|row| row["purpose"] == "product").take(reference_limit).collect();
|
||||
if let Some(request) = target.get("cropPreview").filter(|value| !value.is_null()) {
|
||||
if !state["productTemplates"].is_object() || !request.is_object() || !target["candidateId"].is_null() {
|
||||
return Err("当前图位无法预览同款原片局部".into());
|
||||
}
|
||||
let index = request["referenceIndex"].as_u64().filter(|index| *index < reference_limit as u64)
|
||||
.ok_or("同款原图编号无效")? as usize;
|
||||
let original = originals.get(index).ok_or("当前花色没有该同款原图。用 read_slot_images 查看当前图位的 productReferences,从清单中选择 reference(如 P01)。")?;
|
||||
let frame = slot_frame(field, mapped_slot(&state, slot, &variant_id)).ok_or("找不到实际图框")?;
|
||||
let crop_mode = product_crop_mode(&state, output, field)?;
|
||||
let inside = matches!(crop_mode, Some("inside" | "cover"));
|
||||
let region = &request["referenceCrop"];
|
||||
let image = photocraft_codecs::decode(&local_product_photo(&dir, original)?).map_err(|_| "产品原图无法解码")?;
|
||||
let dimensions = image.dimensions();
|
||||
let bounds = product_crop_pixels(region, dimensions, frame, inside)?;
|
||||
let crop = crop_product_image(&image, bounds)?;
|
||||
let preview = cover_review_preview(super::images::agent_color_preview(crop), frame)?;
|
||||
let guide = outline_crop(super::images::agent_color_preview(image), dimensions, bounds);
|
||||
let [x0, y0, x1, y1] = bounds;
|
||||
let (w, h) = dimensions;
|
||||
let applied = [x0*1000/w, y0*1000/h, (x1*1000).div_ceil(w), (y1*1000).div_ceil(h)];
|
||||
return Ok(json!({
|
||||
"referenceIndex":index,"referenceCrop":region,"appliedReferenceCrop":applied,"frame":frame,
|
||||
"hasSwatchBackdrop":(crop_mode == Some("inside")).then(||swatch_has_white_backdrop(&preview)),
|
||||
"sourceCropGuide":{"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&guide,512)?,"mimeType":"image/jpeg"},
|
||||
"images":[{"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"}],
|
||||
}));
|
||||
}
|
||||
let include_product = target["includeProductReferences"] != false;
|
||||
if include_product {
|
||||
for image in &originals {
|
||||
let bytes = local_product_photo(&dir, image)?;
|
||||
let preview = super::images::decode_agent_image(&bytes)?;
|
||||
images.push(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"}));
|
||||
}
|
||||
}
|
||||
let reference_count = images.len();
|
||||
let reference_binding = |image: &Value| {
|
||||
let mut binding = json!({});
|
||||
for key in ["name","purpose","imageRole","fieldKey","barcode"] {
|
||||
if let Some(value) = image.get(key) { binding[key] = value.clone(); }
|
||||
}
|
||||
binding
|
||||
};
|
||||
let reference_bindings: Vec<_> = if include_product {
|
||||
originals.iter().enumerate().map(|(index, image)| {
|
||||
let mut binding = reference_binding(image);
|
||||
binding["reference"] = json!(format!("P{:02}", index + 1));
|
||||
binding
|
||||
}).collect()
|
||||
} else { Vec::new() };
|
||||
let mut supplemental = Vec::new();
|
||||
let mut supplemental_bindings = Vec::new();
|
||||
if include_product && candidate_record.is_none() && target["originalsOnly"] != true {
|
||||
for image in references.as_array().into_iter().flatten().filter(|image| image["purpose"] == "scene" && image["imageRole"].is_string()) {
|
||||
let bytes = local_product_photo(&dir, image)?;
|
||||
let preview = super::images::decode_agent_image(&bytes)?;
|
||||
supplemental.push(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"}));
|
||||
supplemental_bindings.push(reference_binding(image));
|
||||
}
|
||||
}
|
||||
let candidate_prompt = candidate_record.as_ref().map(|record| record["prompt"].clone());
|
||||
let is_production_review = state["productTemplates"].is_object() && candidate_record.is_some();
|
||||
let template_base = candidate_record.as_ref().is_some_and(|record| record["templateBase"] == true);
|
||||
let cropped_candidate = state["template"]["enterprise"].is_object() && candidate_record.as_ref().is_some_and(|record| {
|
||||
let crop = &record["canvasTransform"]["transform"]["crop"];
|
||||
crop.is_array() && *crop != json!([0,0,1000,1000])
|
||||
});
|
||||
let fixed_layout = target["originalsOnly"] != true && (template_base || cropped_candidate);
|
||||
let layout = if fixed_layout && template_base {
|
||||
let id = candidate_id.ok_or("候选编号缺失")?;
|
||||
super::images::read_image_request(&dir, id)
|
||||
.and_then(|task| super::images::verified_reference_at(&task["references"][0]))
|
||||
.map(Some)
|
||||
} else if fixed_layout {
|
||||
let original = json!({"templateHash":state["template"]["contentHash"],"component":output["component"],
|
||||
"documentId":output["id"],"variantId":variant_id,"fieldId":field["fieldId"]});
|
||||
let frame = slot_frame(field, mapped_slot(&state, slot, &variant_id)).ok_or("当前图位缺少实际图框")?;
|
||||
self.template_edit_pixels(&dir, &original, frame).map(Some)
|
||||
} else if target["originalsOnly"] == true || target["includeTemplateReference"] == false {
|
||||
Ok(None)
|
||||
} else if is_production_review {
|
||||
if candidate_record.as_ref().is_some_and(|record| record["sourceType"] != "product-reference") {
|
||||
self.cached_detail_layout_bytes(field)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
self.detail_layout_bytes(field)
|
||||
};
|
||||
let (layout_preview, layout_issue) = match layout.and_then(|bytes|
|
||||
bytes.as_deref().map(super::images::decode_agent_image).transpose())
|
||||
{
|
||||
Ok(preview) => (preview, None),
|
||||
Err(error) => (None, Some(error)),
|
||||
};
|
||||
let layout_count = if let Some(preview) = layout_preview {
|
||||
images.push(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"}));
|
||||
1
|
||||
} else { 0 };
|
||||
let mut original_reference_index = None;
|
||||
let mut review_frame = &field["frame"];
|
||||
let mut ground_contact_detail = None;
|
||||
let mut action_review_detail = None;
|
||||
let mut scene_edge_details = Vec::new();
|
||||
let text_regions = slot_text_regions(&state, slot, &variant_id);
|
||||
let mut candidate_original = None;
|
||||
let mut candidate_file = None;
|
||||
if let Some((candidate, record)) = candidate_id.zip(candidate_record) {
|
||||
let inspect_ground = is_production_review && target["groundContactDetail"] == true;
|
||||
let inspect_edges = is_production_review && target["sceneEdgeDetails"] == true;
|
||||
let action_region: Option<[u8; 4]> = if is_production_review && !target["actionReviewRegion"].is_null() {
|
||||
Some(serde_json::from_value(target["actionReviewRegion"].clone()).map_err(|_| "验图局部坐标无效")?)
|
||||
} else { None };
|
||||
let source = self.agent_image_source(&json!({"doc":doc,"taskId":candidate}));
|
||||
let raw_candidate = target["candidatePixels"] == true;
|
||||
let raster = if !raw_candidate && adopted_canvas.is_some() && record["sourceType"] == "product-reference" {
|
||||
source.ok().map(|(_, raster)| raster)
|
||||
} else {
|
||||
Some(source?.1)
|
||||
};
|
||||
let inspect_original = target["includeCandidateOriginal"] == true && adopted_canvas.is_none();
|
||||
candidate_file = raster.as_ref().map(|image| {
|
||||
let mut file = json!({"width":image.width(),"height":image.height(),"hasTransparency":image.has_translucency()});
|
||||
if inspect_original { file["sha256"] = record["artifact"]["sha256"].clone(); }
|
||||
file
|
||||
});
|
||||
let mut preview = if let Some(canvas) = adopted_canvas {
|
||||
if !is_production_review || (!scoped && canvas.id.0 != doc) { return Err("当前画布不属于已回填候选的复验项目".into()); }
|
||||
let mapped = mapped_slot(&state, slot, &variant_id).ok_or("已回填图位没有当前模板映射")?;
|
||||
if raw_candidate {
|
||||
verify_adopted_source(&dir, canvas, mapped, &record["artifact"])?;
|
||||
super::images::agent_color_preview(raster.ok_or("候选原文件不可读取")?)
|
||||
} else {
|
||||
adopted_review_image(&dir, canvas, mapped, &record["artifact"],
|
||||
if inspect_ground || inspect_edges || action_region.is_some() { 1536 } else { 768 })?
|
||||
}
|
||||
} else {
|
||||
let pixels = raster.ok_or("候选原文件不可读取")?;
|
||||
super::images::agent_color_preview(pixels)
|
||||
};
|
||||
if inspect_original {
|
||||
candidate_original = Some(json!({"type":"image",
|
||||
"data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,1024)?,"mimeType":"image/jpeg"}));
|
||||
}
|
||||
if is_production_review {
|
||||
review_frame = slot_frame(field, mapped_slot(&state, slot, &variant_id))
|
||||
.ok_or("候选缺少当前图位的实际图框")?;
|
||||
if !raw_candidate && adopted_canvas.is_none() && (record["sourceType"] != "product-reference" || record["binding"]["referenceCrop"].is_array()) {
|
||||
preview = cover_review_preview(preview, review_frame)?;
|
||||
} else if !raw_candidate && adopted_canvas.is_none() && production_profile::select(&state["template"], output["component"].as_str().unwrap_or_default())?
|
||||
.and_then(|profile| profile["imageRules"].get(field["fieldId"].as_str()?))
|
||||
.is_some_and(|rule| rule["structureGuides"].is_object()) {
|
||||
preview = contain_review_preview(preview, review_frame)?;
|
||||
}
|
||||
}
|
||||
if inspect_ground {
|
||||
ground_contact_detail = Some(review_region_preview(&preview, [0, 40, 100, 100])?);
|
||||
}
|
||||
if inspect_edges {
|
||||
scene_edge_details.push(review_region_preview(&preview, [0, 0, 24, 100])?);
|
||||
scene_edge_details.push(review_region_preview(&preview, [76, 0, 100, 100])?);
|
||||
}
|
||||
if let Some(bounds) = action_region {
|
||||
action_review_detail = Some(review_region_preview(&preview, bounds)?);
|
||||
}
|
||||
images.push(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,768)?,"mimeType":"image/jpeg"}));
|
||||
if record["sourceType"] == "product-reference" {
|
||||
original_reference_index = originals.iter().position(|image| image["source"] == record["references"][0]["source"]);
|
||||
}
|
||||
}
|
||||
let mapping = cached_prompt_mapping(&dir, &state["template"]);
|
||||
let aspect = specified_image_ratio(field).map(|(w,h)| format!("{w}:{h}"));
|
||||
images.extend(supplemental);
|
||||
Ok(json!({"images":images,"referenceCount":reference_count,"layoutCount":layout_count,"layoutIssue":layout_issue,
|
||||
"referenceBindings":reference_bindings,"supplementalBindings":supplemental_bindings,
|
||||
"layoutSource":(fixed_layout && layout_count>0).then_some("pinnedTemplateOriginal"),
|
||||
"relatedCopy":target["relatedCopy"],"adopted":adopted_canvas.is_some(),
|
||||
"outputId":target["outputId"],"variantId":variant_id,
|
||||
"textRegions":text_regions,
|
||||
"candidateFile":candidate_file,"candidateOriginal":candidate_original,"candidatePrompt":candidate_prompt,
|
||||
"originalReferenceIndex":original_reference_index,
|
||||
"groundContactDetail":ground_contact_detail,"actionReviewDetail":action_review_detail,
|
||||
"sceneEdgeDetails":scene_edge_details,
|
||||
"role":field["role"],"requirements":field["requirements"],"aspectRatio":aspect,"frame":review_frame,"outputSpec":field["outputSpec"],"prompt":editable_image_prompt(field,&output["id"],mapping.as_ref()),"candidateId":target["candidateId"],
|
||||
"brief":{"name":state["brief"]["name"],"note":state["brief"]["note"],"color":variant(&state,&variant_id)?["colorName"],
|
||||
"dimensions":variant(&state,&variant_id)?["dimensions"]}}))
|
||||
}
|
||||
|
||||
pub(crate) fn pinned_template_layer(&self, dir: &Path, target: &Value) -> R<(Document, photocraft_doc::LayerId, Value, Value)> {
|
||||
let state = load(dir)?;
|
||||
let component = target["component"].as_str().ok_or("模板组件缺失")?;
|
||||
let pack = state["productTemplates"].get(component).unwrap_or(&state["template"]);
|
||||
if !pack["enterprise"].is_object() || target["templateHash"] != pack["contentHash"] {
|
||||
return Err("当前项目的固定模板原图不可用".into());
|
||||
}
|
||||
let variant_id = target["variantId"].as_str().ok_or("原稿图位花色缺失")?;
|
||||
variant(&state, variant_id)?;
|
||||
let document = if component == "detail" { None } else { target["documentId"].as_str() };
|
||||
let original = self.enterprise_template_canvas(pack, component, document, variant_id, |_| {})?;
|
||||
let meta = mapping(&original).ok_or("固定原稿缺少图位映射")?;
|
||||
let field = page_fields(&meta).flat_map(|(_, fields)| fields)
|
||||
.find(|field| field["fieldId"] == target["fieldId"] && field["kind"] == "image")
|
||||
.ok_or("指定图位在固定原稿里缺少可读图层")?;
|
||||
let id = field["nativeLayerId"].as_u64().ok_or("指定图位在原稿中没有图层身份")?;
|
||||
let field = field.clone();
|
||||
Ok((original, photocraft_doc::LayerId(id), field, pack["version"].clone()))
|
||||
}
|
||||
|
||||
pub(crate) fn read_pinned_template_image(&self, dir: &Path, target: &Value) -> R<Value> {
|
||||
let (original, id, field, version) = self.pinned_template_layer(dir, target)?;
|
||||
let image = photocraft_ui_egui::jiansun::template_layer_jpeg(&original, id)?;
|
||||
Ok(json!({"source":"pinnedTemplateOriginal","fieldId":field["fieldId"],"label":field["label"],
|
||||
"templateVersion":version,"images":[{"type":"image","data":image,"mimeType":"image/jpeg"}]}))
|
||||
}
|
||||
|
||||
pub(crate) fn template_edit_pixels(&self, dir: &Path, target: &Value, frame: &Value) -> R<Vec<u8>> {
|
||||
let (original, id, field, _) = self.pinned_template_layer(dir, target)?;
|
||||
render_template_edit(original, id, &field["frame"], frame)
|
||||
}
|
||||
|
||||
pub(crate) fn repair_template_ending(&self, dir: &Path, doc: &mut Document, progress: impl FnMut(Value)) -> R<Vec<String>> {
|
||||
let missing = missing_ending_pages(doc);
|
||||
if missing.is_empty() { return Ok(missing); }
|
||||
let state = load(dir)?;
|
||||
let meta = mapping(doc).ok_or("现有画布图位映射缺失")?;
|
||||
let pack = state["productTemplates"].get("detail").unwrap_or(&state["template"]);
|
||||
if meta["workspaceId"] != state["id"] || meta["templateHash"] != pack["contentHash"] {
|
||||
return Err("固定原稿与当前项目不一致,未改动画布".into());
|
||||
}
|
||||
let variant = meta["variantId"].as_str().ok_or("保存的画布花色缺失")?;
|
||||
let original = self.enterprise_template_canvas(pack, "detail", None, variant, progress)?;
|
||||
merge_missing_ending(doc, original, &meta)?;
|
||||
Ok(missing)
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,602 @@
|
||||
use super::super::{Digest, Arc, Backend, Document, Path, PathBuf, R, Sha256, Value, creation, fs, hash, json, load_draft, original_project_present, production_profile, read_json, sync, write_json};
|
||||
use super::{DELIVERY_REOPEN_MISMATCH, SUPPORTED_PRODUCTION_OUTPUTS, candidate_available, candidate_pixels, candidate_uses_current_inputs, checked_binding, document_mapping_key, exists, load, load_detail_workspace, mapped_fields, mapping, mapping_key, output_state_inner, output_variant, persist_locked, read_candidate, records, retired_archive, revision, snapshot, specified_image_ratio, uuid, variant, variant_input_hash, variants};
|
||||
|
||||
pub(crate) fn acknowledge_adoption(dir: &Path, state: &Value, input: &Value) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
original_project_present(dir)?;
|
||||
let adoption = uuid(&input["adoptionId"], "采纳")?;
|
||||
let file = dir.join("template-outputs").join(format!("canvas-adoption-{adoption}.json"));
|
||||
let mut audit = read_json(&file)?;
|
||||
for key in [
|
||||
"candidateId",
|
||||
"sourceCandidateId",
|
||||
"manualAdoption",
|
||||
"slotId",
|
||||
"variantId",
|
||||
"nativeLayerId",
|
||||
"baseRevision",
|
||||
"doc",
|
||||
"accountId",
|
||||
"origin",
|
||||
"workspaceId",
|
||||
"templateHash",
|
||||
"structureHash",
|
||||
"adoptionId",
|
||||
"workflowOperationId",
|
||||
"workflowRun",
|
||||
"sha256",
|
||||
] {
|
||||
if audit["meta"][key] != input[key] {
|
||||
return Err("采纳回执与原生事务、项目或像素身份不一致".into());
|
||||
}
|
||||
}
|
||||
let before = input["beforeRevision"].as_u64();
|
||||
let prepared = audit["meta"]["baseRevision"].as_u64();
|
||||
let accepted_base = if audit["meta"]["detailBatch"] == true || audit["meta"]["manualAdoption"] == true {
|
||||
before.zip(prepared).is_some_and(|(before, prepared)| before >= prepared)
|
||||
} else { before == prepared };
|
||||
if audit["meta"]["workspaceId"] != state["id"]
|
||||
|| input["afterRevision"].as_u64().zip(before).is_none_or(|(a, b)| b.checked_add(1) != Some(a))
|
||||
|| !accepted_base
|
||||
{
|
||||
return Err("原生采纳修订回执无效".into());
|
||||
}
|
||||
if audit["phase"] != "acknowledged" {
|
||||
if audit["phase"] != "prepared" {
|
||||
return Err("采纳准备记录无效".into());
|
||||
}
|
||||
audit["phase"] = json!("acknowledged");
|
||||
audit["revision"] = input["afterRevision"].clone();
|
||||
write_json(&file, &audit)?;
|
||||
} else if audit["revision"] != input["afterRevision"] {
|
||||
return Err("采纳回执修订不一致,未覆盖原记录".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn enrich_creation(dir: &Path, mut creation: Value) -> R<Value> {
|
||||
if exists(dir) {
|
||||
let state = load(dir)?;
|
||||
if creation["brief"].get("variants").is_none_or(|rows| rows.as_array().is_some_and(Vec::is_empty)) {
|
||||
// Empty selections in older canvas briefs predate the canonical
|
||||
// default colour. Recover its existing identity, never invent one.
|
||||
creation["brief"]["variants"] = state["variants"].clone();
|
||||
}
|
||||
if creation["brief"].get("templateSelection").is_none() {
|
||||
creation["brief"]["templateSelection"] = json!({"id":state["template"]["id"],"version":state["template"]["version"],"contentHash":state["template"]["contentHash"],"name":state["template"]["name"],"brandId":state["template"]["brandId"],"categoryId":state["template"]["categoryId"]});
|
||||
}
|
||||
}
|
||||
Ok(creation)
|
||||
}
|
||||
pub(crate) fn reuse_saved_product_view(dir: &Path, doc: &Document) -> R<bool> {
|
||||
let Some(meta) = mapping(doc) else { return Ok(false); };
|
||||
let variant = uuid(&meta["variantId"], "编辑稿花色")?;
|
||||
let component = meta["component"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id)).ok_or("当前画布类型缺失")?;
|
||||
let key = mapping_key(&variant, component, meta["outputId"].as_str());
|
||||
let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
if !file.is_file() { return Ok(false); }
|
||||
let staged = tempfile::tempdir_in(dir).map_err(|_| "无法保存当前输出记录")?;
|
||||
let link = staged.path().join("canvas.pcraft");
|
||||
if fs::hard_link(&file, &link).is_err() { return Ok(false); }
|
||||
let canonical = dir.join("canvas.pcraft");
|
||||
photocraft_format::atomic::retry_rename(photocraft_format::atomic::RenameRetry::platform(), || fs::rename(&link, &canonical))
|
||||
.map_err(|_| "无法切换已保存的当前输出")?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn save_edited_output(dir: &Path, doc: &Document, bytes: &[u8]) -> R<bool> {
|
||||
let Some(meta) = mapping(doc) else { return Ok(false) };
|
||||
let state = load(dir)?;
|
||||
let variant_id = uuid(&meta["variantId"], "编辑稿花色")?;
|
||||
variant(&state, &variant_id)?;
|
||||
let component = meta["component"].as_str().filter(|component| matches!(*component, "detail" | "main_images" | "sku_images")).ok_or("编辑稿输出类型缺失")?;
|
||||
let pack = state["productTemplates"].get(component).unwrap_or(&state["template"]);
|
||||
if meta["workspaceId"] != state["id"] || meta["templateHash"] != pack["contentHash"] {
|
||||
return Err("原生画布模板身份已变化,未覆盖编辑稿".into());
|
||||
}
|
||||
let key = mapping_key(&variant_id, component, meta["outputId"].as_str());
|
||||
photocraft_format::atomic_write(&dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")), bytes)
|
||||
.map_err(|_| "画布编辑稿保存失败,请保留原稿")?;
|
||||
write_json(&dir.join("template-outputs").join(format!("canvas-{key}-edited.json")), &meta)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn verify_saved_output(dir: &Path, doc: &Document, digest: &str) -> R<()> {
|
||||
let meta = mapping(doc).ok_or("编辑稿输出映射缺失")?;
|
||||
let key = document_mapping_key(&meta)?;
|
||||
let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
if !file_digest(&file).is_ok_and(|actual| actual == digest) {
|
||||
return Err("当前输出的编辑稿已变化,请重新保存".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn activate_edited_output(dir: &Path, doc: &Document) -> R<Value> {
|
||||
activate_edited_output_with_knowledge(dir, doc, &Value::Null, true)
|
||||
}
|
||||
|
||||
pub(crate) fn apply_locked_production_profiles(state: &mut Value, knowledge: &Value) -> R<()> {
|
||||
if knowledge.is_null() { return Ok(()); }
|
||||
let id = knowledge["templateId"].as_str().ok_or("小壹知识包模板编号缺失")?;
|
||||
knowledge["knowledgeVersion"].as_str().ok_or("小壹知识版本缺失")?;
|
||||
knowledge["productionProfiles"].as_object().ok_or("小壹制作配置缺失")?;
|
||||
if state["template"]["id"] != id {
|
||||
return Err("小壹知识包与项目模板编号不一致".into());
|
||||
}
|
||||
if let Some(packs) = state["productTemplates"].as_object_mut() {
|
||||
for pack in packs.values_mut().filter(|pack| pack["id"] == id) {
|
||||
pack["xiaoyi"] = knowledge.clone();
|
||||
}
|
||||
}
|
||||
state["template"]["xiaoyi"] = knowledge.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn product_view_variant<'a>(state: &'a Value, component: &str, requested: Option<&'a str>) -> R<&'a str> {
|
||||
// Empty lists in older projects can still be viewed and saved. Production
|
||||
// eligibility remains governed by the selected colors and detail barcode.
|
||||
if state["brief"]["outputVariantIds"][component].as_array().is_some_and(Vec::is_empty)
|
||||
&& !(component == "detail" && creation::detail_barcode(&state["brief"]).is_some())
|
||||
{
|
||||
let id = requested.or_else(|| state["activeVariantId"].as_str()).ok_or("当前花色缺失")?;
|
||||
variant(state, id)?;
|
||||
return Ok(id);
|
||||
}
|
||||
output_variant(state, component, requested)
|
||||
}
|
||||
|
||||
pub(crate) fn activate_edited_output_with_knowledge(dir: &Path, doc: &Document, knowledge: &Value, viewing: bool) -> R<Value> {
|
||||
let mut state = load(dir)?;
|
||||
apply_locked_production_profiles(&mut state, knowledge)?;
|
||||
let meta = mapping(doc).ok_or("当前画布没有产品模板映射")?;
|
||||
let component = meta["component"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id)).ok_or("当前画布类型缺失")?;
|
||||
let pack = state["productTemplates"].get(component).ok_or("当前产品模板已变化")?.clone();
|
||||
let variant_id = uuid(&meta["variantId"], "编辑稿花色")?;
|
||||
let selected = if viewing { product_view_variant } else { output_variant };
|
||||
if meta["workspaceId"] != state["id"] || meta["templateHash"] != pack["contentHash"]
|
||||
|| selected(&state, component, Some(&variant_id)).is_err() {
|
||||
return Err("当前产品画布不属于所选输出".into());
|
||||
}
|
||||
let key = mapping_key(&variant_id, component, meta["outputId"].as_str());
|
||||
state["activeVariantId"] = json!(variant_id);
|
||||
state["activeOutput"] = json!(component);
|
||||
state["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string()));
|
||||
state["template"] = pack;
|
||||
state["activeMapping"] = json!(key);
|
||||
if let Some(issues) = state["productTemplateIssues"].as_object_mut() {
|
||||
issues.remove(component);
|
||||
}
|
||||
state["mappings"][&key] = meta;
|
||||
let expected = revision(&state);
|
||||
persist_locked(dir, &mut state, expected)
|
||||
}
|
||||
|
||||
pub(crate) fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf {
|
||||
dir.join("product-exports").join(variant).join(format!("{component}.json"))
|
||||
}
|
||||
|
||||
pub(crate) fn manifest_path(generation: &str) -> PathBuf {
|
||||
Path::new("generations").join(generation).join("manifest.json")
|
||||
}
|
||||
|
||||
pub(crate) fn published_receipt(path: &Path) -> R<Value> {
|
||||
let pointer = read_json(path)?;
|
||||
if pointer["reopenVerification"]["consistent"] == false {
|
||||
return Err(DELIVERY_REOPEN_MISMATCH.into());
|
||||
}
|
||||
if pointer.get("publishedPointer").is_none() {
|
||||
return Ok(pointer);
|
||||
}
|
||||
let id = pointer["generationId"].as_str().ok_or("交付版本缺失")?;
|
||||
let manifest = manifest_path(id);
|
||||
if !id.starts_with("generation-") || Path::new(id).components().count() != 1
|
||||
|| pointer["publishedPointer"] != json!(manifest)
|
||||
{
|
||||
return Err("交付指针无效".into());
|
||||
}
|
||||
let mut manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?;
|
||||
if manifest["reopenVerification"]["consistent"] == false {
|
||||
return Err(DELIVERY_REOPEN_MISMATCH.into());
|
||||
}
|
||||
if ["generationId", "workspaceId", "outputId", "variantId"].iter()
|
||||
.any(|field| manifest[*field] != pointer[*field])
|
||||
{
|
||||
return Err("交付清单与发布指针不一致".into());
|
||||
}
|
||||
if pointer["reusedGeneration"] == true {
|
||||
for field in ["documentKey", "canvasRevision", "operationId", "deliveryInputHash", "briefRevision",
|
||||
"productionProfile", "fidelityReport", "knownIssues", "issues", "slotCoverage", "missingImages",
|
||||
"missingSlots", "unreviewedScreens", "missingVisibleText", "visibleSampleLayer",
|
||||
"unapprovedFixedTextLayer", "unapprovedFixedTextLayerId", "visibleSampleLayerId", "reviewHints",
|
||||
"unverifiedCopy", "unverifiedFacts", "blankCopyReasons",
|
||||
"warnings", "missingFonts", "allOutputsCompleted", "deliveryStatus"] {
|
||||
if let Some(value) = pointer.get(field) {
|
||||
manifest[field] = value.clone();
|
||||
} else {
|
||||
manifest.as_object_mut().unwrap().remove(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub(crate) fn template_screen_regions<'a>(pages: impl IntoIterator<Item = &'a Value>) -> R<Vec<(u64, u64, u64)>> {
|
||||
let mut regions = Vec::new();
|
||||
for page in pages {
|
||||
let top = page["top"].as_u64().ok_or("模板屏的纵坐标无效")?;
|
||||
let width = page["width"].as_u64().filter(|&n| n > 0).ok_or("模板屏宽度无效")?;
|
||||
let height = page["height"].as_u64().filter(|&n| n > 0).ok_or("模板屏高度无效")?;
|
||||
top.checked_add(height).ok_or("模板屏下边界无效")?;
|
||||
regions.push((top, width, height));
|
||||
}
|
||||
if regions.is_empty() { return Err("没有可导出的画布页面".into()); }
|
||||
Ok(regions)
|
||||
}
|
||||
|
||||
pub(crate) fn production_settings_path(dir: &Path) -> Option<PathBuf> {
|
||||
match (dir.file_name(), dir.parent().and_then(Path::parent).and_then(Path::file_name)) {
|
||||
(Some(project), Some(account)) => {
|
||||
Some(dir.join("agent").join(account).join(project).join("production-settings.json"))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read_production_settings(dir: &Path) -> R<Value> {
|
||||
if let Some(file) = production_settings_path(dir)
|
||||
&& file.try_exists().map_err(|error| error.to_string())? {
|
||||
return read_json(&file);
|
||||
}
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
pub(crate) fn production_settings_facts(settings: &Value, profile: &Value) -> Value {
|
||||
let refinement = settings["refinement"] == true;
|
||||
let mode = if refinement { "fine" } else { "fast" };
|
||||
let minutes = settings["timeBudgetMinutes"].as_f64().or_else(|| profile["timeBudgetMinutes"][mode].as_f64())
|
||||
.filter(|minutes| minutes.is_finite() && *minutes > 0.0)
|
||||
.unwrap_or(if refinement { 120.0 } else { 45.0 });
|
||||
json!({"refinement":refinement,"timeBudgetMinutes":minutes})
|
||||
}
|
||||
|
||||
pub(crate) fn save_production_settings(dir: &Path, refinement: bool) -> R<Value> {
|
||||
let state = if exists(dir) { load_detail_workspace(dir)? } else { Value::Null };
|
||||
let profile = production_profile::select(&state["template"], state["activeOutput"].as_str().unwrap_or("detail"))?
|
||||
.unwrap_or(&Value::Null);
|
||||
let facts = production_settings_facts(&json!({"refinement":refinement}), profile);
|
||||
let mut settings = read_production_settings(dir)?;
|
||||
settings["refinement"] = facts["refinement"].clone();
|
||||
settings["timeBudgetMinutes"] = facts["timeBudgetMinutes"].clone();
|
||||
write_json(&production_settings_path(dir).ok_or("当前项目路径无效")?, &settings)?;
|
||||
Ok(facts)
|
||||
}
|
||||
|
||||
pub(crate) fn main_image_aspects(dir: &Path, pack: &Value, component: &str) -> R<Value> {
|
||||
if component != "main_images" { return Ok(Value::Null); }
|
||||
let profile = production_profile::select(pack, component)?;
|
||||
let settings = read_production_settings(dir)?;
|
||||
Ok(settings.get("mainImageAspects").or_else(|| profile.and_then(|profile| profile.get("mainImageAspects")))
|
||||
.cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(crate) fn field_uses_aspect(field: &Value, aspects: &Value) -> bool {
|
||||
aspects.as_array().is_none_or(|aspects| specified_image_ratio(field).is_some_and(|(w, h)|
|
||||
aspects.contains(&json!(format!("{w}:{h}")))))
|
||||
}
|
||||
|
||||
pub(crate) fn production_export_pages<'a>(pack: &'a Value, component: &'a str, aspects: &'a Value) -> impl Iterator<Item = &'a Value> {
|
||||
pack["outputs"].as_array().into_iter().flatten().filter(move |page|
|
||||
page["component"] == component && (aspects.is_null() || page["slots"].as_array().into_iter().flatten()
|
||||
.any(|field| field["kind"] == "image" && field_uses_aspect(field, aspects))))
|
||||
}
|
||||
|
||||
pub(crate) fn product_export_regions<'a>(
|
||||
pages: impl IntoIterator<Item = &'a Value>, component: &str,
|
||||
) -> R<Vec<(u64, u64, u64)>> {
|
||||
let regions = template_screen_regions(pages)?;
|
||||
if component != "detail" { return Ok(regions); }
|
||||
let width = regions.iter().map(|&(_, width, _)| width).max().unwrap_or(0);
|
||||
let bottom = regions.iter().map(|&(top, _, height)| top + height).max().unwrap_or(0);
|
||||
Ok(vec![(0, width, bottom)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) fn product_exports_keep_the_last_registered_screen_and_split_other_outputs() {
|
||||
let screens = [
|
||||
json!({"top":0,"width":1440,"height":2126}),
|
||||
json!({"top":25024,"width":1440,"height":1918,"slots":[]}),
|
||||
];
|
||||
assert_eq!(product_export_regions(&screens, "detail").unwrap(), [(0, 1440, 26942)]);
|
||||
assert_eq!(template_screen_regions(&screens).unwrap(), [(0, 1440, 2126), (25024, 1440, 1918)]);
|
||||
assert_eq!(product_export_regions(&screens, "main_images").unwrap(),
|
||||
[(0, 1440, 2126), (25024, 1440, 1918)]);
|
||||
assert!(product_export_regions(&[json!({"top":u64::MAX,"width":1,"height":1})], "detail").is_err());
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn provisional_slot(&self, doc: Arc<Document>, input: &Value) -> R<photocraft_doc::Layer> {
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
use photocraft_engine::smart_cmds;
|
||||
let id = doc.id.0;
|
||||
self.ensure_owner(id)?;
|
||||
if input["doc"].as_u64() != Some(id) { return Err("预览项目已切换".into()); }
|
||||
let dir = self.project_dir(id)?;
|
||||
let candidate = uuid(&input["candidateId"], "候选预览")?;
|
||||
let record = read_candidate(&dir, &candidate)?;
|
||||
let binding = &record["binding"];
|
||||
let (state, _) = checked_binding(&dir, binding, true)?;
|
||||
let canvas = mapping(&doc).ok_or("预览画布没有图位映射")?;
|
||||
let component = canvas["component"].as_str().ok_or("预览画布缺少输出类型")?;
|
||||
let variant = canvas["variantId"].as_str().ok_or("预览花色缺失")?;
|
||||
let slot = input["slotId"].as_str().ok_or("预览图位缺失")?;
|
||||
let layer_id = LayerId(input["nativeLayerId"].as_u64().ok_or("预览图层缺失")?);
|
||||
let state = if state["productTemplates"][component].is_object()
|
||||
&& (state["activeOutput"] != component || state["activeVariantId"] != variant)
|
||||
{
|
||||
output_state_inner(state, component, variant, false)?
|
||||
} else { state };
|
||||
if state["template"]["contentHash"] != canvas["templateHash"]
|
||||
|| state["structureHash"] != binding["structureHash"] {
|
||||
return Err("预览模板已切换".into());
|
||||
}
|
||||
let key = mapping_key(variant, component, canvas["documentId"].as_str());
|
||||
let mapped = mapped_fields(&state["mappings"][&key]).find(|field| field["slotId"] == slot)
|
||||
.ok_or("预览图位不存在")?;
|
||||
if !candidate_available(&record) || record["sourceType"].is_string()
|
||||
|| binding["slotId"] != slot || binding["variantId"] != variant
|
||||
|| binding["templateHash"] != canvas["templateHash"] || binding["workspaceId"] != canvas["workspaceId"]
|
||||
|| binding["fieldId"] != mapped["fieldId"] || mapped["nativeLayerId"].as_u64() != Some(layer_id.0)
|
||||
|| !candidate_uses_current_inputs(&dir, &state, &record, variant)?
|
||||
{
|
||||
return Err("候选和预览图位不一致".into());
|
||||
}
|
||||
let before = doc.layer(layer_id).ok_or("预览图层不存在")?;
|
||||
let LayerContent::Smart(smart) = &before.content else { return Err("预览图位不是智能图层".into()); };
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(doc.as_ref().clone(), None);
|
||||
let original = if before.vector_mask.as_ref().is_some_and(|mask| mask.enabled) {
|
||||
None
|
||||
} else {
|
||||
let revision = session.active().ok_or("预览画布缺失")?.revision;
|
||||
let source = smart_cmds::freeze_source(&session, doc.id, revision, layer_id, smart.contents_id)
|
||||
.and_then(|ticket| ticket.read()).map_err(|error| error.to_string())?;
|
||||
Some(smart_cmds::prepare_bounded_source(&source.file_name, source.bytes).map_err(|error| error.to_string())?)
|
||||
};
|
||||
let bytes = candidate_pixels(&dir, &record["artifact"])?;
|
||||
let (bytes, _) = placement_pixels(bytes)?;
|
||||
let source = smart_cmds::prepare_bounded_source("candidate.png", Arc::new(bytes)).map_err(|error| error.to_string())?;
|
||||
smart_cmds::replace_instance_bounded_fit(&mut session, layer_id, original.as_ref(), &source, false)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut preview = session.active().and_then(|state| state.doc.layer(layer_id)).cloned().ok_or("候选预览无法准备")?;
|
||||
preview.visible = true;
|
||||
Ok(preview)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn matches_placed_candidate(dir: &Path, artifact: &Value, embedded: &[u8]) -> bool {
|
||||
if embedded.is_empty() { return false; }
|
||||
if artifact["sha256"] == format!("{:x}", Sha256::digest(embedded)) { return true; }
|
||||
// Large sources are reduced before placement. Only accept the exact pixels
|
||||
// produced by the normal placement path from the verified original candidate.
|
||||
candidate_pixels(dir, artifact).and_then(placement_pixels)
|
||||
.is_ok_and(|(prepared, sizing)| sizing.is_object() && prepared == embedded)
|
||||
}
|
||||
|
||||
pub(crate) fn placement_pixels(bytes: Vec<u8>) -> R<(Vec<u8>, Value)> {
|
||||
let (width, height) = creation::png_size(&bytes)?;
|
||||
let pixels = u64::from(width) * u64::from(height);
|
||||
let budget = photocraft_io::SMART_PREVIEW_MAX_PIXELS;
|
||||
if pixels <= budget { return Ok((bytes, Value::Null)); }
|
||||
let scale = (budget as f64 / pixels as f64).sqrt();
|
||||
let scaled = |edge: u32| ((f64::from(edge) * scale).floor() as u32).max(1);
|
||||
let (target_width,target_height) = (scaled(width),scaled(height));
|
||||
let source = photocraft_io::import("candidate.png", &bytes).map_err(|error| format!("候选图片无法打开:{error}"))?;
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(source.document, None);
|
||||
session.execute("image.imageSize", json!({"width":target_width,"height":target_height,"resample":"lanczos"}))
|
||||
.map_err(|error| format!("图位用图重采样失败:{error}"))?;
|
||||
let fitted = session.active().ok_or("图位工作图缺失")?;
|
||||
let options = photocraft_io::ExportOptions { xmp:photocraft_io::XmpEmbed::None, ..Default::default() };
|
||||
let png = photocraft_io::export(&fitted.doc, "png", &options).map_err(|error| format!("图位用图编码失败:{error}"))?;
|
||||
Ok((png.bytes, json!({"original":[width,height],"embedded":[target_width,target_height]})))
|
||||
}
|
||||
|
||||
pub(crate) fn artifact_matches(artifact: &Value, verify_hash: bool) -> bool {
|
||||
let Some(path) = artifact["path"].as_str().map(Path::new) else { return false };
|
||||
let Some(expected) = artifact["sha256"].as_str() else { return false };
|
||||
fs::metadata(path).is_ok_and(|meta| meta.is_file() && artifact["sizeBytes"].as_u64() == Some(meta.len()))
|
||||
&& (!verify_hash || file_digest(path).is_ok_and(|actual| actual == expected))
|
||||
}
|
||||
|
||||
pub(crate) fn file_digest(path: &Path) -> std::io::Result<String> {
|
||||
let mut file = fs::File::open(path)?;
|
||||
let mut sha = Sha256::new();
|
||||
std::io::copy(&mut file, &mut sha)?;
|
||||
Ok(format!("{:x}", sha.finalize()))
|
||||
}
|
||||
|
||||
pub(crate) fn export_files_present(files: &Value, regions: &[(u64, u64, u64)], generation: Option<&str>) -> bool {
|
||||
export_records_match(files, regions, generation) && files.as_array().is_some_and(|files|
|
||||
files.iter().all(|file| match generation {
|
||||
Some(_) => artifact_matches(file, true),
|
||||
None => file["path"].as_str().is_some_and(|path| Path::new(path).is_file()),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn export_records_match(files: &Value, regions: &[(u64, u64, u64)], generation: Option<&str>) -> bool {
|
||||
files.as_array().is_some_and(|files| files.len() == regions.len()
|
||||
&& files.iter().zip(regions).all(|(file, &(top, width, height))|
|
||||
file["width"].as_u64() == Some(width) && file["height"].as_u64() == Some(height)
|
||||
&& generation.is_none_or(|id| file["generationId"] == id && file["top"].as_u64() == Some(top))))
|
||||
}
|
||||
|
||||
pub(crate) fn production_audit(dir: &Path, state: &Value, component: &str, variant: &str, scope: &str) -> R<Value> {
|
||||
let project = dir.file_name().ok_or("本机项目身份缺失")?;
|
||||
let path = dir.join("agent").join(scope).join(project).join("conversation-v1")
|
||||
.join(format!("production-{component}-{variant}.json"));
|
||||
let audit = if path.is_file() { read_json(&path).unwrap_or_default() } else { Value::Null };
|
||||
let binding = json!([state["template"]["contentHash"], variant]).to_string();
|
||||
Ok(if audit["binding"] == binding { audit } else { Value::Null })
|
||||
}
|
||||
|
||||
pub(crate) fn approved_structure_guides(recipe: &Value, item: &Value, candidate: &str) -> R<Option<Value>> {
|
||||
let Some(recipe) = recipe.as_object().filter(|map| !map.is_empty()) else { return Ok(None) };
|
||||
let points_by_id = item["approvals"].as_array().into_iter().flatten()
|
||||
.find(|row| row["candidateId"] == candidate && row["decision"] == "pass")
|
||||
.and_then(|review| review["observation"]["structureGuides"].as_object());
|
||||
let Some(points_by_id) = points_by_id else { return Ok(None) };
|
||||
let mut guides = Vec::new();
|
||||
for (id, spec) in recipe {
|
||||
let Some(path) = points_by_id.get(id) else { continue };
|
||||
let kind = spec["kind"].as_str().unwrap_or("outline");
|
||||
let label = spec.as_str().or_else(|| spec["label"].as_str()).ok_or("标注名称缺失")?;
|
||||
let points: Vec<[u16; 2]> = serde_json::from_value(path.clone())
|
||||
.map_err(|_| "实物标注的取景坐标无效")?;
|
||||
let range = match kind {
|
||||
"measurement" => 2..=2,
|
||||
"leader" => 2..=3,
|
||||
"outline" => 2..=8,
|
||||
_ => return Err("模板实物标注类型无效".into()),
|
||||
};
|
||||
if !range.contains(&points.len()) || points.iter().flatten().any(|&value| value > 1000)
|
||||
|| points.iter().collect::<std::collections::HashSet<_>>().len() != points.len()
|
||||
{
|
||||
return Err("实物标注的取景坐标无效".into());
|
||||
}
|
||||
let mut guide = json!({"kind":kind,"label":label,"points":points});
|
||||
if let Some(style) = spec["styleLayerId"].as_u64() { guide["styleLayerId"] = json!(style); }
|
||||
guides.push(guide);
|
||||
}
|
||||
Ok(Some(json!(guides)))
|
||||
}
|
||||
|
||||
pub(crate) fn stage_input_hash(state: &Value, creation: &Value, variant: &str, component: &str) -> R<String> {
|
||||
let template = &state["productTemplates"][component]["contentHash"];
|
||||
let structure = json!(hash(&json!([template,state["width"]]).to_string()));
|
||||
let inputs = json!({"variant":variant_input_hash(state, creation, variant, component, template, &structure)?,
|
||||
"width":creation["width"],"screenCount":creation["screenCount"],
|
||||
"selected":creation["sellingPoints"]["selected"],"direction":creation["sellingPoints"]["direction"],
|
||||
"screens":creation["plan"]["screens"]});
|
||||
Ok(hash(&inputs.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) fn delivery_input_hash(state: &Value, creation: &Value, variant: &str, component: &str) -> R<String> {
|
||||
let mut inputs = creation.clone();
|
||||
if let Some(snapshot) = inputs["designSnapshot"].as_object_mut() {
|
||||
snapshot.remove("rules");
|
||||
if snapshot.is_empty() {
|
||||
inputs["designSnapshot"] = Value::Null;
|
||||
}
|
||||
}
|
||||
stage_input_hash(state, &inputs, variant, component)
|
||||
}
|
||||
|
||||
pub(crate) fn delivery_inputs_match(
|
||||
state: &Value, creation: &Value, variant: &str, component: &str, receipt: &Value,
|
||||
) -> bool {
|
||||
if receipt["deliveryInputHash"].is_string() {
|
||||
return delivery_input_hash(state, creation, variant, component)
|
||||
.is_ok_and(|hash| receipt["deliveryInputHash"] == hash);
|
||||
}
|
||||
current_export_inputs(state, Some(creation), &creation["revision"], variant, component, receipt)
|
||||
}
|
||||
|
||||
pub(crate) const STALE_DELIVERY_EXPORT: &str = "画布在导出后已修改,请重新导出该组";
|
||||
|
||||
pub(crate) fn edited_delivery_canvas(dir: &Path, state: &Value, variant: &str, component: &str) -> R<Option<PathBuf>> {
|
||||
let key = mapping_key(variant, component, None);
|
||||
let edited = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
let active = dir.join("canvas.pcraft");
|
||||
let modified = |path: &Path| match fs::metadata(path) {
|
||||
Ok(metadata) => metadata.modified().map(Some).map_err(|error| error.to_string()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
let edited_time = modified(&edited)?;
|
||||
if state["activeOutput"] == component && state["activeVariantId"] == variant
|
||||
&& modified(&active)?.is_some_and(|time| Some(time) > edited_time)
|
||||
{
|
||||
let canvas = super::load_draft(dir, &active).map_err(|_| "当前画布无法读取,请保存后重新导出")?;
|
||||
if mapping(&canvas).is_some_and(|meta| meta["workspaceId"] == state["id"]
|
||||
&& meta["variantId"] == variant && meta["component"] == component)
|
||||
{
|
||||
return Ok(Some(active));
|
||||
}
|
||||
}
|
||||
Ok(edited_time.map(|_| edited))
|
||||
}
|
||||
|
||||
pub(crate) fn check_delivery_source(
|
||||
dir: &Path, state: &Value, variant: &str, component: &str, receipt: &Value,
|
||||
) -> R<()> {
|
||||
let source = &receipt["sourceDocument"];
|
||||
let Some(path) = edited_delivery_canvas(dir, state, variant, component)? else {
|
||||
return if source["workingSha256"].is_string() { Err(STALE_DELIVERY_EXPORT.into()) } else { Ok(()) };
|
||||
};
|
||||
let expected = source["sha256"].as_str().ok_or(STALE_DELIVERY_EXPORT)?;
|
||||
let actual = file_digest(&path).map_err(|_| STALE_DELIVERY_EXPORT)?;
|
||||
if source["workingSha256"] == actual || actual == expected {
|
||||
return Ok(());
|
||||
}
|
||||
// Draft checkpoints can reference an object store, while the exported
|
||||
// document is self-contained. Compare equivalent portable encodings.
|
||||
let saved = super::load_draft(dir, &path).map_err(|_| STALE_DELIVERY_EXPORT)?;
|
||||
let bytes = photocraft_format::save_to_bytes(&saved, &Default::default())
|
||||
.map_err(|_| STALE_DELIVERY_EXPORT)?;
|
||||
if format!("{:x}", Sha256::digest(bytes)) != expected {
|
||||
return Err(STALE_DELIVERY_EXPORT.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn check_delivery_export(
|
||||
dir: &Path, state: &Value, creation: &Value, variant: &str, component: &str, receipt: &Value,
|
||||
) -> R<()> {
|
||||
if let Some(issue) = state["productTemplateIssues"][component].as_str() {
|
||||
return Err(issue.to_owned());
|
||||
}
|
||||
let pack = &state["productTemplates"][component];
|
||||
if receipt["templateHash"] != pack["contentHash"] {
|
||||
return Err("制作模板与成品回执不一致,请重新导出该组".into());
|
||||
}
|
||||
if !delivery_inputs_match(state, creation, variant, component, receipt) {
|
||||
return Err("商品资料或制作设置与上次导出不同,请重新导出该组".into());
|
||||
}
|
||||
check_delivery_source(dir, state, variant, component, receipt)?;
|
||||
if receipt_uses_retired_image(dir, receipt) {
|
||||
return Err("该组成品使用了已退回的图片,请核对画布后重新导出".into());
|
||||
}
|
||||
let aspects = main_image_aspects(dir, pack, component)?;
|
||||
if receipt["mainImageAspects"] != aspects {
|
||||
return Err("主图画幅已变化,请重新导出该组".into());
|
||||
}
|
||||
let pages = production_export_pages(pack, component, &aspects);
|
||||
let (records, regions) = if component == "detail" {
|
||||
(&receipt["screenFiles"], template_screen_regions(pages)?)
|
||||
} else {
|
||||
(&receipt["files"], product_export_regions(pages, component)?)
|
||||
};
|
||||
if !export_records_match(records, ®ions, receipt["generationId"].as_str()) {
|
||||
return Err("成品图片数量或尺寸与模板不一致,请重新导出该组".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn current_export_inputs(
|
||||
state: &Value, creation: Option<&Value>, brief_revision: &Value,
|
||||
variant: &str, component: &str, receipt: &Value,
|
||||
) -> bool {
|
||||
if receipt["stageInputHash"].is_string() {
|
||||
creation.and_then(|value| stage_input_hash(state, value, variant, component).ok())
|
||||
.is_some_and(|inputs| receipt["stageInputHash"] == inputs)
|
||||
} else {
|
||||
receipt["briefRevision"] == *brief_revision
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn receipt_uses_retired_image(dir: &Path, receipt: &Value) -> bool {
|
||||
receipt["imageSources"].as_array().into_iter().flatten().any(|source| {
|
||||
!(source["origin"] == "human" && source["candidateArtifact"].is_null())
|
||||
&& source["candidateId"].as_str().is_some_and(|id| retired_archive(dir, id))
|
||||
})
|
||||
}
|
||||
|
||||
@ -0,0 +1,465 @@
|
||||
use super::super::{Digest, Document, Path, PathBuf, R, Sha256, Value, creation, delivery, fs, hash, json, load_draft, read_json};
|
||||
use super::{CANDIDATE, SUPPORTED_PRODUCTION_OUTPUTS, VARIANT_INPUT_HASH, artifact_matches, candidate_available, completed_candidate, current_export_inputs, document_mapping_key, exists, export_files_present, fidelity, field_uses_aspect, image_output_component, input_hash, load, main_image_aspects, mapping, matches_placed_candidate, material_task_id, page_fields, product_export_regions, production_export_pages, production_stages, published_receipt, read_candidate, receipt_path, receipt_uses_retired_image, runnable_stages, slot_id, template_screen_regions, text, unindexed_candidate_ids, uuid, variant};
|
||||
|
||||
pub(crate) fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec<Value> {
|
||||
let creation = creation::load(dir);
|
||||
production_stages(state).into_iter().filter(|stage| {
|
||||
let (Some(variant), Some(component)) = (stage["variantId"].as_str(), stage["outputId"].as_str()) else { return true };
|
||||
if !state["productTemplateIssues"][component].is_null() { return true; }
|
||||
let receipt = published_receipt(&receipt_path(dir,variant,component)).unwrap_or(Value::Null);
|
||||
let pack = &state["productTemplates"][component];
|
||||
let Ok(aspects) = main_image_aspects(dir, pack, component) else { return true };
|
||||
let pages = || production_export_pages(pack, component, &aspects);
|
||||
let Ok(regions) = product_export_regions(pages(), component) else { return true };
|
||||
let generation = receipt["generationId"].as_str();
|
||||
let split_missing = component == "detail" && !template_screen_regions(pages()).is_ok_and(|screens|
|
||||
export_files_present(&receipt["screenFiles"], &screens, generation));
|
||||
let editable_present = match generation {
|
||||
Some(id) => {
|
||||
let source = &receipt["sourceDocument"];
|
||||
source["generationId"] == id && source["path"] == receipt["editable"]
|
||||
&& source["reopened"] == true && (artifact_matches(source, verify_editable)
|
||||
|| source["path"].as_str().is_some_and(|path| {
|
||||
if Path::new(path).exists() { return false; }
|
||||
let parts: Vec<_> = path.split(['/', '\\']).collect();
|
||||
let Some(at) = parts.iter().rposition(|part| matches!(*part, "product-exports" | "image-jobs")) else { return false; };
|
||||
let relative = &parts[at..];
|
||||
if relative.iter().any(|part| {
|
||||
let mut components = Path::new(part).components();
|
||||
!matches!(components.next(), Some(std::path::Component::Normal(_))) || components.next().is_some()
|
||||
}) { return false; }
|
||||
let mut relocated = source.clone();
|
||||
relocated["path"] = json!(dir.join(relative.iter().collect::<PathBuf>()));
|
||||
artifact_matches(&relocated, true)
|
||||
}))
|
||||
}
|
||||
None => receipt["editable"].as_str().is_some_and(|path| Path::new(path).is_file()),
|
||||
};
|
||||
let current_inputs = current_export_inputs(state, creation.as_ref().ok(), brief_revision, variant, component, &receipt);
|
||||
receipt_uses_retired_image(dir, &receipt) || !current_inputs || receipt["mainImageAspects"] != aspects || receipt["templateHash"] != state["productTemplates"][component]["contentHash"]
|
||||
|| !export_files_present(&receipt["files"], ®ions, generation) || split_missing || !editable_present
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn resumable_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec<Value> {
|
||||
let mut remaining = remaining_stages(dir, state, brief_revision, verify_editable);
|
||||
let path = dir.join("production-run.json");
|
||||
if let Ok(checkpoint) = read_json(&path)
|
||||
&& checkpoint["status"] == "paused_on_exit"
|
||||
&& checkpoint["workspaceId"] == state["id"]
|
||||
&& checkpoint["project"].as_str().is_some_and(|id| dir.file_name().is_some_and(|name| name == id))
|
||||
{
|
||||
for stage in production_stages(state) {
|
||||
if remaining.contains(&stage) { continue; }
|
||||
let output = stage["outputId"].as_str().unwrap_or_default();
|
||||
let variant = stage["variantId"].as_str().unwrap_or_default();
|
||||
let published = checkpoint["published"].as_array().into_iter().flatten().find(|row|
|
||||
row["outputId"] == output && row["variantId"] == variant);
|
||||
if let Some(row) = published
|
||||
&& row["issues"].as_array().is_some_and(|issues| !issues.is_empty())
|
||||
&& row["generationId"].is_string()
|
||||
&& published_receipt(&receipt_path(dir, variant, output)).is_ok_and(|receipt|
|
||||
receipt["generationId"] == row["generationId"])
|
||||
{
|
||||
remaining.push(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
runnable_stages(state, remaining)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_export_source(dir: &Path, record: &Value) -> Value {
|
||||
let candidate_id = record["id"].as_str().unwrap_or_default();
|
||||
let archive = format!("image-jobs/{candidate_id}");
|
||||
let task_record = format!("{archive}/task.json");
|
||||
let task = read_json(&dir.join(&task_record)).ok()
|
||||
.filter(|task| task["id"] == record["id"] && task["slotBinding"] == record["binding"]);
|
||||
let mut source = json!({
|
||||
"candidateId":candidate_id,"materialTaskId":material_task_id(record),
|
||||
"prompt":record["prompt"],"requestId":record["requestId"],
|
||||
"candidateRecord":format!("{archive}/{CANDIDATE}"),"candidateArtifact":record["artifact"],"kind":"unrecorded",
|
||||
});
|
||||
if task.is_some() {
|
||||
source["taskRecord"] = json!(task_record);
|
||||
}
|
||||
if record["canvasTransform"].is_object() {
|
||||
source["kind"] = json!("transform");
|
||||
source["requestId"] = record["sourceRequestId"].clone();
|
||||
if record["reusedFrom"].is_object() {
|
||||
source["reusedFrom"] = record["reusedFrom"].clone();
|
||||
}
|
||||
} else if record["sourceType"] == "archived-candidate" {
|
||||
source["kind"] = json!("reused");
|
||||
source["reusedFrom"] = record["reusedFrom"].clone();
|
||||
source["requestId"] = record["sourceRequestId"].clone();
|
||||
} else if record["sourceType"] == "local-import" {
|
||||
source["kind"] = json!("local-import");
|
||||
source["origin"] = json!("human");
|
||||
} else if record["sourceType"] == "product-reference" {
|
||||
source["kind"] = json!("product-reference");
|
||||
if let Some(crop) = record["binding"].get("referenceCrop") {
|
||||
source["referenceCrop"] = crop.clone();
|
||||
}
|
||||
} else if let Some(task) = task {
|
||||
source["kind"] = json!(if task["sceneComposite"].is_object() { "scene-composite" } else { "generation" });
|
||||
source["requestId"] = task["requestId"].clone();
|
||||
if dir.join(&archive).join("response.json").is_file() {
|
||||
source["responseRecord"] = json!(format!("{archive}/response.json"));
|
||||
}
|
||||
if task["sceneComposite"].is_object() && dir.join(&archive).join("scene-product.png").is_file() {
|
||||
source["compositeProduct"] = json!(format!("{archive}/scene-product.png"));
|
||||
}
|
||||
}
|
||||
source
|
||||
}
|
||||
|
||||
pub(crate) fn manual_image_source(doc: &Document, layer: &photocraft_doc::Layer, variant: &str, slot: &str) -> Option<Value> {
|
||||
use photocraft_doc::{LayerContent, SmartSource};
|
||||
let marker = format!("jiansun.manual-image.{variant}.{slot}");
|
||||
let (_, value) = doc.metadata.text.iter().find(|(key, _)| *key == marker)?;
|
||||
let record: Value = serde_json::from_str(value).ok()?;
|
||||
let source = record["source"].as_str().filter(|source| matches!(*source, "professional-edit" | "local-import"))?;
|
||||
let sha = record["sha256"].as_str().filter(|sha| sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()))?;
|
||||
let embedded = match &layer.content {
|
||||
LayerContent::Smart(smart) => {
|
||||
let SmartSource::Embedded { bytes, .. } = &smart.source else { return None; };
|
||||
let actual = format!("{:x}", Sha256::digest(bytes.as_slice()));
|
||||
if actual != sha { return None; }
|
||||
Some(actual)
|
||||
}
|
||||
LayerContent::Raster(surface) if !surface.content_bounds().is_empty() => None,
|
||||
_ => return None,
|
||||
};
|
||||
Some(json!({"kind":source,"origin":"human","sha256":sha,"embeddedSha256":embedded,
|
||||
"updatedAt":record["updatedAt"],"candidateId":record["candidateId"]}))
|
||||
}
|
||||
|
||||
pub(crate) const COVERAGE_FIELDS: [&str; 6] = ["adopted", "manual", "unadoptedWithCandidates", "empty", "skipped", "total"];
|
||||
|
||||
pub(crate) fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value, component: &str, variant: &str, aspects: &Value) -> (Vec<String>, Vec<String>, Vec<Value>, Value) {
|
||||
use photocraft_doc::{LayerContent, LayerId, SmartSource};
|
||||
let mut missing = Vec::new();
|
||||
let mut invalid_sources = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
let mut coverage = json!({"adopted":0,"manual":0,"unadoptedWithCandidates":0,"empty":0,"skipped":0,"total":0});
|
||||
let available_slots: std::collections::HashSet<_> = state["candidates"].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).filter_map(|id| read_candidate(dir, id).ok())
|
||||
.filter(candidate_available).filter_map(|record| record["binding"]["slotId"].as_str().map(str::to_owned)).collect();
|
||||
let template = &state["template"];
|
||||
let current_input = input_hash(dir, state, variant).ok();
|
||||
for page in production_export_pages(template, component, aspects) {
|
||||
let mapping = page_fields(meta).find(|(id, _)| *id == &page["id"]).map(|(_, fields)| fields);
|
||||
for field in page["slots"].as_array().into_iter().flatten().filter(|field| field["kind"] == "image" && field_uses_aspect(field, aspects)) {
|
||||
let Some(id) = field["fieldId"].as_str() else { continue };
|
||||
let slot = slot_id(&template["contentHash"], variant, id);
|
||||
let layer_path = mapping.into_iter().flatten().find(|row| row["kind"] == "image" && row["slotId"] == slot)
|
||||
.and_then(|row| row["nativeLayerId"].as_u64()).and_then(|id| doc.path_of(LayerId(id)));
|
||||
let marker = format!("jiansun.adopted.{variant}.{slot}");
|
||||
let adopted = doc.metadata.text.iter().find(|(key, _)| *key == marker);
|
||||
let record = adopted.and_then(|(_, id)| read_candidate(dir, id).ok())
|
||||
.filter(|record| candidate_available(record) && record["binding"]["slotId"] == slot
|
||||
&& record["binding"]["workspaceId"] == state["id"] && record["binding"]["templateHash"] == template["contentHash"]
|
||||
&& record["binding"]["variantId"] == variant
|
||||
&& record["inputHash"].as_str().is_none_or(|input|
|
||||
!input.starts_with(VARIANT_INPUT_HASH) || current_input.as_deref() == Some(input)));
|
||||
let visible = layer_path.as_ref().is_some_and(|path| (1..=path.len())
|
||||
.all(|len| doc.layer_at(&path[..len]).is_some_and(|layer| layer.visible && layer.opacity > 0.0)));
|
||||
let manual_key = format!("jiansun.manual-image.{variant}.{slot}");
|
||||
let found = layer_path.as_deref().and_then(|path| {
|
||||
let layer = doc.layer_at(path)?;
|
||||
let mut source = if let Some(manual) = manual_image_source(doc, layer, variant, &slot) {
|
||||
manual
|
||||
} else {
|
||||
let record = record?;
|
||||
let LayerContent::Smart(smart) = &layer.content else { return None; };
|
||||
let SmartSource::Embedded { file_name, bytes } = &smart.source else { return None; };
|
||||
if file_name != "candidate.png" || !matches_placed_candidate(dir, &record["artifact"], bytes) {
|
||||
return None;
|
||||
}
|
||||
let mut source = candidate_export_source(dir, &record);
|
||||
source["embeddedSha256"] = json!(fidelity::embedded_hash(layer));
|
||||
source["embeddedSize"] = json!(creation::png_size(bytes).ok());
|
||||
source
|
||||
};
|
||||
source["pageId"] = page["id"].clone();
|
||||
source["fieldId"] = json!(id);
|
||||
source["slotId"] = json!(slot);
|
||||
source["nativeLayerId"] = json!(layer.id.0);
|
||||
source["variantId"] = json!(variant);
|
||||
Some(source)
|
||||
});
|
||||
let skipped_key = format!("jiansun.skipped-image.{variant}.{slot}");
|
||||
let skipped = doc.metadata.text.iter().any(|(key, raw)| *key == skipped_key
|
||||
&& serde_json::from_str::<Value>(raw).is_ok_and(|status| status["status"] == "skipped"));
|
||||
let status = if let Some(source) = found.as_ref().filter(|_| visible) {
|
||||
let status = if matches!(source["kind"].as_str(), Some("professional-edit" | "local-import")) {
|
||||
"manual"
|
||||
} else { "adopted" };
|
||||
sources.push(source.clone());
|
||||
status
|
||||
} else if skipped {
|
||||
"skipped"
|
||||
} else {
|
||||
if found.is_none() && (adopted.is_some() || doc.metadata.text.iter().any(|(key, _)| *key == manual_key)) {
|
||||
invalid_sources.push(id.to_owned());
|
||||
}
|
||||
missing.push(id.to_owned());
|
||||
if available_slots.contains(&slot) { "unadoptedWithCandidates" } else { "empty" }
|
||||
};
|
||||
coverage[status] = json!(coverage[status].as_u64().unwrap_or(0) + 1);
|
||||
coverage["total"] = json!(coverage["total"].as_u64().unwrap_or(0) + 1);
|
||||
}
|
||||
}
|
||||
(missing, invalid_sources, sources, coverage)
|
||||
}
|
||||
|
||||
pub(crate) fn unverified_export_copy(
|
||||
doc: &Document, meta: &Value, journal: &Value,
|
||||
) -> Vec<String> {
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
page_fields(meta).flat_map(|(_, fields)| fields).filter_map(|field| {
|
||||
if field["kind"] != "text" { return None; }
|
||||
let field_id = field["fieldId"].as_str()?;
|
||||
let layer = field["nativeLayerId"].as_u64()?;
|
||||
let path = doc.path_of(LayerId(layer))?;
|
||||
if !(1..=path.len()).all(|len| doc.layer_at(&path[..len])
|
||||
.is_some_and(|node| node.visible && node.opacity > 0.0)) { return None; }
|
||||
let text_value: String = if field["embeddedTarget"].is_object() {
|
||||
let Ok(Some(value)) = photocraft_ui_egui::jiansun::production_facts::read_embedded_layer(doc, &field["embeddedTarget"], |child, inner_id| {
|
||||
let Some(inner) = child.layer(inner_id) else { return Ok(None) };
|
||||
let LayerContent::Text(text) = &inner.content else { return Ok(None) };
|
||||
Ok((!text.text.trim().is_empty()).then(|| text.text.clone()))
|
||||
}) else { return None };
|
||||
value
|
||||
} else {
|
||||
let LayerContent::Text(text) = &doc.layer_at(&path)?.content else { return None; };
|
||||
if text.text.trim().is_empty() { return None; }
|
||||
text.text.clone()
|
||||
};
|
||||
let marker = format!("jiansun.manual-text.{layer}");
|
||||
if doc.metadata.text.iter().any(|(key, raw)| *key == marker
|
||||
&& serde_json::from_str::<Value>(raw).is_ok_and(|record| record["source"] == "human" && record["sha256"] == hash(&text_value)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let recorded = &journal["copyEvidence"][layer.to_string()];
|
||||
let verified = recorded["field"] == field_id && recorded["text"] == text_value
|
||||
&& recorded["sources"].as_array().is_some_and(|sources| !sources.is_empty())
|
||||
&& recorded["pictures"].as_array().is_some_and(|pictures| !pictures.is_empty());
|
||||
(!verified).then(|| field_id.to_owned())
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn with_export_region<T>(native: &Document, region: (u64, u64, u64), render: impl FnOnce(&Document) -> R<T>) -> R<T> {
|
||||
let (top, width, height) = region;
|
||||
if width == 0 || height == 0 || width > u64::from(native.size.width)
|
||||
|| top.checked_add(height).is_none_or(|bottom| bottom > u64::from(native.size.height))
|
||||
{
|
||||
return Err("导出范围超出画布".into());
|
||||
}
|
||||
if region == (0, u64::from(native.size.width), u64::from(native.size.height)) {
|
||||
return render(native);
|
||||
}
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(native.clone(), None);
|
||||
session.execute("image.crop", json!({"x":0,"y":top,"width":width,"height":height,"deleteCroppedPixels":false}))
|
||||
.map_err(|error| format!("图组裁切失败:{error}"))?;
|
||||
render(&session.active().ok_or("图组裁切画布缺失")?.doc)
|
||||
}
|
||||
|
||||
pub(crate) fn export_jpg_region(native: &Document, region: (u64, u64, u64)) -> R<photocraft_io::ExportResult> {
|
||||
let options = photocraft_io::ExportOptions { xmp:photocraft_io::XmpEmbed::None, ..Default::default() };
|
||||
with_export_region(native, region, |doc| {
|
||||
photocraft_io::export(doc, "jpg", &options).map_err(|error| format!("JPG 导出失败:{error}"))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn save_delivery_canvas(
|
||||
native: &Document, export_dir: &Path, name: &str, component: &str, choices: &Value,
|
||||
sku: Option<(&Value, &str)>,
|
||||
) -> R<(usize, bool)> {
|
||||
let mut count = 0;
|
||||
let mut sku_barcode_warning = false;
|
||||
if choices["psd"] == true {
|
||||
let file = photocraft_io::export(native, "psd", &Default::default()).map_err(|error| format!("分层文件导出失败:{error}"))?;
|
||||
let extension = match file.bytes.get(..6) {
|
||||
Some(b"8BPS\0\x01") => "psd",
|
||||
Some(b"8BPS\0\x02") => "psb",
|
||||
_ => return Err("分层文件导出格式无效".into()),
|
||||
};
|
||||
photocraft_format::atomic_write(&export_dir.join(format!("{name}.{extension}")), &file.bytes)
|
||||
.map_err(|_| "分层文件写入失败")?;
|
||||
count += 1;
|
||||
}
|
||||
if choices["jpg"] == true {
|
||||
let write = |path: &Path, region: (u64, u64, u64)| -> R<()> {
|
||||
let file = export_jpg_region(native, region)?;
|
||||
if path.exists() { return Err("同一文件夹已有同名 JPG,未覆盖".into()); }
|
||||
photocraft_format::atomic_write(path, &file.bytes).map_err(|_| "JPG 写入失败".into())
|
||||
};
|
||||
if let Some(meta) = mapping(native).filter(|_| SUPPORTED_PRODUCTION_OUTPUTS.contains(&component)) {
|
||||
let pages = meta["outputs"].as_array().ok_or("当前画布缺少输出范围")?;
|
||||
if component == "detail" {
|
||||
let regions = product_export_regions(pages, component)?;
|
||||
for region in regions { write(&export_dir.join(format!("{name}.jpg")), region)?; count += 1; }
|
||||
}
|
||||
let regions = template_screen_regions(pages)?;
|
||||
if let Some((brief, variant)) = sku {
|
||||
let mut sku_entries = Vec::new();
|
||||
let mut sku_counts: std::collections::BTreeMap<(String, String), usize> = std::collections::BTreeMap::new();
|
||||
for (index, ®ion) in regions.iter().enumerate() {
|
||||
let (names, missing) = super::delivery::sku_export_names(brief, variant, index);
|
||||
sku_barcode_warning |= missing;
|
||||
let size = format!("{}x{}", region.1, region.2);
|
||||
for sku_name in names {
|
||||
*sku_counts.entry((size.clone(), sku_name.clone())).or_insert(0) += 1;
|
||||
sku_entries.push((region, size.clone(), sku_name));
|
||||
}
|
||||
}
|
||||
let mut sku_offsets: std::collections::BTreeMap<(String, String), usize> = std::collections::BTreeMap::new();
|
||||
for (region, size, sku_name) in sku_entries {
|
||||
let base_target = if regions.len() > 1 {
|
||||
export_dir.join(&size)
|
||||
} else {
|
||||
export_dir.to_owned()
|
||||
};
|
||||
let key = (size, sku_name);
|
||||
let target = if sku_counts.get(&key).copied().unwrap_or(0) > 1 {
|
||||
let offset = sku_offsets.entry(key.clone()).or_insert(0);
|
||||
*offset += 1;
|
||||
base_target.join(format!("{:02}", *offset))
|
||||
} else {
|
||||
base_target
|
||||
};
|
||||
fs::create_dir_all(&target).map_err(|_| "成品目录无法创建")?;
|
||||
write(&target.join(format!("{}.jpg", key.1)), region)?;
|
||||
count += 1;
|
||||
}
|
||||
} else {
|
||||
for (index, ®ion) in regions.iter().enumerate() {
|
||||
write(&export_dir.join(format!("{name}-{:02}.jpg", index + 1)), region)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write(&export_dir.join(format!("{name}.jpg")), (0, u64::from(native.size.width), u64::from(native.size.height)))?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
Ok((count, sku_barcode_warning))
|
||||
}
|
||||
|
||||
pub(crate) fn export_candidates(
|
||||
dir: &Path,
|
||||
workspace: Option<&Value>,
|
||||
mut save: impl FnMut(&Value, &Path, &[u8], (u32, u32)) -> R<()>,
|
||||
) -> R<()> {
|
||||
if !exists(dir) { return Ok(()); }
|
||||
let state = load(dir)?;
|
||||
if workspace.is_some_and(|id| *id != state["id"]) {
|
||||
return Err("交付候选所属画布已变化".into());
|
||||
}
|
||||
let indexed: std::collections::HashSet<_> = state["candidates"].as_array().into_iter()
|
||||
.flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
let orphans = unindexed_candidate_ids(dir, &indexed)?;
|
||||
let mut ids: Vec<_> = indexed.iter().chain(&orphans).collect();
|
||||
ids.sort_unstable();
|
||||
for id in ids {
|
||||
let Ok(record) = read_candidate(dir, id) else { continue; };
|
||||
let Some((record, pixels)) = completed_candidate(dir, &state, record, indexed.contains(id)) else { continue; };
|
||||
let Ok(size) = creation::png_size(&pixels) else { continue; };
|
||||
let binding = &record["binding"];
|
||||
let variant_id = uuid(&binding["variantId"], "花色")?;
|
||||
let name = variant(&state, &variant_id).ok().and_then(|row| row["name"].as_str())
|
||||
.filter(|name| !name.trim().is_empty()).unwrap_or("花色");
|
||||
let component = binding["component"].as_str().or_else(|| image_output_component(&state, binding))
|
||||
.or_else(|| state["template"]["outputs"].as_array()?.iter()
|
||||
.find(|output| output["id"] == binding["outputId"])?.get("component")?.as_str());
|
||||
let label = match component {
|
||||
Some("detail") => "详情页",
|
||||
Some("main_images") => "主图",
|
||||
Some("sku_images") => "SKU",
|
||||
_ => "历史输出",
|
||||
};
|
||||
let page = super::delivery::name_component(binding["outputId"].as_str().unwrap_or(label), 9);
|
||||
let field = super::delivery::name_component(binding["fieldId"].as_str().unwrap_or("图位"), 9);
|
||||
let sequence = record["sequence"].as_u64().unwrap_or_default();
|
||||
let name = super::delivery::name_component(name, 11);
|
||||
let relative = PathBuf::from(format!("{name}-{}", &variant_id[..8]))
|
||||
.join(label).join(format!("{page}-{field}-{sequence:03}-{id}.png"));
|
||||
save(&record, &relative, &pixels, size)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: &Path, choices: &Value) -> R<(usize, bool)> {
|
||||
let state = exists(dir).then(|| load(dir)).transpose()?;
|
||||
let mut count = 0;
|
||||
let mut sku_barcode_warning = false;
|
||||
if choices["psd"] == true || choices["jpg"] == true {
|
||||
if let Some(state) = state.as_ref().filter(|state| state["productTemplates"].is_object()) {
|
||||
let mappings = state["mappings"].as_object().ok_or("项目没有可保存的画布")?;
|
||||
let active_mapping = mapping(active);
|
||||
let creation = creation::load(dir)?;
|
||||
for (key, meta) in mappings {
|
||||
let component = meta["component"].as_str().ok_or("画布输出无效")?;
|
||||
let label = match component {
|
||||
"detail" => "详情",
|
||||
"main_images" => "主图",
|
||||
"sku_images" => "SKU",
|
||||
_ => continue,
|
||||
};
|
||||
let variant_id = uuid(&meta["variantId"], "花色")?;
|
||||
if document_mapping_key(meta)? != *key {
|
||||
return Err("项目画布映射不一致".into());
|
||||
}
|
||||
let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
if !file.is_file() { continue; }
|
||||
let owned;
|
||||
let native = if active_mapping.as_ref().is_some_and(|active| {
|
||||
active["component"] == meta["component"] && active["variantId"] == meta["variantId"]
|
||||
&& active["outputId"] == meta["outputId"]
|
||||
}) { active } else {
|
||||
owned = super::load_draft(dir, &file).map_err(|_| format!("{label}编辑稿无法打开"))?;
|
||||
&owned
|
||||
};
|
||||
let variant_name = variant(state, &variant_id)?["name"].as_str().unwrap_or("花色");
|
||||
let variant_name: String = variant_name.chars().map(|ch| {
|
||||
if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch }
|
||||
}).collect();
|
||||
let mut target = export_dir.join(format!("{} ({})", variant_name.trim(), &variant_id[..8])).join(label);
|
||||
if meta["outputId"].is_string() { target.push(&key[..8]); }
|
||||
fs::create_dir_all(&target).map_err(|_| "成品目录无法创建")?;
|
||||
let sku = (component == "sku_images").then_some((&creation["brief"], variant_id.as_str()));
|
||||
let (written, warning) = save_delivery_canvas(native, &target, label, component, choices, sku)?;
|
||||
count += written;
|
||||
sku_barcode_warning |= warning;
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
let active_mapping = mapping(active);
|
||||
let sku_variant = active_mapping.as_ref().filter(|meta| meta["component"] == "sku_images")
|
||||
.and_then(|meta| meta["variantId"].as_str());
|
||||
if let Some(variant) = sku_variant {
|
||||
let creation = creation::load(dir)?;
|
||||
let (written, warning) = save_delivery_canvas(active, export_dir, "SKU", "sku_images",
|
||||
choices, Some((&creation["brief"], variant)))?;
|
||||
count += written;
|
||||
sku_barcode_warning |= warning;
|
||||
} else {
|
||||
count += save_delivery_canvas(active, export_dir, "当前画布", "", choices, None)?.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if choices["candidates"] == true {
|
||||
export_candidates(dir, None, |_, relative, pixels, _| {
|
||||
let target = export_dir.join("候选区图片").join(relative);
|
||||
fs::create_dir_all(target.parent().ok_or("候选目录无效")?).map_err(|_| "候选目录无法创建")?;
|
||||
fs::write(target, pixels).map_err(|_| "一张候选图无法保存")?;
|
||||
count += 1;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok((count, sku_barcode_warning))
|
||||
}
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reference_roles_match_post_rotation_order_with_and_without_template_base() {
|
||||
let state = json!({
|
||||
"brief": {"name": "实木休闲椅", "materials": "北美黑胡桃木"},
|
||||
"variants": [{"id": "v1", "name": "胡桃木色"}]
|
||||
});
|
||||
let output = json!({"id": "out1"});
|
||||
let field = json!({"name": "首屏场景图", "role": "主场景展示"});
|
||||
|
||||
let origins_no_tpl = vec![
|
||||
json!({"purpose": "product", "name": "正面实拍.png"}),
|
||||
json!({"purpose": "product", "name": "侧面实拍.png"}),
|
||||
];
|
||||
let ctx_no_tpl = build_manual_image_fact_context(&state, &output, &field, "v1", "换成阳光客厅", &origins_no_tpl);
|
||||
assert_eq!(ctx_no_tpl.reference_roles.len(), 2);
|
||||
assert!(ctx_no_tpl.reference_roles[0].starts_with("图1 = 本款真实产品实拍图「正面实拍.png」"));
|
||||
assert!(ctx_no_tpl.reference_roles[1].starts_with("图2 = 本款真实产品实拍图「侧面实拍.png」"));
|
||||
|
||||
let origins_with_tpl = vec![
|
||||
json!({"purpose": "template-base", "source": "pinned-template:slot1"}),
|
||||
json!({"purpose": "product", "name": "正面实拍.png"}),
|
||||
];
|
||||
let ctx_with_tpl = build_manual_image_fact_context(&state, &output, &field, "v1", "不要沿用旧产品", &origins_with_tpl);
|
||||
assert!(ctx_with_tpl.reference_roles[0].starts_with("图1 = 当前模板构图与留白参考"));
|
||||
assert!(ctx_with_tpl.reference_roles[1].starts_with("图2 = 本款真实产品实拍图「正面实拍.png」"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_compiler_uses_chat_model_output_and_gracefully_falls_back_on_error() {
|
||||
let state = json!({"brief": {"name": "实木休闲椅"}, "variants": [{"id": "v1", "name": "胡桃木色"}]});
|
||||
let output = json!({"id": "out1"});
|
||||
let field = json!({"name": "细节图"});
|
||||
let origins = vec![json!({"purpose": "product", "name": "实拍1.png"})];
|
||||
let ctx = build_manual_image_fact_context(&state, &output, &field, "v1", "不要受到原模板结构影响", &origins);
|
||||
|
||||
let (ok_prompt, by_ok) = compile_manual_image_prompt_with_fn(&ctx, |_, _| Ok("以图1本款实木休闲椅实拍为唯一外观依据,呈现温暖自然光细节特写。".into()));
|
||||
assert_eq!(by_ok, "chat-model");
|
||||
assert!(ok_prompt.contains("图1"));
|
||||
|
||||
let (fb_prompt, by_fb) = compile_manual_image_prompt_with_fn(&ctx, |_, _| Err("timeout".into()));
|
||||
assert_eq!(by_fb, "structured-fallback");
|
||||
assert!(fb_prompt.contains("图1 = 本款真实产品实拍图「实拍1.png」"));
|
||||
assert!(fb_prompt.contains("不要受到原模板结构影响"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn product_reference_selector_resolves_by_path_or_index() {
|
||||
let products = json!([
|
||||
{"purpose": "product", "source": "local:1111", "name": "A.png"},
|
||||
{"purpose": "product", "source": "local:2222", "name": "B.png"}
|
||||
]);
|
||||
assert_eq!(resolve_product_reference_index(&products, &json!(1), None).unwrap(), 1);
|
||||
assert_eq!(resolve_product_reference_index(&products, &json!(0), Some(&json!("local:2222"))).unwrap(), 1);
|
||||
assert_eq!(resolve_product_reference_index(&products, &json!(0), Some(&json!("B.png"))).unwrap(), 1);
|
||||
assert!(resolve_product_reference_index(&products, &json!(0), Some(&json!("missing.png"))).is_err());
|
||||
}
|
||||
@ -0,0 +1,172 @@
|
||||
use super::super::{Backend, R, Uuid, Value, json, pi_runtime};
|
||||
use super::{editable_image_prompt, product_reference_index, text, variant};
|
||||
|
||||
pub(crate) fn resolve_product_reference_index(products: &Value, index_value: &Value, path_value: Option<&Value>) -> R<usize> {
|
||||
if let Some(target_path) = path_value.and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
||||
if let Some(pos) = products.as_array().into_iter().flatten()
|
||||
.filter(|row| row["purpose"] == "product")
|
||||
.position(|row| row["source"].as_str() == Some(target_path) || row["name"].as_str() == Some(target_path))
|
||||
{
|
||||
return Ok(pos);
|
||||
}
|
||||
return Err("所选产品实拍图不在当前花色清单中".into());
|
||||
}
|
||||
product_reference_index(index_value)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ManualImageFactContext {
|
||||
pub(crate) user_instructions: String,
|
||||
pub(crate) slot_label: String,
|
||||
pub(crate) slot_purpose: String,
|
||||
pub(crate) product_facts: Vec<String>,
|
||||
pub(crate) reference_roles: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn build_manual_image_fact_context(
|
||||
state: &Value,
|
||||
output: &Value,
|
||||
field: &Value,
|
||||
variant_id: &str,
|
||||
instructions: &str,
|
||||
origins: &[Value],
|
||||
) -> ManualImageFactContext {
|
||||
let slot_label = field.get("name").or_else(|| field.get("label"))
|
||||
.and_then(Value::as_str).unwrap_or("当前图位").trim().to_owned();
|
||||
let slot_prompt_owned = editable_image_prompt(field, &output["id"], None);
|
||||
let slot_purpose = [
|
||||
field.get("role").and_then(Value::as_str),
|
||||
field.get("requirements").and_then(Value::as_str),
|
||||
slot_prompt_owned.as_deref(),
|
||||
].into_iter().flatten().map(str::trim).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(";");
|
||||
|
||||
let brief = &state["brief"];
|
||||
let mut product_facts = Vec::new();
|
||||
if let Some(name) = brief["name"].as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
product_facts.push(format!("商品名称:{name}"));
|
||||
}
|
||||
if let Ok(selected) = variant(state, variant_id) {
|
||||
if let Some(vname) = selected["name"].as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
product_facts.push(format!("当前花色:{vname}"));
|
||||
}
|
||||
}
|
||||
for (label, key) in [("材质", "materials"), ("核心卖点", "sellingPoints"), ("风格定位", "style")] {
|
||||
if let Some(val) = brief.get(key) {
|
||||
let text = match val {
|
||||
Value::String(s) => s.trim().to_owned(),
|
||||
Value::Array(arr) => arr.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).collect::<Vec<_>>().join("、"),
|
||||
_ => String::new(),
|
||||
};
|
||||
if !text.is_empty() {
|
||||
product_facts.push(format!("{label}:{text}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let reference_roles = origins.iter().enumerate().map(|(i, origin)| {
|
||||
let num = i + 1;
|
||||
match origin["purpose"].as_str() {
|
||||
Some("template-base") => format!("图{num} = 当前模板构图与留白参考(仅借用构图、视角与留白,产品主体必须替换为本款实拍,不要沿用其中旧产品造型或文字)"),
|
||||
Some("product") => {
|
||||
let name = origin["name"].as_str().map(str::trim).filter(|s| !s.is_empty()).unwrap_or("本款产品实拍");
|
||||
format!("图{num} = 本款真实产品实拍图「{name}」(唯一外观、结构、材质与颜色依据)")
|
||||
}
|
||||
Some("selected-candidate-edit-base") => format!("图{num} = 待微调的当前候选底图"),
|
||||
_ => format!("图{num} = 补充参考图"),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
ManualImageFactContext {
|
||||
user_instructions: instructions.trim().to_owned(),
|
||||
slot_label,
|
||||
slot_purpose,
|
||||
product_facts,
|
||||
reference_roles,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build_structured_manual_prompt(ctx: &ManualImageFactContext) -> String {
|
||||
let mut parts = Vec::new();
|
||||
if !ctx.reference_roles.is_empty() {
|
||||
parts.push(format!("【参考图角色说明】
|
||||
{}", ctx.reference_roles.join("
|
||||
")));
|
||||
}
|
||||
if !ctx.product_facts.is_empty() {
|
||||
parts.push(format!("【商品客观外观】{}", ctx.product_facts.join(";")));
|
||||
}
|
||||
let mut goal = format!("请为「{}」生成高质量电商实拍视觉图,严格以本款真实产品实拍图作为产品造型、结构、材质与色彩的唯一依据。", ctx.slot_label);
|
||||
if !ctx.slot_purpose.is_empty() {
|
||||
goal.push_str(&format!("图位要求:{}。", ctx.slot_purpose));
|
||||
}
|
||||
parts.push(goal);
|
||||
if !ctx.user_instructions.is_empty() {
|
||||
parts.push(format!("【画面调整需求】{}", ctx.user_instructions));
|
||||
}
|
||||
parts.join("
|
||||
")
|
||||
}
|
||||
|
||||
pub(crate) fn compile_manual_image_prompt_with_fn(
|
||||
ctx: &ManualImageFactContext,
|
||||
invoke: impl FnOnce(&str, &str) -> R<String>,
|
||||
) -> (String, &'static str) {
|
||||
let system = "你是电商视觉生图提示词编译助手。请根据给定的参考图角色编号、商品客观外观、图位用途与用户口语要求,输出一段可直接发给生图模型的精准正向中文提示词(纯文本,不要Markdown或解释)。要求:1) 保留全部参考图编号(图1、图2…)及其角色分工;2) 将用户的否定句(如“不要受参考图原产品影响”)转化为明确的正向视觉指令(如“以图X本款实拍为唯一产品造型与材质依据,仅借用构图”);3) 严禁虚构未提供的材质、颜色或配件。";
|
||||
let mut user_lines = Vec::new();
|
||||
user_lines.push(format!("图位:{}", ctx.slot_label));
|
||||
if !ctx.slot_purpose.is_empty() { user_lines.push(format!("图位用途:{}", ctx.slot_purpose)); }
|
||||
if !ctx.product_facts.is_empty() { user_lines.push(format!("商品事实:{}", ctx.product_facts.join(";"))); }
|
||||
if !ctx.reference_roles.is_empty() { user_lines.push(format!("参考图清单:
|
||||
{}", ctx.reference_roles.join("
|
||||
"))); }
|
||||
user_lines.push(format!("用户要求:{}", if ctx.user_instructions.is_empty() { "按图位用途自然呈现本款产品" } else { &ctx.user_instructions }));
|
||||
let user_msg = user_lines.join("
|
||||
");
|
||||
match invoke(system, &user_msg) {
|
||||
Ok(compiled) if !compiled.trim().is_empty() => (compiled.trim().to_owned(), "chat-model"),
|
||||
_ => (build_structured_manual_prompt(ctx), "structured-fallback"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn compile_manual_image_prompt(&self, fact_ctx: &ManualImageFactContext) -> (String, &'static str) {
|
||||
compile_manual_image_prompt_with_fn(fact_ctx, |system, user_msg| {
|
||||
let settings = self.settings()?;
|
||||
let key = settings["key"].as_str().filter(|s| !s.trim().is_empty()).ok_or("未配置Key")?;
|
||||
let chosen = settings["copyModel"].as_str().filter(|s| !s.trim().is_empty())
|
||||
.or_else(|| settings["model"].as_str().filter(|s| !s.trim().is_empty()))
|
||||
.ok_or("未配置对话模型")?;
|
||||
let model = self.live_text_choice(chosen, key)?;
|
||||
if !matches!(
|
||||
(model["protocol"].as_str(), model["path"].as_str()),
|
||||
(Some("openai-chat"), Some("/v1/chat/completions")) | (Some("anthropic-messages"), Some("/v1/messages"))
|
||||
) {
|
||||
return Err("对话协议不支持".into());
|
||||
}
|
||||
let invocation = crate::jiansun_backend::pi_runtime::invocation(self, &model)?;
|
||||
let mut requested = model.clone();
|
||||
requested["headers"] = invocation["headers"].clone();
|
||||
let anthropic = model["protocol"] == "anthropic-messages";
|
||||
let payload = if anthropic {
|
||||
json!({"model":model["id"],"system":system,"messages":[{"role":"user","content":user_msg}],"max_tokens":600,"stream":false})
|
||||
} else {
|
||||
json!({"model":model["id"],"messages":[{"role":"system","content":system},{"role":"user","content":user_msg}],"max_tokens":600,"stream":false})
|
||||
};
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let response = crate::jiansun_backend::pi::send_text(self, &model, &requested, key, &id, std::time::Duration::from_secs(15), |_| true, |request, _, _| {
|
||||
request.json(&payload).send().map_err(|_| "编译提示词超时或网络中断".into())
|
||||
})?;
|
||||
if response.status().as_u16() != 200 {
|
||||
return Err("编译提示词返回非200".into());
|
||||
}
|
||||
let (_, v) = crate::jiansun_backend::body(response, crate::jiansun_backend::MAX_JSON)?;
|
||||
let content = if anthropic {
|
||||
v["content"].as_array()
|
||||
.map(|items| items.iter().filter(|v| v["type"] == "text").filter_map(|v| v["text"].as_str()).collect::<Vec<_>>().join("\n"))
|
||||
} else {
|
||||
v["choices"].as_array().and_then(|a| a.first()).and_then(|v| v["message"]["content"].as_str()).map(str::to_owned)
|
||||
}.ok_or("编译提示词响应为空")?;
|
||||
Ok(content)
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,97 @@
|
||||
use super::*;
|
||||
#[test]
|
||||
fn structure_guides_require_the_same_approved_candidate_and_frame_coordinates() {
|
||||
let recipe = json!({"edge":{"label":"框架下沿","styleLayerId":71}});
|
||||
let mut item = json!({"approvals":[{"candidateId":"good","decision":"pass","checks":{"structure":false},
|
||||
"observation":{"structureGuides":{"edge":[[210,530],[680,560]]}}}]});
|
||||
assert_eq!(approved_structure_guides(&recipe, &item, "good").unwrap(),
|
||||
Some(json!([{"kind":"outline","label":"框架下沿","points":[[210,530],[680,560]],"styleLayerId":71}])));
|
||||
assert_eq!(approved_structure_guides(&recipe, &item, "other").unwrap(), None);
|
||||
item["approvals"][0]["observation"]["structureGuides"]["edge"][0][0] = json!(1001);
|
||||
assert!(approved_structure_guides(&recipe, &item, "good").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annotation_coordinates_include_the_letterbox_of_a_contained_original() {
|
||||
let source = egui::ColorImage::filled([12, 6], egui::Color32::BLACK);
|
||||
let preview = contain_review_preview(source, &json!({"width":120,"height":120})).unwrap();
|
||||
assert_eq!(preview.size, [12, 12]);
|
||||
assert!(preview.pixels[..3*12].iter().all(|pixel| *pixel == egui::Color32::WHITE));
|
||||
assert!(preview.pixels[3*12..9*12].iter().all(|pixel| *pixel == egui::Color32::BLACK));
|
||||
assert!(preview.pixels[9*12..].iter().all(|pixel| *pixel == egui::Color32::WHITE));
|
||||
}
|
||||
#[test]
|
||||
fn a_fresh_product_draft_clears_nested_and_unmapped_copy_without_changing_layout() {
|
||||
use photocraft_doc::{Layer, LayerContent, TextLayer};
|
||||
let sample = Layer::new("Template example", LayerContent::Text(TextLayer {text:"3 年质保".into(), ..Default::default()}));
|
||||
let group = Layer::group("Original layout", vec![sample.clone()]);
|
||||
let mut layers = vec![group, sample];
|
||||
let original = layers.clone();
|
||||
clear_sample_copy(&mut layers);
|
||||
let LayerContent::Group(group) = &layers[0].content else { panic!("missing group"); };
|
||||
for layer in [&group.children[0], &layers[1]] {
|
||||
assert!(layer.visible);
|
||||
assert!(matches!(&layer.content, LayerContent::Text(text) if text.text.is_empty() && text.cache.is_none()));
|
||||
}
|
||||
assert_eq!(layers[1].id, original[1].id);
|
||||
assert!(matches!(&original[1].content, LayerContent::Text(text) if text.text == "3 年质保"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_ratio_uses_template_spec_instead_of_the_native_crop() {
|
||||
let field = json!({"outputSpec":"标准比例 2 : 3。实际图框1442×2353px","frame":{"width":1442,"height":2353}});
|
||||
assert_eq!(specified_image_ratio(&field), Some((2,3)));
|
||||
assert_eq!(specified_image_ratio(&json!({"requirements":"标准比例16:9。"})), Some((16,9)));
|
||||
assert_eq!(specified_image_ratio(&json!({"requirements":"图框980×1200"})), None);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn rejects_new_crossing_edges_but_preserves_template_shadows() {
|
||||
let mut photo = egui::ColorImage::filled([100, 90], egui::Color32::from_gray(224));
|
||||
let mut reference = photo.clone();
|
||||
for y in 0..90 {
|
||||
for x in 0..100 {
|
||||
let gradient = 150 + x as u8;
|
||||
reference[(x, y)] = egui::Color32::from_gray(gradient);
|
||||
if x < 50 { photo[(x, y)] = egui::Color32::from_gray(80); }
|
||||
}
|
||||
}
|
||||
let areas = [
|
||||
json!({"field":"title","bounds":[25,10,80,40]}),
|
||||
json!({"field":"caption","bounds":[60,50,98,85]}),
|
||||
];
|
||||
assert_eq!(compare_text_region_edges(&photo, &reference, &areas).unwrap(), vec![
|
||||
json!({"field":"title","direction":"纵向","coverage":100,"referenceCoverage":0}),
|
||||
]);
|
||||
assert!(compare_text_region_edges(&photo, &photo, &areas).unwrap().is_empty());
|
||||
assert!(compare_text_region_edges(&reference, &reference, &areas).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_template_prompt_uses_only_the_pinned_image_description() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let project = temp.path().join("projects").join("existing");
|
||||
let docs = temp.path().join("enterprise-templates").join("documents");
|
||||
fs::create_dir_all(&docs).unwrap();
|
||||
let raw = json!({"template_id":"GJ-DETAIL","fields":[{
|
||||
"field_id":"S02-I03","screen_id":"S02","type":"图片",
|
||||
"fill_requirements":"近景,柔光掠过涂层。\r\n近景,柔光掠过涂层。\r\n不把漆面做成镜面。",
|
||||
"adaptation_requirements":"相同说明再重复一次","output_spec":"裁切要求","rules":"图层定位"
|
||||
}]});
|
||||
let pack = json!({"id":"GJ-DETAIL","enterprise":{"component":"detail","components":{"detail":{"mappingAssetId":"mapping"}}},
|
||||
"resourceFiles":[{"role":"mapping","fileId":"mapping","revision":"pinned"}]});
|
||||
let field = json!({"fieldId":"S02-I03","requirements":"重复内容、裁切要求和图层定位"});
|
||||
write_json(&docs.join("mapping-newer.json"), &raw).unwrap();
|
||||
assert!(cached_prompt_mapping(&project, &pack).is_none());
|
||||
assert!(editable_image_prompt(&field, &json!("S02"), None).is_none());
|
||||
write_json(&docs.join("ekb%3Arelease%2Fcurrent%2Fa-mapping-pinned.json"), &raw).unwrap();
|
||||
let loaded = cached_prompt_mapping(&project, &pack).unwrap();
|
||||
assert_eq!(editable_image_prompt(&field, &json!("S02"), Some(&loaded)).as_deref(),
|
||||
Some("近景,柔光掠过涂层。\n不把漆面做成镜面。"));
|
||||
assert!(editable_image_prompt(&field, &json!("S03"), Some(&loaded)).is_none());
|
||||
|
||||
let imported = json!({"fieldId":"S02-I03","imagePrompt":"新包原始描述\n新包原始描述", "requirements":"图层定位"});
|
||||
assert_eq!(editable_image_prompt(&imported, &json!("S02"), None).as_deref(), Some("新包原始描述"));
|
||||
}
|
||||
|
||||
@ -0,0 +1,543 @@
|
||||
use super::super::{Digest, Backend, Document, Path, R, Sha256, Value, creation, delivery, fs, hash, json, load_draft, now, pi_runtime, production_profile, read_json, sync, transfer, write_json};
|
||||
use super::{DELIVERY_REOPEN_MISMATCH, SUPPORTED_PRODUCTION_OUTPUTS, artifact_matches, delivery_input_hash, edited_delivery_canvas, export_image_sources, export_jpg_region, export_records_match, fidelity, file_digest, load, main_image_aspects, manifest_path, manual_image_source, mapping, mapping_key, output_uses_variant, pending, product_export_regions, production_audit, production_export_pages, production_stages, published_receipt, receipt_path, remaining_stages, revision, runnable_stages, snapshot, stage_input_hash, template_screen_regions, text, unverified_export_copy, uuid, variant, with_export_region};
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn export_product_snapshot(&self, native: &Document, input: &Value) -> R<Value> {
|
||||
self.check_dispatch()?;
|
||||
self.ensure_owner(native.id.0)?;
|
||||
let dir = self.project_dir(native.id.0)?;
|
||||
let state = load(&dir)?;
|
||||
let doc = native.id.0;
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "running", Value::Null);
|
||||
let result = export_product_stage_snapshot(&dir, doc, &state, input, &self.scope(), Some(native));
|
||||
match &result {
|
||||
Ok(value) if value["publishedPointer"].is_string() => {
|
||||
let progress = json!({"generationId":value["generationId"],"publishedPointer":value["publishedPointer"],
|
||||
"filesVerified":value["validation"]["filesVerified"],"sourceHash":value["sourceDocument"]["sha256"]});
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "completed",
|
||||
json!({"generationId":value["generationId"],"validation":value["validation"]}));
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "publish", "completed", progress);
|
||||
}
|
||||
Ok(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "blocked", Value::Null),
|
||||
Err(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "failed", Value::Null),
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn export_saved_production_output(
|
||||
dir: &Path, doc: u64, scope: &str, workspace: &Value, output: &Value, reason: &Value,
|
||||
) -> R<Value> {
|
||||
let component = output["outputId"].as_str().filter(|id| SUPPORTED_PRODUCTION_OUTPUTS.contains(id))
|
||||
.ok_or("制作输出缺失")?;
|
||||
let variant = uuid(&output["variantId"], "制作款式")?;
|
||||
let state = load(dir)?;
|
||||
let live = {
|
||||
let _guard = sync::context_guard();
|
||||
let path = edited_delivery_canvas(dir, &state, &variant, component)?
|
||||
.ok_or("该输出没有已保存的可编辑画布")?;
|
||||
let native = super::load_draft(dir, &path).map_err(|_| "该输出的编辑稿无法读取")?;
|
||||
let sha = file_digest(&path).map_err(|_| "无法核对编辑稿内容")?;
|
||||
(native, sha)
|
||||
};
|
||||
let input = json!({"workspaceId":workspace,"outputId":component,"variantId":variant,
|
||||
"complete":true,"deliveryReason":reason});
|
||||
export_product_stage_with_source(dir, doc, &state, &input, scope, Some(&live.0), Some(&live.1))
|
||||
}
|
||||
|
||||
pub(crate) fn export_product_stage(dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str) -> R<Value> {
|
||||
export_product_stage_snapshot(dir, doc, state, input, scope, None)
|
||||
}
|
||||
|
||||
pub(crate) fn layered_format(bytes: &[u8]) -> R<&'static str> {
|
||||
match bytes.get(..6) {
|
||||
Some(b"8BPS\0\x01") => Ok("psd"),
|
||||
Some(b"8BPS\0\x02") => Ok("psb"),
|
||||
_ => Err("PSD / PSB 文件头无效".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn layered_size(name: &str, bytes: &[u8]) -> R<(u32, u32)> {
|
||||
let format = layered_format(bytes)?;
|
||||
if Path::new(name).extension().and_then(|ext| ext.to_str()) != Some(format) {
|
||||
return Err("分层文件扩展名与文件头不一致".into());
|
||||
}
|
||||
let imported = photocraft_io::import(name, bytes)
|
||||
.map_err(|error| format!("无法重开分层文件:{error}"))?;
|
||||
Ok((imported.document.size.width, imported.document.size.height))
|
||||
}
|
||||
|
||||
pub(crate) fn export_layered_document(dir: &Path, component: &str, generation: &str, doc: &Document) -> R<Value> {
|
||||
let exported = photocraft_io::export(doc, "psd", &Default::default())
|
||||
.map_err(|error| format!("分层文件导出失败:{error}"))?;
|
||||
let format = layered_format(&exported.bytes)?;
|
||||
let name = format!("{component}.{format}");
|
||||
let path = dir.join(&name);
|
||||
photocraft_format::atomic_write(&path, &exported.bytes)
|
||||
.map_err(|error| format!("分层文件写入失败:{error}"))?;
|
||||
let saved = fs::read(&path).map_err(|error| format!("分层文件读取失败:{error}"))?;
|
||||
if saved != exported.bytes || layered_size(&name, &saved)? != (doc.size.width, doc.size.height) {
|
||||
return Err("分层文件与本轮画布的内容或尺寸不一致".into());
|
||||
}
|
||||
Ok(json!({"path":path,"format":format,"role":"layered","generationId":generation,
|
||||
"width":doc.size.width,"height":doc.size.height,"sizeBytes":saved.len(),
|
||||
"sha256":format!("{:x}",Sha256::digest(&saved))}))
|
||||
}
|
||||
|
||||
pub(crate) fn reusable_product_generation(receipt: &Path, result: &Value,
|
||||
regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)]) -> Option<Value> {
|
||||
let old = published_receipt(receipt).ok()?;
|
||||
let generation = old["generationId"].as_str().filter(|id| id.strip_prefix("generation-")
|
||||
.is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())))?;
|
||||
let manifest = receipt.parent()?.join(manifest_path(generation));
|
||||
let folder = manifest.parent()?;
|
||||
if !result["workingSha256"].is_string() || result["workingSha256"] != old["sourceDocument"]["workingSha256"]
|
||||
|| !result["stageInputHash"].is_string()
|
||||
|| old["validation"]["mode"] != "full"
|
||||
|| old["reopenVerification"]["consistent"] != true
|
||||
|| ["templateHash", "stageInputHash", "variantId", "outputId", "workspaceId", "imageSources"]
|
||||
.iter().any(|key| old[*key] != result[*key])
|
||||
|| !export_records_match(&old["files"], regions, Some(generation))
|
||||
|| !screens.is_empty() && !export_records_match(&old["screenFiles"], screens, Some(generation))
|
||||
|| screens.is_empty() && old["screenFiles"].as_array().is_some_and(|files| !files.is_empty())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let intact = [&old["sourceDocument"], &old["layeredDocument"]].into_iter()
|
||||
.chain(old["files"].as_array()?.iter())
|
||||
.chain(old["screenFiles"].as_array().into_iter().flatten())
|
||||
.all(|artifact| artifact["generationId"] == generation && artifact["path"].as_str()
|
||||
.is_some_and(|path| Path::new(path).parent() == Some(folder)) && artifact_matches(artifact, true));
|
||||
intact.then_some(old)
|
||||
}
|
||||
|
||||
pub(crate) fn set_delivery_status(receipt: &mut Value, completed: bool) {
|
||||
receipt["allOutputsCompleted"] = json!(completed);
|
||||
receipt["deliveryStatus"] = json!(if completed { "completed" } else { "partial_delivered" });
|
||||
}
|
||||
|
||||
pub(crate) fn publish_product_generation(
|
||||
receipt: &Path, native: &Document, document_revision: &Value, result: &mut Value,
|
||||
regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)],
|
||||
) -> R<()> {
|
||||
let component = result["outputId"].as_str().ok_or("制作输出缺失")?;
|
||||
if let Some(old) = reusable_product_generation(receipt, result, regions, screens) {
|
||||
for field in ["reopenVerification", "generationId", "sourceDocument", "layeredDocument",
|
||||
"files", "screenFiles", "editable", "productionDelivery", "validation"] {
|
||||
if let Some(value) = old.get(field) {
|
||||
result[field] = value.clone();
|
||||
}
|
||||
}
|
||||
result.as_object_mut().unwrap().remove("workingSha256");
|
||||
result["publishedPointer"] = json!(manifest_path(old["generationId"].as_str().unwrap()));
|
||||
result["reusedGeneration"] = json!(true);
|
||||
let _guard = sync::context_guard();
|
||||
write_json(receipt, result)?;
|
||||
return Ok(());
|
||||
}
|
||||
let root = receipt.with_file_name("generations");
|
||||
fs::create_dir_all(&root).map_err(|error| format!("无法创建成品目录:{error}"))?;
|
||||
let generation = tempfile::Builder::new().prefix("generation-").tempdir_in(&root)
|
||||
.map_err(|error| format!("无法准备本次成品:{error}"))?;
|
||||
let id = generation.path().file_name().and_then(|name| name.to_str()).ok_or("成品版本标识缺失")?;
|
||||
let editable = generation.path().join(format!("{component}.pcraft"));
|
||||
photocraft_format::PcraftWriter::new().save_path(native, &editable, &Default::default())
|
||||
.map_err(|error| format!("成品工程保存失败:{error}"))?;
|
||||
let reopened = photocraft_format::load_path(&editable)
|
||||
.map_err(|error| format!("成品工程重开失败:{error}"))?;
|
||||
if reopened.id != native.id || reopened.size != native.size || reopened.guides != native.guides
|
||||
|| reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text {
|
||||
return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into());
|
||||
}
|
||||
let (manual, adopted): (Vec<_>, Vec<_>) = result["imageSources"].as_array().into_iter().flatten()
|
||||
.cloned().partition(|source| source["origin"] == "human" && source["candidateArtifact"].is_null());
|
||||
let mut reopen_verification = fidelity::reopen(native, &reopened, &json!(adopted));
|
||||
if !manual.is_empty() {
|
||||
let verified: Vec<_> = manual.iter().map(|source| {
|
||||
let consistent = source["nativeLayerId"].as_u64().and_then(|id| reopened.layer(photocraft_doc::LayerId(id)))
|
||||
.and_then(|layer| manual_image_source(&reopened, layer, source["variantId"].as_str()?, source["slotId"].as_str()?))
|
||||
.is_some_and(|saved| saved["sha256"] == source["sha256"]);
|
||||
json!({"slotId":source["slotId"],"sha256":source["sha256"],"consistent":consistent})
|
||||
}).collect();
|
||||
reopen_verification["consistent"] = json!(reopen_verification["consistent"] == true
|
||||
&& verified.iter().all(|row| row["consistent"] == true));
|
||||
reopen_verification["manualImages"] = json!(verified);
|
||||
}
|
||||
if reopen_verification["consistent"] != true {
|
||||
return Err(DELIVERY_REOPEN_MISMATCH.into());
|
||||
}
|
||||
super::transfer::check_pcraft_file(&editable)?;
|
||||
let layered = export_layered_document(generation.path(), component, id, &reopened)?;
|
||||
let exported_mapping = mapping(&reopened);
|
||||
let save_region = |name: &str, role: &str, (top, width, height): (u64, u64, u64), bytes: Vec<u8>| -> R<Value> {
|
||||
let file = generation.path().join(name);
|
||||
photocraft_format::atomic_write(&file, &bytes).map_err(|error| format!("{name} 写入失败:{error}"))?;
|
||||
let saved = fs::read(&file).map_err(|error| format!("{name} 无法读取:{error}"))?;
|
||||
if saved != bytes
|
||||
|| photocraft_codecs::probe_size(&saved).ok().map(|(w, h)| (u64::from(w), u64::from(h))) != Some((width, height))
|
||||
{
|
||||
return Err(format!("{name} 内容或尺寸与导出结果不一致"));
|
||||
}
|
||||
#[cfg(test)]
|
||||
if std::env::var_os("PHOTOCRAFT_TEST_CRASH_EXPORT").as_deref() == Some(receipt.as_os_str()) {
|
||||
std::process::exit(81);
|
||||
}
|
||||
let mut artifact = json!({"path":file,"format":"jpg","role":role,"generationId":id,"top":top,"width":width,"height":height,
|
||||
"sizeBytes":saved.len(),"sha256":format!("{:x}",Sha256::digest(&saved))});
|
||||
if role != "detail"
|
||||
&& let Some(page) = exported_mapping.as_ref().and_then(|meta| meta["outputs"].as_array())
|
||||
.and_then(|pages| pages.iter().find(|page| page["top"] == top && page["width"] == width && page["height"] == height))
|
||||
&& let Some(page_id) = page["documentId"].as_str()
|
||||
{
|
||||
artifact["pageId"] = json!(page_id);
|
||||
}
|
||||
Ok(artifact)
|
||||
};
|
||||
let (files, split) = if let [region @ (0, width, height)] = regions && !screens.is_empty() {
|
||||
if screens.iter().any(|&(top, w, h)| w > *width || top.checked_add(h).is_none_or(|end| end > *height)) {
|
||||
return Err("详情分屏超出长图范围".into());
|
||||
}
|
||||
let coordinates = screens.iter().map(|&(top, width, height)|
|
||||
(top as u32, width as u32, height as u32)).collect::<Vec<_>>();
|
||||
let options = photocraft_io::ExportOptions {xmp:photocraft_io::XmpEmbed::None, ..Default::default()};
|
||||
let (long, splits) = with_export_region(&reopened, *region, |doc| {
|
||||
photocraft_io::export_jpeg_with_screens(doc, &coordinates, &options)
|
||||
.map_err(|error| format!("长图和分屏导出失败:{error}"))
|
||||
})?;
|
||||
if splits.len() != screens.len() {
|
||||
return Err("导出的分屏数量与模板不一致".into());
|
||||
}
|
||||
let full = save_region("detail.jpg", component, *region, long.bytes)?;
|
||||
let split = screens.iter().zip(splits).enumerate().map(|(index, (®ion, image))|
|
||||
save_region(&format!("detail-S{:02}.jpg", index+1), "detail-screen", region, image.bytes))
|
||||
.collect::<R<Vec<_>>>()?;
|
||||
(vec![full], split)
|
||||
} else {
|
||||
let files = regions.iter().enumerate().map(|(index, ®ion)| {
|
||||
let name = if regions.len() > 1 { format!("{component}-{:02}.jpg", index+1) } else { format!("{component}.jpg") };
|
||||
save_region(&name, component, region, export_jpg_region(&reopened, region)?.bytes)
|
||||
}).collect::<R<Vec<_>>>()?;
|
||||
(files, Vec::new())
|
||||
};
|
||||
let size = fs::metadata(&editable).map_err(|error| format!("无法读取成品工程信息:{error}"))?.len();
|
||||
let sha = file_digest(&editable).map_err(|error| format!("无法核对成品工程内容:{error}"))?;
|
||||
let delivery = json!({"state":"output_exported","outputState":"exported","outputId":component,"generationId":id});
|
||||
result["reopenVerification"] = reopen_verification;
|
||||
result["generationId"] = json!(id);
|
||||
result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id,
|
||||
"revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height,
|
||||
"sizeBytes":size,"sha256":sha});
|
||||
if let Some(working_sha) = result.as_object_mut().and_then(|row| row.remove("workingSha256")) {
|
||||
result["sourceDocument"]["workingSha256"] = working_sha;
|
||||
}
|
||||
result["layeredDocument"] = layered;
|
||||
result["files"] = json!(files);
|
||||
if !split.is_empty() { result["screenFiles"] = json!(split); }
|
||||
result["editable"] = json!(editable);
|
||||
result["productionDelivery"] = delivery;
|
||||
result["validation"] = json!({"mode":"full","editableReopened":true,
|
||||
"filesVerified":2 + regions.len() + screens.len(),"validatedAt":chrono::Utc::now().timestamp_millis()});
|
||||
write_json(&generation.path().join("manifest.json"), result)?;
|
||||
// A replacement can report a directory flush error after the rename.
|
||||
// Keep the complete generation before attempting to publish its pointer.
|
||||
let pointer = manifest_path(id);
|
||||
let _ = generation.keep();
|
||||
use photocraft_format::atomic::{AtomicFs, RealFs};
|
||||
RealFs.sync_dir(&root).map_err(|error| format!("成品版本目录保存未确认:{error}"))?;
|
||||
let _guard = sync::context_guard();
|
||||
result["publishedPointer"] = json!(pointer);
|
||||
write_json(receipt, result)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str, snapshot: Option<&Document>) -> R<Value> {
|
||||
export_product_stage_with_source(dir, doc, state, input, scope, snapshot, None)
|
||||
}
|
||||
|
||||
pub(crate) fn export_product_stage_with_source(
|
||||
dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str,
|
||||
snapshot: Option<&Document>, working_sha: Option<&str>,
|
||||
) -> R<Value> {
|
||||
let component = input["outputId"].as_str().filter(|kind| SUPPORTED_PRODUCTION_OUTPUTS.contains(kind)).ok_or("制作输出缺失")?;
|
||||
let variant_id = uuid(&input["variantId"], "制作款式")?;
|
||||
if !state["productTemplates"].is_object() || input["workspaceId"] != state["id"]
|
||||
|| (snapshot.is_none() && (input["outputId"] != state["activeOutput"]
|
||||
|| input["variantId"] != state["activeVariantId"]
|
||||
|| read_json(&dir.join("context.json"))?["revision"] != input["baseRevision"])) {
|
||||
return Err("已保存画布与制作任务不一致".into());
|
||||
}
|
||||
let scoped;
|
||||
let state = if snapshot.is_some() {
|
||||
let pack = state["productTemplates"].get(component).filter(|pack| pack.is_object())
|
||||
.ok_or("当前产品模板已变化")?;
|
||||
if variant(state, &variant_id).is_err() || !output_uses_variant(&state["brief"], component, &variant_id) {
|
||||
return Err("制作款式不属于当前输出".into());
|
||||
}
|
||||
let mut bound = state.clone();
|
||||
bound["activeOutput"] = json!(component);
|
||||
bound["activeVariantId"] = json!(variant_id);
|
||||
if pack["contentHash"] != state["template"]["contentHash"] {
|
||||
bound["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string()));
|
||||
}
|
||||
bound["template"] = pack.clone();
|
||||
scoped = bound;
|
||||
&scoped
|
||||
} else { state };
|
||||
let mut result = json!({"doc":doc,"workspaceId":state["id"],"outputId":component,"variantId":variant_id,
|
||||
"canvasRevision":input["baseRevision"],"documentKey":input["documentKey"],"operationId":input["operationId"],"files":[],
|
||||
"allOutputsCompleted":false,"missingSlots":[],"unreviewedScreens":[],"deliveryStatus":"failed"});
|
||||
if let Some(version) = state["template"]["xiaoyi"]["knowledgeVersion"].as_str().or_else(|| input["knowledgeVersion"].as_str()) {
|
||||
result["knowledgeVersion"] = json!(version);
|
||||
}
|
||||
if input["complete"] != true {
|
||||
result["productionDelivery"] = json!({"state":"pending","outputId":component});
|
||||
result["stageStatus"] = input["stageStatus"].clone();
|
||||
result["blocker"] = input["blocker"].clone();
|
||||
result["originals"] = input["originals"].clone();
|
||||
result["canContinue"] = input["canContinue"].clone();
|
||||
result["issues"] = input["issues"].clone();
|
||||
result["editable"] = json!(dir.join("template-outputs")
|
||||
.join(format!("canvas-{}-edited.pcraft", mapping_key(&variant_id, component, None))));
|
||||
return Ok(result);
|
||||
}
|
||||
result["exportAttempted"] = json!(true);
|
||||
let blocked = |mut result: Value| {
|
||||
result["productionDelivery"] = json!({"state":"blocked","outputId":component});
|
||||
Ok(result)
|
||||
};
|
||||
let loaded;
|
||||
let native = match snapshot {
|
||||
Some(canvas) => canvas,
|
||||
None => {
|
||||
let _guard = sync::context_guard();
|
||||
let path = edited_delivery_canvas(dir, state, &variant_id, component)?
|
||||
.ok_or("本组没有已保存的可编辑画布")?;
|
||||
loaded = super::load_draft(dir, &path).map_err(|_| "可编辑画布无法读取")?;
|
||||
result["workingSha256"] = json!(file_digest(&path).map_err(|_| "无法核对编辑稿内容")?);
|
||||
&loaded
|
||||
}
|
||||
};
|
||||
if let Some(sha) = working_sha {
|
||||
result["workingSha256"] = json!(sha);
|
||||
}
|
||||
let meta = mapping(native).ok_or("可编辑画布缺少图层映射")?;
|
||||
if snapshot.is_some() && input["canvasRevision"].is_u64()
|
||||
&& (native.id.0 != doc || input["canvasRevision"] != input["baseRevision"])
|
||||
|| meta["workspaceId"] != state["id"]
|
||||
|| meta["component"] != component || meta["variantId"] != variant_id
|
||||
|| input["documentKey"].is_object()
|
||||
&& !photocraft_ui_egui::jiansun::same_canvas_target(
|
||||
&photocraft_ui_egui::jiansun::product_document_key(native), &input["documentKey"]) {
|
||||
return Err("可编辑画布与目标项目、成品或花色不一致".into());
|
||||
}
|
||||
let aspects = main_image_aspects(dir, &state["template"], component)?;
|
||||
let planned_pages: Vec<_> = production_export_pages(&state["template"], component, &aspects).collect();
|
||||
if !aspects.is_null() && planned_pages.is_empty() {
|
||||
return Err("主图制作画幅未匹配到模板登记的图位".into());
|
||||
}
|
||||
let profile = production_profile::select(&state["template"], component)?;
|
||||
result["fidelityReport"] = fidelity::report(native, &meta);
|
||||
let missing_fonts = photocraft_engine::type_extra_cmds::missing_fonts(native);
|
||||
if !missing_fonts.is_empty() {
|
||||
result["missingFonts"] = json!(missing_fonts);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
result["productionProfile"] = production_profile::source(&state["template"], component);
|
||||
if let Some(layer) = production_profile::visible_sample_layer(native, profile, &meta) {
|
||||
result["visibleSampleLayer"] = json!(layer.name);
|
||||
result["visibleSampleLayerId"] = json!(layer.id.0);
|
||||
}
|
||||
let missing_text = production_profile::missing_visible_text(native, &meta, profile);
|
||||
if !missing_text.is_empty() {
|
||||
result["missingVisibleText"] = json!(missing_text);
|
||||
}
|
||||
}
|
||||
if production_profile::fixed_text_policy(profile) {
|
||||
if let Some(layer) = production_profile::unapproved_fixed_text(native, &meta) {
|
||||
result["unapprovedFixedTextLayer"] = json!(layer.name);
|
||||
result["unapprovedFixedTextLayerId"] = json!(layer.id.0);
|
||||
}
|
||||
} else {
|
||||
result["warnings"] = json!([production_profile::UNPUBLISHED_FIXED_TEXT]);
|
||||
}
|
||||
let variant_id_ref = &variant_id;
|
||||
let review_hints = meta["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.flat_map(|field| {
|
||||
[&field["review_hint"], &field["manualReviewHint"]].into_iter()
|
||||
.chain(field["reviewHints"].as_array().into_iter().flatten())
|
||||
.filter_map(move |hint| {
|
||||
let message = hint.as_str().or_else(|| hint["message"].as_str())?;
|
||||
Some(json!({"outputId":component,"variantId":variant_id_ref,"layerId":field["nativeLayerId"],
|
||||
"slotId":field["slotId"],"message":message}))
|
||||
})
|
||||
}).collect::<Vec<_>>();
|
||||
if !review_hints.is_empty() { result["reviewHints"] = json!(review_hints); }
|
||||
let (missing, invalid_sources, image_sources, coverage) = export_image_sources(dir, native, state, &meta, component, &variant_id, &aspects);
|
||||
result["slotCoverage"] = coverage;
|
||||
let missing_issues: Vec<_> = missing.iter().map(|field| json!({
|
||||
"outputId":component,"variantId":variant_id,"field":field,"reason":"图位尚未采用图片"
|
||||
})).collect();
|
||||
result["knownIssues"] = json!(missing_issues);
|
||||
result["missingSlots"] = json!(missing);
|
||||
set_delivery_status(&mut result, false);
|
||||
if !missing.is_empty() {
|
||||
result["missingImages"] = json!(missing);
|
||||
}
|
||||
if !invalid_sources.is_empty() {
|
||||
result["invalidImageSources"] = json!(invalid_sources);
|
||||
return blocked(result);
|
||||
}
|
||||
let journal = production_audit(dir, state, component, &variant_id, scope)?;
|
||||
if input["deliveryReason"].is_string() {
|
||||
let mut issues = Vec::new();
|
||||
for review in journal["screenReviews"].as_array().into_iter().flatten() {
|
||||
let Some(page) = review[0].as_u64() else { continue; };
|
||||
for issue in review[1]["issues"].as_array().into_iter().flatten() {
|
||||
if let Some(reason) = issue["issue"].as_str().or_else(|| issue["reason"].as_str()) {
|
||||
issues.push(json!({"page":page+1,"reason":reason}));
|
||||
}
|
||||
}
|
||||
}
|
||||
for slot in &missing {
|
||||
issues.push(json!({"field":slot,"reason":"图位尚未采用图片"}));
|
||||
}
|
||||
for field in meta["outputs"].as_array().into_iter().flatten()
|
||||
.filter(|page| aspects.is_null() || planned_pages.iter().any(|plan| plan["id"] == page["documentId"]))
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.filter(|field| field["kind"] == "text")
|
||||
{
|
||||
let filled = if field["embeddedTarget"].is_object() {
|
||||
photocraft_ui_egui::jiansun::production_facts::read_embedded_layer(native, &field["embeddedTarget"], |child, inner_id| {
|
||||
Ok(child.layer(inner_id).is_some_and(|layer| matches!(&layer.content, photocraft_doc::LayerContent::Text(text)
|
||||
if !text.text.trim().is_empty() && field["originalText"].as_str() != Some(text.text.as_str()))))
|
||||
}).unwrap_or(false)
|
||||
} else {
|
||||
let text = field["nativeLayerId"].as_u64().and_then(|id| native.layer(photocraft_doc::LayerId(id)));
|
||||
text.is_some_and(|layer| matches!(&layer.content, photocraft_doc::LayerContent::Text(text)
|
||||
if !text.text.trim().is_empty() && field["originalText"].as_str() != Some(text.text.as_str())))
|
||||
};
|
||||
if !filled {
|
||||
issues.push(json!({"field":field["fieldId"],"reason":"文案格尚未填写"}));
|
||||
}
|
||||
}
|
||||
for issue in &mut issues {
|
||||
issue["outputId"] = json!(component);
|
||||
issue["variantId"] = json!(variant_id);
|
||||
}
|
||||
result["issues"] = json!(issues);
|
||||
}
|
||||
let unverified_copy = unverified_export_copy(native, &meta, &journal);
|
||||
if !unverified_copy.is_empty() {
|
||||
result["unverifiedCopy"] = json!(unverified_copy);
|
||||
}
|
||||
let path = receipt_path(dir, &variant_id, component);
|
||||
let pages = meta["outputs"].as_array().ok_or("没有可导出的画布页面")?;
|
||||
let regions = product_export_regions(pages.iter().filter(|page| aspects.is_null() ||
|
||||
planned_pages.iter().any(|planned| planned["id"] == page["documentId"])), component)?;
|
||||
let expected = product_export_regions(planned_pages, component)?;
|
||||
if regions != expected || regions.iter().any(|&(top, width, height)|
|
||||
width > u64::from(native.size.width) || top + height > u64::from(native.size.height))
|
||||
{
|
||||
return Err("画布的可见成品范围与当前模板登记不一致".into());
|
||||
}
|
||||
let screens = if component == "detail" {
|
||||
let screens = template_screen_regions(pages)?;
|
||||
let expected_screens = template_screen_regions(state["template"]["outputs"].as_array().into_iter()
|
||||
.flatten().filter(|page| page["component"] == component))?;
|
||||
if screens != expected_screens {
|
||||
return Err("详情分屏位置与模板不一致".into());
|
||||
}
|
||||
screens
|
||||
} else { Vec::new() };
|
||||
let reviewed = &journal["screenReviews"];
|
||||
result["unreviewedScreens"] = json!((0..screens.len()).filter(|index|
|
||||
!reviewed.as_array().into_iter().flatten().any(|review| review[0].as_u64() == Some(*index as u64)))
|
||||
.map(|index| index + 1).collect::<Vec<_>>());
|
||||
let creation = creation::load(dir)?;
|
||||
result["briefRevision"] = creation["revision"].clone();
|
||||
result["stageInputHash"] = json!(stage_input_hash(state, &creation, &variant_id, component)?);
|
||||
result["deliveryInputHash"] = json!(delivery_input_hash(state, &creation, &variant_id, component)?);
|
||||
result["templateHash"] = state["template"]["contentHash"].clone();
|
||||
result["imageSources"] = json!(image_sources);
|
||||
result["unverifiedFacts"] = json!(input["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice));
|
||||
if !aspects.is_null() { result["mainImageAspects"] = aspects; }
|
||||
let all_filled = missing.is_empty() && production_stages(state).iter().all(|stage| {
|
||||
let variant = stage["variantId"].as_str().unwrap_or_default();
|
||||
let output = stage["outputId"].as_str().unwrap_or_default();
|
||||
(variant == variant_id && output == component) ||
|
||||
published_receipt(&receipt_path(dir, variant, output)).is_ok_and(|receipt|
|
||||
receipt["missingImages"].as_array().is_none_or(Vec::is_empty)
|
||||
&& receipt["unreviewedScreens"].as_array().is_none_or(Vec::is_empty))
|
||||
});
|
||||
let reviewed = result["unreviewedScreens"].as_array().is_some_and(Vec::is_empty);
|
||||
let complete = reviewed && all_filled && remaining_stages(dir, state, &result["briefRevision"], false)
|
||||
.iter().all(|stage| stage["variantId"] == variant_id && stage["outputId"] == component);
|
||||
set_delivery_status(&mut result, complete);
|
||||
let blank_reasons: serde_json::Map<String, Value> = journal["copyEvidence"].as_object().into_iter().flatten()
|
||||
.filter(|(_, row)| row["text"].as_str().is_some_and(|text| text.trim().is_empty()))
|
||||
.filter_map(|(id, row)| {
|
||||
let reason = row["blankReason"].as_str().filter(|reason| !reason.trim().is_empty())?;
|
||||
Some((id.clone(), json!({"field":row["field"],"reason":reason})))
|
||||
}).collect();
|
||||
if !blank_reasons.is_empty() {
|
||||
result["blankCopyReasons"] = Value::Object(blank_reasons);
|
||||
}
|
||||
publish_product_generation(&path, native, &input["baseRevision"], &mut result, ®ions, &screens)?;
|
||||
let mut remaining = remaining_stages(dir, state, &result["briefRevision"], false);
|
||||
if remaining.is_empty() {
|
||||
remaining = remaining_stages(dir, state, &result["briefRevision"], true);
|
||||
}
|
||||
set_delivery_status(&mut result, remaining.is_empty() && all_filled && reviewed);
|
||||
if result["allOutputsCompleted"] == true
|
||||
&& let Some(goal) = input["piGoalId"].as_str()
|
||||
&& let Err(error) = super::pi_runtime::record_product_export(dir, scope, goal)
|
||||
{
|
||||
result["goalSyncError"] = json!(error);
|
||||
}
|
||||
result["productionDelivery"] = json!({"state":if result["allOutputsCompleted"] == true {"completed"} else {"in_progress"},
|
||||
"outputState":"exported","outputId":component,"generationId":result["generationId"]});
|
||||
result["productionStages"] = json!(runnable_stages(state, remaining));
|
||||
Ok(result)
|
||||
}
|
||||
// Older projects stored the mapping's combined requirements. Use the original
|
||||
// typed fields from the cached mapping for that same fixed template version.
|
||||
pub(crate) fn cached_prompt_mapping(dir: &Path, pack: &Value) -> Option<Value> {
|
||||
if let Some(file) = pack["enterprise"]["mappingPath"].as_str() {
|
||||
return read_json(Path::new(file)).ok();
|
||||
}
|
||||
let component = pack["enterprise"]["component"].as_str()?;
|
||||
let mapping_id = pack["enterprise"]["components"][component]["mappingAssetId"].as_str()?;
|
||||
let mapping = pack["resourceFiles"].as_array()?.iter()
|
||||
.find(|file| file["fileId"] == mapping_id && file["role"] == "mapping")?;
|
||||
let revision = mapping["revision"].as_str()?;
|
||||
let documents = dir.parent()?.parent()?.join("enterprise-templates").join("documents");
|
||||
let filename = format!("{mapping_id}-{revision}.json");
|
||||
let legacy_suffix = format!("%2Fa-{filename}");
|
||||
fs::read_dir(documents).ok()?.flatten().find_map(|entry| {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_str()?;
|
||||
if name != filename && !(name.starts_with("ekb%3Arelease%2F") && name.ends_with(&legacy_suffix)) {
|
||||
return None;
|
||||
}
|
||||
let raw = read_json(&entry.path()).ok()?;
|
||||
(raw["template_id"] == pack["id"]
|
||||
&& raw["component"].as_str().unwrap_or("detail") == component
|
||||
&& raw["fields"].is_array()).then_some(raw)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn editable_image_prompt(field: &Value, page: &Value, cached_mapping: Option<&Value>) -> Option<String> {
|
||||
let text = match field.get("imagePrompt") {
|
||||
Some(value) => value.as_str(),
|
||||
None => field["prompt"].as_str().or_else(|| {
|
||||
let fields = cached_mapping?["fields"].as_array()?;
|
||||
fields.iter().find(|item| item["field_id"] == field["fieldId"]
|
||||
&& item["screen_id"] == *page && item["type"] == "图片")?["fill_requirements"].as_str()
|
||||
}),
|
||||
}?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let lines: Vec<_> = text.lines().map(str::trim).filter(|line| !line.is_empty() && seen.insert(*line)).collect();
|
||||
(!lines.is_empty()).then(|| lines.join("\n"))
|
||||
}
|
||||
|
||||
@ -0,0 +1,502 @@
|
||||
#[cfg(test)]
|
||||
use super::encode_template_rgba;
|
||||
use super::super::{Arc, Backend, Document, PathBuf, R, Value, images, json, load_draft, production_profile, sync};
|
||||
use super::{approved_structure_guides, candidate_available, candidate_pixels, candidate_uses_current_inputs, definition, guide_visibility, load_detail_workspace, mapped_fields, mapping, mapping_key, placement_pixels, production_audit, production_output_state, read_candidate, revision, screen_preview, template_fidelity, text, uuid, variant};
|
||||
use photocraft_ui_egui::jiansun::production_facts::{screen_area, screen_fingerprint, screen_overlay_layers};
|
||||
|
||||
pub(crate) fn production_placement_fit(record: &Value, field: &Value, requested: &Value, batch: bool) -> Value {
|
||||
let batch_fit = batch && matches!(requested.as_str(), Some("cover" | "contain"));
|
||||
if record["sourceType"] == "product-reference" {
|
||||
if batch_fit && record["binding"]["referenceCrop"].is_array() { requested.clone() }
|
||||
else { json!("contain") }
|
||||
} else if batch_fit { requested.clone() }
|
||||
else { field["crop"].clone() }
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn load_saved_output_canvas(&self, doc: u64, input: &Value) -> R<(PathBuf, Document, Value)> {
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
let target = &input["targetOutput"];
|
||||
let variant = uuid(&target["variantId"], "花色")?;
|
||||
let component = target["outputId"].as_str()
|
||||
.filter(|id| matches!(*id, "detail" | "main_images" | "sku_images"))
|
||||
.ok_or("成品类型无效")?;
|
||||
let key = mapping_key(&variant, component, None);
|
||||
let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
let mut native = super::load_draft(&dir, &file).map_err(|_| "该成品的已保存工作画布无法读取")?;
|
||||
native.id = photocraft_doc::DocId(doc);
|
||||
let meta = mapping(&native).ok_or("已保存画布缺少模板映射")?;
|
||||
if meta["workspaceId"] != input["workspaceId"] || meta["variantId"] != variant || meta["component"] != component {
|
||||
return Err("已保存画布与目标成品不一致".into());
|
||||
}
|
||||
Ok((file, native, meta))
|
||||
}
|
||||
|
||||
pub(crate) fn read_saved_copy_fields(&self, doc: u64, input: &Value) -> R<Value> {
|
||||
let (_, native, _) = self.load_saved_output_canvas(doc, input)?;
|
||||
photocraft_ui_egui::jiansun::detail_copy_snapshot(&native, None, &input["query"])
|
||||
}
|
||||
|
||||
pub(crate) fn read_saved_candidate_screen(&self, doc: u64, input: &Value) -> R<Value> {
|
||||
let mut timing = photocraft_ui_egui::operation_timer::OperationTimer::new("pi-product-screen", None, false);
|
||||
use photocraft_doc::{LayerContent, LayerId};
|
||||
use photocraft_engine::smart_cmds::freeze_source;
|
||||
let (file, native, meta) = self.load_saved_output_canvas(doc, input)?;
|
||||
timing.set_document(&native);
|
||||
let slot = &input["candidatePreview"]["slotId"];
|
||||
let layer = mapped_fields(&meta).find(|field| field["kind"] == "image" && field["slotId"] == *slot)
|
||||
.and_then(|field| field["nativeLayerId"].as_u64()).map(LayerId).ok_or("已保存画布没有此图位")?;
|
||||
let mut query = input.clone();
|
||||
query["candidatePreview"]["nativeLayerId"] = json!(layer.0);
|
||||
let LayerContent::Smart(smart) = &native.layer(layer).ok_or("候选图位缺失")?.content else {
|
||||
return self.read_candidate_screen(&native, &query, None);
|
||||
};
|
||||
let contents = smart.contents_id;
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(native, Some(file.to_string_lossy().into_owned()));
|
||||
let active = session.active().ok_or("已保存画布无法读取")?;
|
||||
let ticket = freeze_source(&session, active.doc.id, active.revision, layer, contents)
|
||||
.map_err(|error| error.to_string())?;
|
||||
self.read_candidate_screen(&active.doc, &query, Some(&ticket))
|
||||
}
|
||||
|
||||
pub(crate) fn attach_template_fidelity(&self, native: &Document, receipt: &mut Value, include_image: bool, detail_layer: Option<u64>) -> R<()> {
|
||||
let dir = self.project_dir(native.id.0)?;
|
||||
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));
|
||||
}
|
||||
}
|
||||
template_fidelity::attach(&dir, native, receipt, include_image, detail_layer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read_candidate_screen(
|
||||
&self, native: &Document, input: &Value, ticket: Option<&photocraft_engine::smart_cmds::SourceTicket>,
|
||||
) -> R<Value> {
|
||||
use photocraft_ui_egui::jiansun::{prepare_adoption_document, update_structure_guides};
|
||||
let request = &input["candidatePreview"];
|
||||
let slot = request["slotId"].as_str().ok_or("候选预览图位缺失")?;
|
||||
let candidate = uuid(&request["candidateId"], "候选")?;
|
||||
let layer = request["nativeLayerId"].as_u64().ok_or("候选预览图层缺失")?;
|
||||
let meta = mapping(native).ok_or("工作画布缺少模板映射")?;
|
||||
let pages = meta["outputs"].as_array().ok_or("工作画布没有页面")?;
|
||||
let index = pages.iter().position(|page| page["mapping"]["fields"].as_array().into_iter().flatten()
|
||||
.any(|field| field["kind"] == "image" && field["slotId"] == slot && field["nativeLayerId"] == layer))
|
||||
.ok_or("候选图位未映射到工作画布的页面")?;
|
||||
let variant = meta["variantId"].as_str().ok_or("候选预览花色缺失")?;
|
||||
let mut query = input.clone();
|
||||
query["page"] = json!(index);
|
||||
if request["adopted"] != true && !native.layer(photocraft_doc::LayerId(layer)).is_some_and(|layer|
|
||||
matches!(layer.content, photocraft_doc::LayerContent::Smart(_)))
|
||||
{
|
||||
return Ok(json!({"candidateId":candidate,"slotId":slot,"page":index,
|
||||
"previewAvailable":false,"reason":"slot_not_smart_layer","message":"当前图位暂无法合成候选预览","images":[]}));
|
||||
}
|
||||
let mut receipt = if request["adopted"] == true {
|
||||
let key = format!("jiansun.adopted.{variant}.{slot}");
|
||||
if !native.metadata.text.iter().any(|(k, v)| k == &key && v == &candidate) {
|
||||
return Err("当前图位没有采纳这一候选".into());
|
||||
}
|
||||
let mut receipt = read_screen_preview(native, &query)?;
|
||||
self.attach_template_fidelity(native, &mut receipt, true, None)?;
|
||||
receipt
|
||||
} else {
|
||||
self.ensure_owner(native.id.0)?;
|
||||
let dir = self.project_dir(native.id.0)?;
|
||||
let state = load_detail_workspace(&dir)?;
|
||||
let component = meta["component"].as_str().ok_or("候选预览成品类型缺失")?;
|
||||
let state = if state["activeOutput"] == component && state["activeVariantId"] == variant {
|
||||
state
|
||||
} else { production_output_state(state, component, variant)? };
|
||||
let (output, field) = definition(&state, slot, variant)?;
|
||||
let record = read_candidate(&dir, &candidate)?;
|
||||
if !candidate_available(&record) || record["binding"]["slotId"] != slot
|
||||
|| record["binding"]["variantId"] != variant || record["binding"]["templateHash"] != meta["templateHash"]
|
||||
|| !candidate_uses_current_inputs(&dir, &state, &record, variant)?
|
||||
{
|
||||
return Err("候选未完成或与当前图位、商品资料不一致".into());
|
||||
}
|
||||
let fit = production_placement_fit(&record, field, &request["fit"], true);
|
||||
let mut placement = json!({"detailBatch":true,"slotId":slot,"candidateId":candidate,
|
||||
"nativeLayerId":layer,"variantId":variant,"fit":fit,"fitRequested":request["fit"].is_string()});
|
||||
let bytes = placement_pixels(candidate_pixels(&dir, &record["artifact"])?)?.0;
|
||||
let ticket = ticket.ok_or("候选预览缺少原图层快照")?;
|
||||
let mut composed = prepare_adoption_document(native, &placement, bytes, ticket, false)?.document;
|
||||
if let Some(component) = output["component"].as_str()
|
||||
&& let Some(profile) = production_profile::select(&state["template"], component)?
|
||||
&& let Some(field) = field["fieldId"].as_str()
|
||||
&& let Some(recipe) = profile["imageRules"][field].get("structureGuides")
|
||||
{
|
||||
let audit = production_audit(&dir, &state, component, variant, &self.scope())?;
|
||||
if let Some(guides) = approved_structure_guides(recipe, &audit["items"][slot], &candidate)? {
|
||||
placement["structureGuides"] = guides;
|
||||
}
|
||||
}
|
||||
update_structure_guides(&mut composed, photocraft_doc::LayerId(layer), &placement)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut receipt = read_screen_preview(&composed, &query)?;
|
||||
template_fidelity::attach(&dir, &composed, &mut receipt, true, None);
|
||||
receipt["fit"] = fit;
|
||||
receipt["pageName"] = output["name"].clone();
|
||||
receipt
|
||||
};
|
||||
receipt["candidateId"] = json!(candidate);
|
||||
receipt["slotId"] = json!(slot);
|
||||
Ok(receipt)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn render_template_edit(
|
||||
mut original: Document, id: photocraft_doc::LayerId, original_frame: &Value, frame: &Value,
|
||||
) -> R<Vec<u8>> {
|
||||
let path = original.path_of(id).ok_or("原稿图层不存在")?;
|
||||
let (&index, parents) = path.split_last().ok_or("原稿图层不存在")?;
|
||||
let mut layers = &mut original.layers;
|
||||
// Keep the backdrop at each level and preserve the groups' compositing settings.
|
||||
for &parent in parents {
|
||||
layers.truncate(parent + 1);
|
||||
layers = layers[parent].children_mut().ok_or("原稿图层组不存在")?;
|
||||
}
|
||||
let end = layers[index + 1..].iter().take_while(|layer| layer.clipped).count();
|
||||
layers.truncate(index + 1 + end);
|
||||
let x = original_frame["x"].as_f64().ok_or("原稿图框横坐标无效")?.round() as i32;
|
||||
let y = original_frame["y"].as_f64().ok_or("原稿图框纵坐标无效")?.round() as i32;
|
||||
let extent = |key| frame[key].as_f64().filter(|n| (1.0..=8192.0).contains(n))
|
||||
.map(|n| n.round() as i32).ok_or("图框尺寸无效");
|
||||
let (width, height) = (extent("width")?, extent("height")?);
|
||||
let area = photocraft_geom::Rect::new(x, y, x + width, y + height);
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode};
|
||||
let pixels = photocraft_compose::render(&original, area).to_rgba8();
|
||||
let mut rgb = Vec::with_capacity((width * height * 3) as usize);
|
||||
for pixel in pixels.pixels.chunks_exact(4) {
|
||||
let alpha = u16::from(pixel[3]);
|
||||
rgb.extend(pixel[..3].iter().map(|&channel|
|
||||
((u16::from(channel) * alpha + 255 * (255 - alpha) + 127) / 255) as u8
|
||||
));
|
||||
}
|
||||
let image = Image::from_u8(width as u32, height as u32, ChannelLayout::Rgb, rgb)
|
||||
.map_err(|_| "模板图位像素无效")?;
|
||||
let options = EncodeOptions { jpeg_quality: 92, ..Default::default() };
|
||||
encode(&image, Format::Jpeg, &options).map_err(|_| "模板图位无法编码".into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) fn jiansun_template_edit_crops_the_composited_layer_stack() {
|
||||
use photocraft_doc::{Adjustment, Layer, LayerContent};
|
||||
let feathered: Vec<_> = (0..16).flat_map(|_| {
|
||||
(0..16).flat_map(|x| [48, 48, 48, 16 * x + 8])
|
||||
}).collect();
|
||||
let mut original = crate::jiansun_document::import(
|
||||
&json!({"name":"fixture","screens":[{"name":"test","width":20,"height":20,"background":"#ffffff","layers":[
|
||||
{"kind":"image","name":"base","source":"base","x":2,"y":2,"width":16,"height":16},
|
||||
{"kind":"shape","name":"overlay","shape":"rect","color":"#0033ff","x":2,"y":2,"width":16,"height":16}
|
||||
]}]}),
|
||||
&std::collections::HashMap::from([("base".to_owned(), encode_template_rgba(16, 16, feathered).unwrap())]),
|
||||
).unwrap();
|
||||
let (path, _, layer) = original.walk().into_iter().find(|(_, _, layer)| layer.name == "base").unwrap();
|
||||
let id = layer.id;
|
||||
let (&index, parents) = path.split_last().unwrap();
|
||||
assert!(!parents.is_empty());
|
||||
let siblings = original.layer_at_mut(parents).unwrap().children_mut().unwrap();
|
||||
let mut adjustment = Layer::new("反相", LayerContent::Adjustment(Adjustment::Invert));
|
||||
adjustment.clipped = true;
|
||||
siblings.insert(index + 1, adjustment);
|
||||
original.layers.push(Layer::new("上方装饰", LayerContent::Adjustment(Adjustment::Invert)));
|
||||
|
||||
let frame = json!({"x":4,"y":4,"width":12,"height":8});
|
||||
let bytes = render_template_edit(original, id, &frame, &frame).unwrap();
|
||||
let jpeg = photocraft_codecs::decode_as(photocraft_codecs::Format::Jpeg, &bytes).unwrap();
|
||||
assert_eq!((jpeg.width(), jpeg.height()), (12, 8));
|
||||
assert_eq!(jpeg.layout(), photocraft_codecs::ChannelLayout::Rgb);
|
||||
for (index, pixel) in jpeg.data().chunks_exact(3).enumerate() {
|
||||
let alpha = 16 * (index % 12 + 2) + 8;
|
||||
// Invert 48 to 207, then composite it over white.
|
||||
let expected = (255 - (48 * alpha + 127) / 255) as u8;
|
||||
assert!(pixel.iter().all(|&channel| channel.abs_diff(expected) <= 3),
|
||||
"pixel {index}: expected {expected}, got {pixel:?}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn subject_bounds(
|
||||
surface: &photocraft_raster::Surface, frame: photocraft_geom::Rect,
|
||||
) -> Result<[i32; 4], &'static str> {
|
||||
let source = surface.content_bounds();
|
||||
let pixels = source.intersect(&frame);
|
||||
if pixels.is_empty() { return Err("图位内没有可测像素"); }
|
||||
let rgba = photocraft_color::PixelFormat::new(
|
||||
photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, true);
|
||||
let distance = |a: &[f32], b: &[f32]| {
|
||||
a[..3].iter().zip(&b[..3]).map(|(a,b)| (a-b).abs()).fold(0.0_f32, f32::max)
|
||||
};
|
||||
let format = surface.format();
|
||||
let sample = |x,y| {
|
||||
if format.mode == photocraft_color::ColorMode::Rgb {
|
||||
let mut pixel = [0.0, 0.0, 0.0, 1.0];
|
||||
surface.read_pixel(x, y, &mut pixel[..format.channels()]);
|
||||
pixel
|
||||
} else {
|
||||
let pixel = photocraft_raster::convert_pixel(&format, &rgba, &surface.pixel(x,y));
|
||||
[pixel[0], pixel[1], pixel[2], pixel[3]]
|
||||
}
|
||||
};
|
||||
// A resampled image can have a partially transparent fringe around the photograph.
|
||||
let inset = if source.width().min(source.height()) > 4 { 2 } else { 0 };
|
||||
let (left,top,right,bottom) = (source.x0+inset,source.y0+inset,source.x1-inset,source.y1-inset);
|
||||
let edge = (left..right).flat_map(|x| [(x,top),(x,bottom-1)])
|
||||
.chain((top..bottom).flat_map(|y| [(left,y),(right-1,y)]));
|
||||
let mut opaque_edge = edge.map(|(x,y)| sample(x,y)).filter(|pixel| pixel[3] >= 0.5);
|
||||
let background = opaque_edge.next().ok_or("图像边缘没有不透明背景样本")?;
|
||||
let (different,total) = opaque_edge.fold((0,1), |(different,total),pixel|
|
||||
(different + usize::from(distance(&background,&pixel) > 0.12),total + 1));
|
||||
if different * 10 > total {
|
||||
return Err("图像边缘颜色不均匀");
|
||||
}
|
||||
let mut bounds = photocraft_geom::Rect::new(0,0,0,0);
|
||||
for y in pixels.y0..pixels.y1 {
|
||||
for x in pixels.x0..pixels.x1 {
|
||||
let pixel = sample(x,y);
|
||||
if pixel[3] >= 0.5 && distance(&background,&pixel) > 0.12 {
|
||||
bounds = bounds.union(&photocraft_geom::Rect::new(x,y,x+1,y+1));
|
||||
}
|
||||
}
|
||||
}
|
||||
if bounds.is_empty() { return Err("主体与背景的色差不足"); }
|
||||
Ok([bounds.x0,bounds.y0,bounds.x1-bounds.x0,bounds.y1-bounds.y0])
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) fn subject_bounds_measure_flat_background_and_reject_uneven_edges() {
|
||||
use photocraft_color::PixelFormat;
|
||||
use photocraft_geom::Rect;
|
||||
let mut surface = photocraft_raster::Surface::new(PixelFormat::RGBA8);
|
||||
let frame = Rect::new(10, 20, 110, 100);
|
||||
surface.fill_rect(frame, &[1.0, 1.0, 1.0, 1.0]);
|
||||
surface.fill_rect(Rect::new(32, 38, 84, 81), &[0.2, 0.1, 0.1, 1.0]);
|
||||
assert_eq!(subject_bounds(&surface, frame), Ok([32, 38, 52, 43]));
|
||||
assert_eq!(subject_bounds(&surface, Rect::new(40, 20, 110, 100)), Ok([40, 38, 44, 43]));
|
||||
surface.fill_rect(Rect::new(10, 20, 60, 100), &[0.3, 0.4, 0.5, 1.0]);
|
||||
assert_eq!(subject_bounds(&surface, frame), Err("图像边缘颜色不均匀"));
|
||||
|
||||
let mut transformed = photocraft_raster::Surface::new(PixelFormat::RGBA8);
|
||||
transformed.fill_rect(frame, &[0.0, 0.0, 0.0, 0.25]);
|
||||
transformed.fill_rect(Rect::new(12, 22, 108, 98), &[1.0, 1.0, 1.0, 1.0]);
|
||||
transformed.fill_rect(Rect::new(32, 38, 84, 81), &[0.2, 0.1, 0.1, 1.0]);
|
||||
assert_eq!(subject_bounds(&transformed, frame), Ok([32, 38, 52, 43]));
|
||||
}
|
||||
|
||||
pub(crate) fn read_screen_preview(native: &Document, input: &Value) -> R<Value> {
|
||||
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.
|
||||
pub(crate) 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]
|
||||
pub(crate) 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());
|
||||
}
|
||||
|
||||
pub(crate) fn dimension_group_facts(native: &Document, meta: &Value, page: &Value, area: photocraft_geom::Rect, receipt: &Value) -> Vec<Value> {
|
||||
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();
|
||||
if row["visible"] == true {
|
||||
row["visibility"] = guide_visibility::measure(native, layer, area, &lines);
|
||||
}
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
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::<Vec<_>>(),
|
||||
"guides":guides.into_iter().map(|(row,_)| row).collect::<Vec<_>>()
|
||||
}))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub(crate) 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]));
|
||||
assert!(guide.get("visibility").is_none());
|
||||
doc.layer_mut(photocraft_doc::LayerId(guide_id)).unwrap().visible = true;
|
||||
let groups = dimension_group_facts(&doc, &meta, &page, doc.bounds(), &Value::Null);
|
||||
let visibility = &groups[0]["guides"][0]["visibility"];
|
||||
assert_eq!(visibility["lineWidthsPx"], json!([1.0]));
|
||||
assert!(visibility["contrastP50"].as_f64().unwrap() > 1.0);
|
||||
}
|
||||
|
||||
pub(crate) fn read_production_screen_with(
|
||||
native: &Document, input: &Value,
|
||||
preview: impl FnOnce(photocraft_geom::Rect) -> R<std::sync::Arc<Vec<u8>>>,
|
||||
) -> R<Value> {
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use photocraft_ui_egui::jiansun::production_facts::{layer_frame, path_visible};
|
||||
let meta = mapping(native).ok_or("工作画布缺少模板映射")?;
|
||||
let pages = meta["outputs"].as_array().ok_or("工作画布没有页面")?;
|
||||
let index = input["page"].as_u64().and_then(|value| usize::try_from(value).ok()).ok_or("屏号无效")?;
|
||||
let page = pages.get(index).ok_or("此屏不属于当前工作画布")?;
|
||||
let area = screen_area(native.bounds(), page)?;
|
||||
let fields: Vec<_> = page["mapping"]["fields"].as_array().into_iter().flatten()
|
||||
.filter_map(|field| field["fieldId"].as_str()).collect();
|
||||
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() {
|
||||
preview(area)?
|
||||
} else {
|
||||
let [x,y,w,h] = serde_json::from_value::<[i32;4]>(input["region"].clone())
|
||||
.map_err(|_| "region 必须是画布坐标 [x,y,w,h]")?;
|
||||
if w <= 0 || h <= 0 || x < area.x0 || y < area.y0
|
||||
|| i64::from(x) + i64::from(w) > i64::from(area.x1)
|
||||
|| i64::from(y) + i64::from(h) > i64::from(area.y1) {
|
||||
return Err("region 必须完整落在当前屏内".into());
|
||||
}
|
||||
let zoom = input["zoom"].as_f64().unwrap_or(1.0).clamp(1.0,4.0);
|
||||
let (jpeg, transform) = screen_preview::render_region(native, photocraft_geom::Rect::new(x,y,x+w,y+h), zoom)?;
|
||||
receipt["regionPreview"] = transform;
|
||||
std::sync::Arc::new(jpeg)
|
||||
};
|
||||
if check_blank {
|
||||
let pixels = photocraft_codecs::decode(&jpeg).map_err(|_| "实际画面无法读取")?
|
||||
.convert(photocraft_codecs::ChannelLayout::Gray, photocraft_codecs::SampleType::U8);
|
||||
receipt["blank"] = json!(pixels.data().iter().all(|pixel| *pixel >= 250));
|
||||
}
|
||||
if with_image {
|
||||
receipt["slotGeometry"] = json!(page["mapping"]["fields"].as_array().into_iter().flatten()
|
||||
.filter(|field| field["kind"] == "image").map(|field| {
|
||||
let mut row = json!({"slotId":field["slotId"],"nativeLayerId":field["nativeLayerId"]});
|
||||
let measured = field["nativeLayerId"].as_u64()
|
||||
.and_then(|id| native.path_of(photocraft_doc::LayerId(id)))
|
||||
.filter(|path| path_visible(native, path))
|
||||
.and_then(|path| native.layer_at(&path))
|
||||
.and_then(|layer| layer.surface().map(|surface|
|
||||
subject_bounds(surface, layer_frame(native, layer).intersect(&area))))
|
||||
.unwrap_or(Err("图位没有可见的放置像素"));
|
||||
match measured {
|
||||
Ok(bounds) => row["subjectBounds"] = json!(bounds),
|
||||
Err(reason) => row["subjectBoundsReason"] = json!(reason),
|
||||
}
|
||||
row
|
||||
}).collect::<Vec<_>>());
|
||||
add_annotation_subject_hits(&mut receipt);
|
||||
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()
|
||||
.filter(|field| field["kind"] == "image").filter_map(|field| field["slotId"].as_str()).collect::<Vec<_>>());
|
||||
receipt["pageName"] = page["name"].as_str().map_or_else(|| page["documentId"].clone(), |name| json!(name));
|
||||
let page_id = page["documentId"].as_str().ok_or("候选预览页面编号缺失")?;
|
||||
receipt["copyFields"] = json!(photocraft_ui_egui::jiansun::screen_copy_fields(native, page_id));
|
||||
}
|
||||
receipt["images"] = json!([{"type":"image","data":STANDARD.encode(jpeg.as_slice()),"mimeType":"image/jpeg"}]);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
@ -0,0 +1,663 @@
|
||||
use super::super::{Backend, Event, Path, R, Value, creation, fs, images, json, mpsc, original_project_present, production_profile, read_json, sync, template_slots, template_workflow, transfer};
|
||||
use super::{SUPPORTED_PRODUCTION_OUTPUTS, automated_candidate, blocked_production_stages, cached_prompt_mapping, candidate_available, candidate_limit_receipt, candidate_limits, candidate_matches_inputs, candidate_path, candidate_projection_task, candidate_receipt, candidate_uses_current_inputs, check_image_dispatch_cancelled, checked_binding, definition, document_mapping_key, editable_image_prompt, emit_production_image_receipt, enrich_creation, exists, generation_limit_receipt, generation_references_for_output, generation_was_dispatched, historical_candidate_pixels, image_output_component, image_output_state, jiansun_image_transform, load, load_detail_workspace, local_candidate, lock_candidate_dispatch, lock_slot_dispatch, mapped_slot, material_task_id, operation_receipt, output_state_inner, output_uses_variant, pending, pending_production_image, pending_production_images, product_slot_binding, production_image_presentation, production_image_target, production_output_state, production_settings_facts, project_candidate, publish_prepared, read_candidate, read_production_settings, read_records, reconcile_candidate, reserve_candidate, resumable_stages, revision, scope_state_for_view, settle_prepared_candidate, slot_dispatch_usage, slot_frame, slot_id, slot_text_regions, specified_image_ratio, uuid, validate_image_context, variant, variants};
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
|
||||
pub(crate) fn snapshot(dir: &Path) -> R<Value> {
|
||||
snapshot_for_view(dir, None, false)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_reviews(dir: &Path, pack: &Value, output: &str, variant: &str) -> Value {
|
||||
use std::io::BufRead as _;
|
||||
|
||||
let Some(project) = dir.file_name() else { return Value::Null };
|
||||
let Some(scope) = dir.parent().and_then(Path::parent).and_then(Path::file_name) else { return Value::Null };
|
||||
let conversation = dir.join("agent").join(scope).join(project).join("conversation-v1");
|
||||
let file = conversation.join(format!("production-{output}-{variant}.json"));
|
||||
let Ok(journal) = read_json(&file) else { return Value::Null };
|
||||
if journal["binding"] != json!([pack["contentHash"],variant]).to_string() {
|
||||
return Value::Null;
|
||||
}
|
||||
let mut reviews = serde_json::Map::new();
|
||||
if let Ok(events) = fs::File::open(conversation.join("events.jsonl")) {
|
||||
for line in std::io::BufReader::new(events).lines().map_while(Result::ok) {
|
||||
if !line.contains("\"type\":\"whole_detail_review\"") {
|
||||
continue;
|
||||
}
|
||||
if let Ok(entry) = serde_json::from_str::<Value>(&line)
|
||||
&& let Some(id) = entry["candidateId"].as_str()
|
||||
&& matches!(entry["verdict"].as_str(), Some("pass" | "revise" | "missing"))
|
||||
{
|
||||
reviews.insert(id.to_owned(), json!({"slotId":entry["slotId"],"decision":entry["verdict"]}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(reviews)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_matches_slot(record: &Value, state: &Value, pack: &Value, output: &Value, field: &Value, variant: &str) -> bool {
|
||||
let binding = &record["binding"];
|
||||
let (Some(field_id), Some(old_hash)) = (field["fieldId"].as_str(), binding["templateHash"].as_str()) else { return false; };
|
||||
if binding["workspaceId"] != state["id"] || binding["variantId"] != variant
|
||||
|| binding["outputId"] != output["id"] || binding["fieldId"] != field_id
|
||||
|| binding["slotId"] != slot_id(&binding["templateHash"], variant, field_id)
|
||||
|| binding["component"].is_string() && binding["component"] != output["component"]
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if pack["contentHash"] == old_hash {
|
||||
return true;
|
||||
}
|
||||
if !candidate_available(record) || !binding["templateId"].is_string() || binding["templateId"] != pack["id"] {
|
||||
return false;
|
||||
}
|
||||
// Older bindings did not store component. Do not infer it if the page
|
||||
// and field are also described by another output in this workspace.
|
||||
binding["component"].is_string() || !state["productTemplates"].as_object().into_iter().flatten()
|
||||
.filter(|(component, _)| output["component"] != component.as_str())
|
||||
.any(|(_, other)| other["outputs"].as_array().into_iter().flatten().any(|page|
|
||||
page["id"] == output["id"] && page["slots"].as_array().into_iter().flatten().any(|slot| slot["fieldId"] == field_id)))
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Value> {
|
||||
let project_plan = read_only && view.is_some();
|
||||
let (state, mut history) = {
|
||||
let _guard = sync::context_guard();
|
||||
let state = load(dir)?;
|
||||
let history = read_records(dir, &state, true)?;
|
||||
let state = if let Some(mut view) = view {
|
||||
view["revision"] = state["revision"].clone();
|
||||
view
|
||||
} else { state };
|
||||
(state, history)
|
||||
};
|
||||
let active = state["activeVariantId"].as_str().ok_or("当前花色缺失")?;
|
||||
let mut dispatched_generations = std::collections::HashSet::new();
|
||||
let mut candidate_counts = std::collections::HashMap::new();
|
||||
let mut pending_image_requests = Vec::new();
|
||||
for record in &mut history {
|
||||
if record["unindexed"] == true { continue; }
|
||||
let task = candidate_projection_task(dir, record)?;
|
||||
let dispatched = generation_was_dispatched(record, task.as_ref());
|
||||
if automated_candidate(record) && (dispatched || local_candidate(record)) {
|
||||
let slot = record["binding"]["slotId"].as_str().unwrap_or_default().to_owned();
|
||||
*candidate_counts.entry(slot).or_insert(0usize) += 1;
|
||||
}
|
||||
if dispatched && record["origin"] != "human" {
|
||||
dispatched_generations.insert(uuid(&record["id"], "候选")?);
|
||||
}
|
||||
if let Some(task) = task {
|
||||
if task["slotBinding"] != record["binding"] {
|
||||
return Err("候选与原任务绑定不一致,原记录保留".into());
|
||||
}
|
||||
let current_binding = !read_only && checked_binding(dir, &record["binding"], true).is_ok();
|
||||
if !read_only && current_binding && let Some(settled) = settle_prepared_candidate(dir, record, &task)? {
|
||||
*record = settled;
|
||||
}
|
||||
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
|
||||
if !read_only && current_binding {
|
||||
*record = reconcile_candidate(dir, &task)?;
|
||||
} else if matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired"))
|
||||
&& let Ok(projected) = project_candidate(dir, record, &task)
|
||||
{
|
||||
*record = projected;
|
||||
}
|
||||
}
|
||||
if let Some(row) = pending_production_image(record, &task)? {
|
||||
pending_image_requests.push(json!({"candidateId":row["candidateId"],"outputId":row["outputId"],"variantId":row["variantId"]}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let current = creation::load(dir)?;
|
||||
let (pending, scoped_production_pending, recovery_candidates) = {
|
||||
let _guard = sync::context_guard();
|
||||
let legacy = if dir.join("template-slots.json").exists() { template_slots::load(dir)? } else { json!({"slots":{}}) };
|
||||
let other_local = template_workflow::other_local_pending(dir, ¤t, &legacy, None)?
|
||||
|| !creation::pending_text_tasks(dir)?.is_empty();
|
||||
let image_pending: Vec<_> = history.iter().filter(|record| !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))).collect();
|
||||
let pending = other_local || !image_pending.is_empty();
|
||||
let scoped = pending && !other_local
|
||||
&& image_pending.iter().all(|record| product_slot_binding(&state, &record["binding"]));
|
||||
(pending, scoped, image_pending.iter().map(|record| &record["id"]).collect::<Vec<_>>())
|
||||
};
|
||||
let ready = current["brief"] == state["brief"];
|
||||
let active_output = state["activeOutput"].as_str().unwrap_or("detail");
|
||||
let active_color_enabled = output_uses_variant(&state["brief"], active_output, active);
|
||||
let index_incomplete = history.iter().any(|record| record["unindexed"] == true);
|
||||
let mut outputs = Vec::new();
|
||||
let mut slots = Vec::new();
|
||||
let active_mapping = &state["mappings"][state["activeMapping"].as_str().unwrap_or("")];
|
||||
let pack = &state["template"];
|
||||
let reviews = if state["productTemplates"].is_object() {
|
||||
candidate_reviews(dir, pack, active_output, active)
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let profile = production_profile::select(pack, active_output)?;
|
||||
let needs_mapping = pack["outputs"].as_array().into_iter().flatten().any(|output|
|
||||
output["slots"].as_array().into_iter().flatten().any(|field| field["kind"] == "image" && field.get("imagePrompt").is_none()));
|
||||
let prompt_mapping = needs_mapping.then(|| cached_prompt_mapping(dir, pack)).flatten();
|
||||
let ready_outputs: Vec<_> = if let Some(packs) = state["productTemplates"].as_object() {
|
||||
packs.iter().flat_map(|(component, pack)| pack["outputs"].as_array().into_iter().flatten()
|
||||
.filter(move |output| output["component"] == component.as_str())).collect()
|
||||
} else { pack["outputs"].as_array().into_iter().flatten().collect() };
|
||||
for output in ready_outputs {
|
||||
let fields = output["slots"].as_array().into_iter().flatten().map(|field|
|
||||
json!({"fieldId":field["fieldId"],"kind":field["kind"],"label":field.get("name").or(field.get("label"))})).collect::<Vec<_>>();
|
||||
outputs.push(json!({"documentId":output["id"],"outputId":output["component"],"name":output["name"],
|
||||
"width":output["width"],"fields":fields,
|
||||
"height":output["height"],"ready":true}));
|
||||
let component = output["component"].as_str().unwrap_or("detail");
|
||||
if state["productTemplates"].is_object() && component != active_output { continue; }
|
||||
if component != active_output && !output_uses_variant(&state["brief"], component, active) {
|
||||
continue;
|
||||
}
|
||||
for field in output["slots"].as_array().into_iter().flatten().filter(|f| f["kind"] == "image") {
|
||||
let id = slot_id(&state["template"]["contentHash"], active, field["fieldId"].as_str().ok_or("图片目标编号缺失")?);
|
||||
let mapped = mapped_slot(&state, &id, active);
|
||||
let resolved_frame = slot_frame(field, mapped);
|
||||
let Some(frame) = resolved_frame.or_else(|| project_plan.then_some(&field["frame"])) else { continue; };
|
||||
let in_slot = || history.iter().filter(|record| candidate_matches_slot(record, &state, pack, output, field, active));
|
||||
let retired: Vec<_> = in_slot().filter(|record| record["retirement"].is_object())
|
||||
.map(|record| &record["id"]).collect();
|
||||
let generation_request_ids: Vec<_> = in_slot().filter(|record|
|
||||
record["binding"]["slotId"] == id && record["id"].as_str().is_some_and(|id| dispatched_generations.contains(id)))
|
||||
.map(|record| &record["id"]).collect();
|
||||
let candidates: Vec<_> = in_slot().filter(|record| record["retirement"].is_null()).map(|record| {
|
||||
let candidate_id = record["id"].as_str().unwrap_or("");
|
||||
let archive_preview = candidate_available(record) && !dir.join("image-jobs").join(candidate_id).join("task.json").is_file();
|
||||
let historical = candidate_available(record) && (archive_preview || record["unindexed"] == true
|
||||
|| record["binding"]["slotId"] != id || record["binding"]["structureHash"] != state["structureHash"]
|
||||
|| !candidate_matches_inputs(&state, record, active, component, ¤t).unwrap_or(false));
|
||||
let review = &reviews[candidate_id];
|
||||
let decision = (!historical && review["slotId"] == id).then(|| &review["decision"]);
|
||||
let mut row = json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"],
|
||||
"historical":historical,"archivePreview":archive_preview,
|
||||
"materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"reworkOf":record["reworkOf"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"generationEvidence":record["generationEvidence"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]});
|
||||
if historical {
|
||||
row["adoptionError"] = json!(historical_candidate_pixels(dir, &state, record).err());
|
||||
}
|
||||
if record["phase"] == "expired" {
|
||||
row["retryable"] = json!(false);
|
||||
row["resultExpiry"] = record["resultExpiry"].clone();
|
||||
}
|
||||
row
|
||||
}).collect();
|
||||
let production_rule = profile
|
||||
.filter(|_| component == active_output)
|
||||
.and_then(|profile| profile["imageRules"].get(field["fieldId"].as_str()?))
|
||||
.or_else(|| field.get("productionRule"));
|
||||
slots.push(json!({"id":id,"fieldId":field["fieldId"],"documentId":output["id"],"outputId":output["component"],"variantId":active,"kind":"image","label":field.get("name").or(field.get("label")).unwrap_or(&field["fieldId"]),"width":frame["width"],"height":frame["height"],"frame":frame,"box":frame,"crop":field["crop"],"sourcePolicy":field["sourcePolicy"],"templatePrompt":editable_image_prompt(field, &output["id"], prompt_mapping.as_ref()),"nativeLayerId":mapped.map(|m|m["nativeLayerId"].clone()),"framePending":resolved_frame.is_none(),"candidates":candidates,"retiredCandidateIds":retired,"selectedCandidateId":null,"appliedCandidateId":null,"fields":[],"required":false,
|
||||
"role":field["role"],"requirements":field["requirements"],"relatedFields":field["relatedFields"],"generationRequestIds":generation_request_ids,"candidateCount":candidate_counts.get(&id).copied().unwrap_or_default(),
|
||||
"aspectRatio":specified_image_ratio(field).map(|(w,h)| format!("{w}:{h}")),
|
||||
"layoutReference":field["previewReference"].is_object(),"checkGeneratedMarks":state["productTemplates"].is_object(),"productionRule":production_rule,
|
||||
"textRegions":state["productTemplates"].is_object().then(||slot_text_regions(&state,&id,active))}));
|
||||
}
|
||||
}
|
||||
let original_canvas = &state["template"]["enterprise"]["canvas"];
|
||||
let screen_count = active_mapping["outputs"].as_array().map_or_else(|| outputs.iter().filter(|output| output["outputId"] == state["activeOutput"]).count(),Vec::len);
|
||||
let template = json!({"id":state["template"]["id"],"name":state["template"]["name"],"version":state["template"]["version"],"contentHash":state["template"]["contentHash"],"resourceSetId":state["template"]["enterprise"]["resourceSetId"],"enterprise":state["template"]["enterprise"].is_object(),
|
||||
"width":original_canvas[0],"height":original_canvas[1],"screenCount":screen_count,
|
||||
"productionRoute":pack["productionRoute"],"skillSources":pack["skillSources"],"production":profile.map(production_profile::agent_rules),
|
||||
"knowledgeVersion":pack["xiaoyi"]["knowledgeVersion"]});
|
||||
let product_references = generation_references_for_output(dir, &state, active, active_output)
|
||||
.ok()
|
||||
.and_then(|value| value.as_array().map(|items| {
|
||||
items.iter().enumerate()
|
||||
.filter(|(_, item)| item["purpose"] == "product")
|
||||
.map(|(index, item)| json!({
|
||||
"index": index,
|
||||
"source": item["source"],
|
||||
"name": item["name"],
|
||||
"purpose": item["purpose"],
|
||||
"barcode": item["barcode"],
|
||||
}))
|
||||
.collect::<Vec<_>>()
|
||||
}))
|
||||
.unwrap_or_default();
|
||||
let mut workflow = json!({"canvasFirst":true,"productReferences":product_references,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&!index_incomplete&&active_color_enabled,"copyDispatchAllowed":ready&&!pending&&active_color_enabled,"localApplyAllowed":ready}});
|
||||
if state["productTemplates"].is_object() {
|
||||
workflow["productTemplateOutputs"] = json!(SUPPORTED_PRODUCTION_OUTPUTS.iter()
|
||||
.filter(|output| state["productTemplates"][**output].is_object()).collect::<Vec<_>>());
|
||||
workflow["productionStages"] = json!(resumable_stages(dir, &state, ¤t["revision"], false));
|
||||
workflow["productionBlocks"] = json!(blocked_production_stages(&state));
|
||||
workflow["scopedProductionPending"] = json!(scoped_production_pending);
|
||||
workflow["pendingImageRequests"] = json!(pending_image_requests);
|
||||
}
|
||||
workflow["productionSettings"] = production_settings_facts(&read_production_settings(dir)?, profile.unwrap_or(&Value::Null));
|
||||
Ok(workflow)
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn opened_workspace_state(&self, doc: u64, state: Value) -> R<(Value, bool)> {
|
||||
let meta = self.access.opened_doc_scopes.lock().unwrap().get(&doc).cloned();
|
||||
let Some(meta) = meta else { return Ok((state, false)); };
|
||||
let component = meta["component"].as_str().ok_or("编辑稿输出类型缺失")?;
|
||||
let variant_id = meta["variantId"].as_str().ok_or("编辑稿花色缺失")?;
|
||||
let mut scoped = if state["productTemplates"].is_object() {
|
||||
output_state_inner(state, component, variant_id, false)?
|
||||
} else {
|
||||
variant(&state, variant_id)?;
|
||||
if !state["template"]["outputs"].as_array().into_iter().flatten().any(|output| output["component"] == component) {
|
||||
return Err("编辑稿输出不属于当前模板".into());
|
||||
}
|
||||
let mut state = state;
|
||||
state["activeOutput"] = json!(component);
|
||||
state["activeVariantId"] = json!(variant_id);
|
||||
state
|
||||
};
|
||||
if meta["workspaceId"] != scoped["id"] || meta["templateHash"] != scoped["template"]["contentHash"] {
|
||||
return Err("当前画布与项目模板版本不一致,请重新选择输出".into());
|
||||
}
|
||||
let key = document_mapping_key(&meta)?;
|
||||
scoped["activeMapping"] = json!(key);
|
||||
scoped["mappings"][&key] = meta;
|
||||
Ok((scoped, true))
|
||||
}
|
||||
pub(crate) fn opened_workspace_snapshot(&self, doc: u64, dir: &Path) -> R<Value> {
|
||||
let (scoped, opened) = self.opened_workspace_state(doc, load(dir)?)?;
|
||||
snapshot_for_view(dir, opened.then_some(scoped), opened)
|
||||
}
|
||||
pub(crate) fn canvas_workspace_result(&self, doc: u64, dir: &Path) -> R<Value> {
|
||||
self.canvas_result_with_workflow(doc, dir, snapshot(dir)?)
|
||||
}
|
||||
pub(crate) fn canvas_result_with_workflow(&self, doc: u64, dir: &Path, workflow: Value) -> R<Value> {
|
||||
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_snapshot(&self, doc: u64, dir: &Path, scoped: Value) -> R<Value> {
|
||||
let workflow = snapshot_for_view(dir, Some(scoped), false)?;
|
||||
self.canvas_result_with_workflow(doc, dir, workflow)
|
||||
}
|
||||
pub(crate) fn canvas_workspace_result_for_view(&self, doc: u64, dir: &Path, input: &Value, view_scoped: bool) -> R<Value> {
|
||||
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(crate) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender<Event>,
|
||||
ctx: &egui::Context, snapshot: Option<&photocraft_ui_egui::jiansun::PiCanvasSnapshot>) -> Result<Value, BridgeFailure> {
|
||||
let cancellation = snapshot.map(|snapshot| snapshot.cancellation.as_ref());
|
||||
self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?;
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
original_project_present(&dir)?;
|
||||
let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?;
|
||||
let request = &binding["request"];
|
||||
transfer::no_credentials(request)?;
|
||||
if phase == "read" {
|
||||
let id = uuid(&request["requestId"], "生图请求")?;
|
||||
let task = super::images::read_image_request(&dir, &id)?;
|
||||
let scope = &binding["scope"];
|
||||
if task["accountScope"] != self.scope() || task["localProjectId"] == Value::Null
|
||||
|| task["localProjectId"].as_str() != self.locations.get(&doc).map(String::as_str)
|
||||
|| task["origin"] != self.origin || task["outputScope"] != scope["outputId"]
|
||||
|| task["slotBinding"]["variantId"] != scope["variantId"]
|
||||
|| task["slotBinding"]["workspaceId"] != scope["id"]
|
||||
|| task["slotBinding"]["templateHash"] != scope["templateHash"] {
|
||||
return Err("生图请求不属于当前账户、项目或工作画布".into());
|
||||
}
|
||||
let mut receipt = super::images::image_request_receipt(&task);
|
||||
if task["message"].is_string() { receipt["message"] = task["message"].clone(); }
|
||||
if task["resultExpiry"].is_object() { receipt["resultExpiry"] = task["resultExpiry"].clone(); }
|
||||
return Ok(receipt);
|
||||
}
|
||||
if phase == "pending" {
|
||||
let _guard = sync::context_guard();
|
||||
return pending_production_images(&dir, &load(&dir)?).map_err(BridgeFailure::from);
|
||||
}
|
||||
check_image_dispatch_cancelled(cancellation)?;
|
||||
let mut scoped_binding;
|
||||
let binding = if binding["projectScope"] == true {
|
||||
let state = production_image_target(load_detail_workspace(&dir)?, &binding["scope"])?;
|
||||
let variant = state["activeVariantId"].as_str().ok_or("花色编号缺失")?;
|
||||
let id = request["slotId"].as_str().ok_or("图片图位缺失")?;
|
||||
let (output, field) = definition(&state, id, variant)?;
|
||||
if output["component"] != state["activeOutput"] {
|
||||
return Err("图片图位不属于所选制作输出".into());
|
||||
}
|
||||
let mapped = mapped_slot(&state, id, variant);
|
||||
scoped_binding = binding.clone();
|
||||
scoped_binding["scope"]["structureHash"] = state["structureHash"].clone();
|
||||
if scoped_binding["revision"].is_null() {
|
||||
scoped_binding["revision"] = state["revision"].clone();
|
||||
}
|
||||
scoped_binding["slotLabel"] = field.get("name").or(field.get("label")).unwrap_or(&field["fieldId"]).clone();
|
||||
let frame = slot_frame(field, mapped).ok_or("当前图片图层缺少已核对的范围")?;
|
||||
scoped_binding["imageFrame"] = json!({"width":frame["width"],"height":frame["height"]});
|
||||
&scoped_binding
|
||||
} else { binding };
|
||||
if matches!(phase, "prepare" | "transform" | "product_reference") {
|
||||
let mut input = request.clone();
|
||||
input["doc"] = json!(doc);
|
||||
input["baseRevision"] = binding["revision"].clone();
|
||||
input["variantId"] = binding["scope"]["variantId"].clone();
|
||||
input["detailBatch"] = json!(true);
|
||||
input["detailWorkspace"] = binding["scope"].clone();
|
||||
input["projectScopedImage"] = binding["projectScope"].clone();
|
||||
let transform_source = if phase == "transform" && !input["sourceSlotId"].is_null() {
|
||||
let state = load_detail_workspace(&dir)?;
|
||||
let variant = uuid(&input["variantId"], "花色")?;
|
||||
Some(jiansun_image_transform::adopted_source(
|
||||
&dir, &state, &input, &variant, snapshot.map(|snapshot| snapshot.document.as_ref()),
|
||||
)?)
|
||||
} else { None };
|
||||
let action = match phase {
|
||||
"transform" => "slot-transform-image",
|
||||
"product_reference" => {
|
||||
input["useProductReference"] = json!(true);
|
||||
input["instructions"] = json!("产品原图");
|
||||
"slot-append"
|
||||
}
|
||||
_ => "slot-prepare-image",
|
||||
};
|
||||
let component = binding["scope"]["outputId"].as_str().ok_or("输出类型缺失")?;
|
||||
let variant = input["variantId"].as_str().ok_or("花色缺失")?;
|
||||
let state = load_detail_workspace(&dir)?;
|
||||
let source = if binding["projectScope"] == true || action == "slot-prepare-image" {
|
||||
production_output_state(state, component, variant)?
|
||||
} else { state };
|
||||
let source_slot = json!({"slotId":request["slotId"],"variantId":variant});
|
||||
let (per_batch, max, generation_cap) = candidate_limits(&dir, &source, component)?;
|
||||
let _admission = if action == "slot-transform-image" {
|
||||
Some(lock_slot_dispatch(&dir, &source_slot)?.ok_or("本图位已有生图批次正在处理")?)
|
||||
} else { None };
|
||||
let (used, generations, _) = {
|
||||
let _guard = sync::context_guard();
|
||||
slot_dispatch_usage(&dir, &load(&dir)?, &source_slot, &[], None)?
|
||||
};
|
||||
if used >= max { return Ok(candidate_limit_receipt(&source_slot, used, max)); }
|
||||
if action != "slot-prepare-image" {
|
||||
return self.canvas_workspace_action_with_source(action, &input, events, ctx, transform_source)
|
||||
.map_err(BridgeFailure::from);
|
||||
}
|
||||
if generations >= generation_cap {
|
||||
return Ok(generation_limit_receipt(&source_slot, used, max, generations, generation_cap));
|
||||
}
|
||||
let mut drafts = Vec::new();
|
||||
for _ in 0..per_batch.min(max - used).min(generation_cap - generations) {
|
||||
drafts.push(self.canvas_workspace_action(action, &input, events, ctx)?);
|
||||
}
|
||||
let mut receipt = drafts[0].clone();
|
||||
let primary = uuid(&receipt["requestId"], "生图请求")?;
|
||||
let mut task = super::images::read_image_request(&dir, &primary)?;
|
||||
task["candidateBatch"] = json!(drafts.iter().skip(1).map(|draft| json!({
|
||||
"requestId":draft["requestId"],"expectedRevision":draft["revision"],"expectedHash":draft["requestSpecHash"]
|
||||
})).collect::<Vec<_>>());
|
||||
super::images::job_save(&dir, &task)?;
|
||||
receipt["candidates"] = json!(drafts);
|
||||
return Ok(receipt);
|
||||
}
|
||||
if phase != "dispatch" { return Err("生图请求动作无效".into()); }
|
||||
let presentation = production_image_presentation(doc, binding, &self.auth["account"]["id"], &self.origin);
|
||||
let primary = uuid(&request["requestId"], "生图请求")?;
|
||||
let mut draft = super::images::read_image_request(&dir, &primary)?;
|
||||
let _slot_dispatch = if draft["slotBinding"]["detailBatch"] == true {
|
||||
let Some(lock) = lock_slot_dispatch(&dir, request)? else {
|
||||
return Err(BridgeFailure::new("slot_image_running", true, false, "本图位已有生图批次正在处理"));
|
||||
};
|
||||
draft = super::images::read_image_request(&dir, &primary)?;
|
||||
Some(lock)
|
||||
} else { None };
|
||||
let siblings = draft["candidateBatch"].as_array().filter(|rows| draft["phase"] == "prepared" && !rows.is_empty());
|
||||
let mut batch = Vec::new();
|
||||
let receipt = match self.dispatch_canvas_image_request(doc, &dir, request,
|
||||
Some((&binding["scope"], &presentation)), events, ctx, cancellation, &batch) {
|
||||
Ok(receipt) => receipt,
|
||||
Err(error) if error.dispatched && siblings.is_some() =>
|
||||
json!({"id":primary,"status":"unknown","message":error.message}),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut receipt = receipt;
|
||||
if receipt["id"] == request["requestId"] && receipt["status"] != "retired" && draft["candidateBatch"].is_array() {
|
||||
// Only members dispatched by this invocation can bypass its pending-original gate.
|
||||
// A replay of an already submitted primary request must recover by original ID.
|
||||
let mut receipts = vec![receipt.clone()];
|
||||
if let Some(siblings) = siblings {
|
||||
batch.push(uuid(&request["requestId"], "生图请求")?);
|
||||
for sibling in siblings {
|
||||
let id = uuid(&sibling["requestId"], "生图请求")?;
|
||||
let mut member = sibling.clone();
|
||||
member["slotId"] = request["slotId"].clone();
|
||||
let mut member_presentation = presentation.clone();
|
||||
member_presentation["taskId"] = json!(id);
|
||||
let result = self.dispatch_canvas_image_request(doc, &dir, &member,
|
||||
Some((&binding["scope"], &member_presentation)), events, ctx, cancellation, &batch);
|
||||
if let Ok(value) = &result
|
||||
&& matches!(value["status"].as_str(), Some("candidate_limit_reached" | "draw_limit_reached")) {
|
||||
break;
|
||||
}
|
||||
let member_receipt = match result {
|
||||
Ok(mut value) => {
|
||||
if value["id"].is_null() { value["id"] = json!(id); }
|
||||
value
|
||||
}
|
||||
Err(error) => json!({"id":id,"status":if error.dispatched {"unknown"} else {"failed"},"message":error.message}),
|
||||
};
|
||||
emit_production_image_receipt(events, member_presentation, &member_receipt,
|
||||
check_image_dispatch_cancelled(cancellation).is_err());
|
||||
receipts.push(member_receipt);
|
||||
batch.push(id);
|
||||
}
|
||||
}
|
||||
receipt["candidates"] = json!(receipts);
|
||||
}
|
||||
self.publish_production_image_receipt(doc, &dir, binding, presentation, receipt, events, ctx, cancellation)
|
||||
}
|
||||
|
||||
pub(crate) fn publish_production_image_receipt(&self, doc: u64, dir: &Path, binding: &Value, presentation: Value,
|
||||
receipt: Value, events: &mpsc::Sender<Event>, ctx: &egui::Context,
|
||||
cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<Value, BridgeFailure> {
|
||||
let cancelled = check_image_dispatch_cancelled(cancellation).is_err();
|
||||
if receipt["status"].is_string() {
|
||||
emit_production_image_receipt(events, presentation, &receipt, cancelled);
|
||||
if !cancelled {
|
||||
match self.canvas_workspace_result(doc, &dir) {
|
||||
Ok(workspace) if binding["projectScope"] == true => {
|
||||
// Refresh the current project index even if the original canvas has since changed.
|
||||
let _ = events.send(Event::Json("slot-progress".into(), Ok(workspace)));
|
||||
}
|
||||
Ok(workspace) => {
|
||||
let mut snapshot = operation_receipt(workspace, Some(receipt.clone()), None);
|
||||
snapshot["writeEpoch"] = binding["writeEpoch"].clone();
|
||||
let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot)));
|
||||
}
|
||||
Err(error) => log::warn!("小壹原生图回执已保留,画布状态未刷新:{error}"),
|
||||
}
|
||||
}
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_canvas_image_request(&mut self, doc: u64, dir: &Path, request: &Value, production: Option<(&Value, &Value)>,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>, batch: &[String]) -> Result<Value, BridgeFailure> {
|
||||
let id = uuid(&request["requestId"], "生图请求")?;
|
||||
let scope = production.map(|(scope, _)| scope);
|
||||
let (task, _dispatch) = {
|
||||
let _guard = sync::context_guard();
|
||||
let mut task = super::images::read_image_request(dir, &id)?;
|
||||
let belongs = task["doc"] == doc && task["accountScope"] == self.scope()
|
||||
&& task["localProjectId"].as_str() == self.locations.get(&doc).map(String::as_str)
|
||||
&& task["origin"] == self.origin && task["slotBinding"]["slotId"] == request["slotId"]
|
||||
&& scope.is_none_or(|scope| task["outputScope"] == scope["outputId"]
|
||||
&& ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field|
|
||||
task["slotBinding"][*field] == scope[if *field=="workspaceId" {"id"}else{*field}]));
|
||||
if !belongs { return Err("生图请求不属于当前账户、项目、工作画布或图位".into()); }
|
||||
super::images::freeze_image_request_locked(dir, &mut task, request)?;
|
||||
let Some(dispatch) = lock_candidate_dispatch(dir, &id)? else {
|
||||
return Ok(json!({"phase":"running","candidateId":id}));
|
||||
};
|
||||
(task, dispatch)
|
||||
};
|
||||
let original_error = |error| BridgeFailure::new("image_request_failed", false, true, error);
|
||||
if task["phase"] != "prepared" {
|
||||
return reconcile_candidate(dir, &task).map(|record| candidate_receipt(&record)).map_err(original_error);
|
||||
}
|
||||
let slot = &task["slotBinding"];
|
||||
let state = if slot["detailBatch"] == true { load_detail_workspace(dir)? } else { load(dir)? };
|
||||
let record = &task["candidateRecord"];
|
||||
let _slot_dispatch = if production.is_none() && (slot["detailBatch"] == true || slot["origin"] == "human") {
|
||||
Some(lock_slot_dispatch(dir, slot)?.ok_or("本图位已有生图批次正在处理")?)
|
||||
} else { None };
|
||||
let admitted = production.is_some() && slot["detailBatch"] == true;
|
||||
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) = {
|
||||
let _guard = sync::context_guard();
|
||||
slot_dispatch_usage(dir, &load(dir)?, slot, batch, Some(&id))?
|
||||
};
|
||||
if used >= max { return Ok(candidate_limit_receipt(slot, used, max)); }
|
||||
if generations >= generation_cap {
|
||||
return Ok(generation_limit_receipt(slot, used, max, generations, generation_cap));
|
||||
}
|
||||
if let Some(original) = pending {
|
||||
return Ok(json!({"status":"unknown","id":original,"message":"本图位有未知原请求,请先按原号核查"}));
|
||||
}
|
||||
}
|
||||
if !candidate_uses_current_inputs(dir, &source, record, slot["variantId"].as_str().ok_or("花色缺失")?)? {
|
||||
return Err("商品资料或制作依据已变化,请重新准备请求".into());
|
||||
}
|
||||
if candidate_path(dir, &id)?.exists() {
|
||||
let existing = read_candidate(dir, &id)?;
|
||||
if existing["phase"] != "prepared" || existing["retirement"].is_object() {
|
||||
return Ok(candidate_receipt(&existing));
|
||||
}
|
||||
} else {
|
||||
reserve_candidate(dir, state, record, scoped_output)?;
|
||||
}
|
||||
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)});
|
||||
}
|
||||
publish_prepared(events, snapshot)?;
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
validate_image_context(dir, Some(slot))?;
|
||||
check_image_dispatch_cancelled(cancellation)?;
|
||||
let mut input = json!({"doc":doc,"frozenRequestId":id});
|
||||
if let Some((_, presentation)) = production {
|
||||
input["productionImage"] = presentation.clone();
|
||||
}
|
||||
let call = self.dispatch_frozen_image(&input, events, ctx, cancellation);
|
||||
let dispatch_error = |error, backend: &Self| {
|
||||
let dispatched = backend.image_dispatch_may_have_started(doc, &id);
|
||||
let category = if !dispatched && check_image_dispatch_cancelled(cancellation).is_err() {
|
||||
"cancelled"
|
||||
} else { "image_request_failed" };
|
||||
BridgeFailure::new(category, false, dispatched, error)
|
||||
};
|
||||
let result = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx, !admitted)
|
||||
.map_err(|error| dispatch_error(error, self))
|
||||
.and_then(|(mut receipt, failure)| {
|
||||
if receipt["status"] == "failed" && let Some(message) = failure {
|
||||
receipt["message"] = json!(message);
|
||||
}
|
||||
self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, true, message))?;
|
||||
receipt["attachmentSources"] = super::images::attachment_sources(&task);
|
||||
Ok(receipt)
|
||||
});
|
||||
if let (Some((_, presentation)), Err(error)) = (production, &result) {
|
||||
let mut image = presentation.clone();
|
||||
image["phase"] = json!(if check_image_dispatch_cancelled(cancellation).is_err() {
|
||||
"cancelled"
|
||||
} else if error.dispatched { "unknown" } else { "failed" });
|
||||
image["isSlotCandidate"] = json!(true);
|
||||
let _ = events.send(Event::Json("image".into(), Ok(image)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn settle_image_candidate(&mut self, dir: &Path, doc: u64, id: &str, binding: &Value, mut call: R<Value>,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context, recover_inline: bool) -> R<(Value, Option<String>)> {
|
||||
let file = dir.join("image-jobs").join(id).join("task.json");
|
||||
let mut journal = if file.try_exists().map_err(|_| "原生图记录无法核对,保留原候选")? {
|
||||
read_json(&file)?
|
||||
} else {
|
||||
json!({"id":id,"slotBinding":binding,"phase":"prepared","notDispatched":true,"message":call.as_ref().err()})
|
||||
};
|
||||
if recover_inline && matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
|
||||
call = self.recover_original_image(doc, id, events, ctx);
|
||||
journal = read_json(&file)?;
|
||||
} else if journal["phase"] == "prepared" && let Err(error) = &call {
|
||||
journal["notDispatched"] = json!(true);
|
||||
journal["message"] = json!(error);
|
||||
}
|
||||
let record = reconcile_candidate(dir, &journal)?;
|
||||
if !recover_inline && matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown"))
|
||||
&& let Ok(snapshot) = self.canvas_workspace_result(doc, dir)
|
||||
{
|
||||
// Publish the archived dispatch so the host queue can probe it before the agent yields.
|
||||
let _ = publish_prepared(events, snapshot);
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
Ok((candidate_receipt(&record),call.err()))
|
||||
}
|
||||
|
||||
pub(crate) fn recover_deferred_candidate(&mut self, input: &Value, cancellation: &std::sync::atomic::AtomicBool) -> R<Value> {
|
||||
let doc = input["doc"].as_u64().ok_or("项目身份无效")?;
|
||||
let authority = self.clone();
|
||||
let check = || {
|
||||
check_image_dispatch_cancelled(Some(cancellation)).map_err(String::from)?;
|
||||
authority.check_dispatch()?;
|
||||
if authority.exiting() { return Err("客户端正在退出,保留原候选".into()); }
|
||||
authority.ensure_owner(doc)
|
||||
};
|
||||
check()?;
|
||||
if input["accountEpoch"].as_u64() != Some(self.access.epoch)
|
||||
|| input["accountId"] != self.auth["account"]["id"] || input["origin"] != self.origin
|
||||
|| self.locations.get(&doc).is_none_or(|project| input["project"] != *project)
|
||||
{
|
||||
return Err("暂缓候选属于其他项目或账户".into());
|
||||
}
|
||||
let dir = self.project_dir(doc)?;
|
||||
original_project_present(&dir)?;
|
||||
let id = uuid(&input["taskId"], "原候选")?;
|
||||
let record = read_candidate(&dir, &id)?;
|
||||
let (state, _) = checked_binding(&dir, &record["binding"], true)?;
|
||||
if state["id"] != input["workspaceId"] || record["binding"]["variantId"] != input["variantId"] {
|
||||
return Err("暂缓候选的画布项目或花色已变化".into());
|
||||
}
|
||||
let Some(_dispatch) = lock_candidate_dispatch(&dir, &id)? else {
|
||||
return Err("原候选仍在处理".into());
|
||||
};
|
||||
let file = dir.join("image-jobs").join(&id).join("task.json");
|
||||
let mut task = read_json(&file)?;
|
||||
super::images::reopen_ambiguous_expiry(&mut task);
|
||||
if task["id"] != id || task["slotBinding"] != record["binding"] || task["outputScope"] != input["outputId"]
|
||||
|| task["slotBinding"]["detailBatch"] != true
|
||||
|| task["origin"] != self.origin || task["accountScope"] != self.scope() || task["localProjectId"] != input["project"]
|
||||
|| !matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown" | "complete" | "applied" | "failed" | "expired"))
|
||||
{
|
||||
return Err("未找到此输出已提交的原生图请求".into());
|
||||
}
|
||||
if !matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired")) {
|
||||
self.recover_archived_image(input, &check)?;
|
||||
}
|
||||
check()?;
|
||||
let mut journal = read_json(&file)?;
|
||||
super::images::reopen_ambiguous_expiry(&mut journal);
|
||||
let status = if journal["phase"] == "applied" { json!("complete") } else { journal["phase"].clone() };
|
||||
let mut receipt = json!({"id":id,"status":status,"variantId":input["variantId"]});
|
||||
if matches!(status.as_str(), Some("complete" | "failed" | "expired")) {
|
||||
receipt["workflow"] = snapshot_for_view(&dir, None, true)?;
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,666 @@
|
||||
use super::super::{Digest, Document, Path, PathBuf, R, Sha256, Uuid, Value, creation, fs, hash, images, json, original_project_present, production_profile, read_json, sync, template_slots, write_json};
|
||||
use super::{CANDIDATE, FILE, SUPPORTED_PRODUCTION_OUTPUTS, bound_product_slot, fidelity, mapping, mapping_key, matches_placed_candidate, variants};
|
||||
use photocraft_ui_egui::jiansun::production_facts::product_brief::{resolve_sku_spec_target, sku_spec_targets};
|
||||
|
||||
pub(crate) fn exists(dir: &Path) -> bool {
|
||||
dir.join(FILE).is_file()
|
||||
}
|
||||
pub(crate) fn uuid(value: &Value, label: &str) -> R<String> {
|
||||
value.as_str().and_then(|s| Uuid::parse_str(s).ok()).map(|id| id.to_string()).ok_or_else(|| format!("{label}编号无效"))
|
||||
}
|
||||
pub(crate) fn text(value: &Value, max: usize, label: &str) -> R<String> {
|
||||
value
|
||||
.as_str()
|
||||
.filter(|s| s.chars().count() <= max && !s.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t')))
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| format!("{label}无效"))
|
||||
}
|
||||
pub(crate) fn revision(state: &Value) -> u64 {
|
||||
state["revision"].as_u64().unwrap_or(0)
|
||||
}
|
||||
pub(crate) fn candidate_path(dir: &Path, id: &str) -> R<PathBuf> {
|
||||
Ok(dir.join("image-jobs").join(uuid(&json!(id), "候选")?).join(CANDIDATE))
|
||||
}
|
||||
pub(crate) fn slot_id(template_hash: &Value, variant: &str, field: &str) -> String {
|
||||
hash(&json!([template_hash, variant, field]).to_string())
|
||||
}
|
||||
pub(crate) fn load(dir: &Path) -> R<Value> {
|
||||
original_project_present(dir)?;
|
||||
let state = read_json(&dir.join(FILE))?;
|
||||
if state["version"] != 1
|
||||
|| state["canvasFirst"] != true
|
||||
|| state["revision"].as_u64().is_none()
|
||||
|| !state["candidates"].is_array()
|
||||
|| !state["mappings"].is_object()
|
||||
{
|
||||
return Err("原生画布项目记录无效,请保留原项目".into());
|
||||
}
|
||||
uuid(&state["id"], "画布项目")?;
|
||||
template_slots::validate_pack(&state["template"])?;
|
||||
let variants = state["variants"].as_array().filter(|v| !v.is_empty() && v.len() <= 64).ok_or("项目花色记录无效")?;
|
||||
let active = uuid(&state["activeVariantId"], "当前花色")?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for variant in variants {
|
||||
if !seen.insert(uuid(&variant["id"], "花色")?) {
|
||||
return Err("项目花色编号重复".into());
|
||||
}
|
||||
}
|
||||
if !seen.contains(&active) {
|
||||
return Err("当前花色不属于此项目".into());
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
pub(crate) fn load_detail_workspace(dir: &Path) -> R<Value> {
|
||||
let _guard = sync::context_guard();
|
||||
load(dir)
|
||||
}
|
||||
|
||||
pub(crate) fn persist(dir: &Path, mut state: Value, expected: u64) -> R<Value> {
|
||||
let _guard = sync::context_guard();
|
||||
persist_locked(dir, &mut state, expected)
|
||||
}
|
||||
pub(crate) fn persist_locked(dir: &Path, state: &mut Value, expected: u64) -> R<Value> {
|
||||
original_project_present(dir)?;
|
||||
let actual = if exists(dir) { revision(&load(dir)?) } else { 0 };
|
||||
if actual != expected {
|
||||
return Err("项目内容在操作期间有改动,原稿已保留".into());
|
||||
}
|
||||
state["revision"] = json!(expected.checked_add(1).filter(|n| *n < 2_147_483_647).ok_or("画布项目修改记录已达上限")?);
|
||||
if state.to_string().len() > 1_900_000 {
|
||||
return Err("画布索引接近文件容量上限,历史候选保留;未删减记录".into());
|
||||
}
|
||||
write_json(&dir.join(FILE), state)?;
|
||||
Ok(state.clone())
|
||||
}
|
||||
pub(crate) fn variant<'a>(state: &'a Value, id: &str) -> R<&'a Value> {
|
||||
if let Some(found) = state["variants"].as_array().into_iter().flatten().find(|v| v["id"] == id) {
|
||||
return Ok(found);
|
||||
}
|
||||
if let Some(target) = resolve_sku_spec_target(&state["brief"], id)
|
||||
&& let Some(found) = state["variants"].as_array().into_iter().flatten().find(|v| v["id"] == target.color_variant_id)
|
||||
{
|
||||
return Ok(found);
|
||||
}
|
||||
Err("花色不属于此项目".into())
|
||||
}
|
||||
pub(crate) fn output_uses_variant(brief: &Value, component: &str, id: &str) -> bool {
|
||||
if component == "detail" && let Some(selected) = creation::detail_barcode(brief) {
|
||||
let count = brief["variants"].as_array().map_or(0, Vec::len);
|
||||
return creation::variant_barcodes(brief, id, count).any(|barcode| barcode == selected);
|
||||
}
|
||||
let color_id = if component == "sku_images" {
|
||||
resolve_sku_spec_target(brief, id).map_or_else(|| id.to_owned(), |target| target.color_variant_id)
|
||||
} else {
|
||||
id.to_owned()
|
||||
};
|
||||
brief["outputVariantIds"][component].as_array().is_none_or(|ids| ids.iter().any(|value| value == color_id.as_str()))
|
||||
}
|
||||
|
||||
pub(crate) fn production_stages(state: &Value) -> Vec<Value> {
|
||||
if !state["productTemplates"].is_object() { return Vec::new(); }
|
||||
let outputs: std::collections::BTreeSet<_> = ["productTemplates", "productTemplateIssues"].into_iter()
|
||||
.flat_map(|key| state[key].as_object().into_iter().flat_map(|rows| rows.keys().map(String::as_str)))
|
||||
.filter(|output| SUPPORTED_PRODUCTION_OUTPUTS.contains(output))
|
||||
.collect();
|
||||
outputs.into_iter().flat_map(|component| {
|
||||
state["variants"].as_array().into_iter().flatten().flat_map(move |row| {
|
||||
let Some(id) = row["id"].as_str() else { return Vec::new(); };
|
||||
if !output_uses_variant(&state["brief"], component, id) {
|
||||
return Vec::new();
|
||||
}
|
||||
if component == "sku_images" {
|
||||
let targets = sku_spec_targets(&state["brief"], id);
|
||||
if targets.iter().any(|target| target.target_id != target.color_variant_id) {
|
||||
return targets.into_iter().map(|target| json!({
|
||||
"outputId": component,
|
||||
"variantId": target.target_id,
|
||||
"colorVariantId": target.color_variant_id,
|
||||
"specId": target.spec_id,
|
||||
"barcodes": target.barcodes,
|
||||
})).collect();
|
||||
}
|
||||
}
|
||||
vec![json!({"outputId":component,"variantId":id})]
|
||||
})
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn blocked_production_stages(state: &Value) -> Vec<Value> {
|
||||
production_stages(state).into_iter().filter_map(|mut stage| {
|
||||
let reason = state["productTemplateIssues"].get(stage["outputId"].as_str()?)?.as_str()?;
|
||||
stage["reason"] = json!(reason);
|
||||
Some(stage)
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn runnable_stages(state: &Value, mut remaining: Vec<Value>) -> Vec<Value> {
|
||||
remaining.retain(|stage| stage["outputId"].as_str().is_some_and(|output| state["productTemplateIssues"][output].is_null()));
|
||||
remaining
|
||||
}
|
||||
|
||||
pub(crate) fn output_state_inner(mut state: Value, output: &str, variant_id: &str, enforce_color: bool) -> R<Value> {
|
||||
if enforce_color && output == "detail" {
|
||||
creation::require_detail_barcode(&state["brief"])?;
|
||||
}
|
||||
variant(&state, 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())
|
||||
.ok_or("所选成品没有可用模板")?.clone();
|
||||
if state["activeOutput"] != output || state["activeVariantId"] != variant_id {
|
||||
state["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string()));
|
||||
state["activeMapping"] = json!(mapping_key(variant_id, output, None));
|
||||
}
|
||||
state["template"] = pack;
|
||||
state["activeOutput"] = json!(output);
|
||||
state["activeVariantId"] = json!(variant_id);
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub(crate) fn production_output_state(state: Value, output: &str, variant_id: &str) -> R<Value> {
|
||||
output_state_inner(state, output, variant_id, true)
|
||||
}
|
||||
|
||||
pub(crate) 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"]
|
||||
&& pack["outputs"].as_array().into_iter().flatten().any(|page|
|
||||
page["component"] == component.as_str() && page["id"] == binding["outputId"]))
|
||||
.map(|(output, _)| output.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn image_output_state(state: Value, binding: &Value) -> R<Value> {
|
||||
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 = output_state_inner(state, &output, variant_id, batch)?;
|
||||
if binding["structureHash"] != scoped["structureHash"] || bound_product_slot(&scoped, binding).is_none() {
|
||||
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.
|
||||
pub(crate) 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() {
|
||||
if let Some(scope) = photocraft_ui_egui::jiansun::user_slot_scope(input)
|
||||
&& (scope["templateHash"] != state["template"]["contentHash"]
|
||||
|| scope["variantId"] != state["activeVariantId"] || scope["outputId"] != state["activeOutput"])
|
||||
{
|
||||
return Err("项目的输出、花色或模板已切换,请回到原画布后再操作。".into());
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
pub(crate) fn output_variant<'a>(state: &'a Value, component: &str, requested: Option<&'a str>) -> R<&'a str> {
|
||||
if let Some(id) = requested {
|
||||
variant(state, id)?;
|
||||
if output_uses_variant(&state["brief"], component, id) {
|
||||
return Ok(id);
|
||||
}
|
||||
return Err("当前花色不属于此输出".into());
|
||||
}
|
||||
let active = state["activeVariantId"].as_str().ok_or("当前花色缺失")?;
|
||||
if output_uses_variant(&state["brief"], component, active) {
|
||||
return Ok(active);
|
||||
}
|
||||
state["variants"].as_array().into_iter().flatten()
|
||||
.filter_map(|row| row["id"].as_str()).find(|id| output_uses_variant(&state["brief"], component, id))
|
||||
.ok_or_else(|| "请在产品资料选择此类图片的 SKU 颜色".into())
|
||||
}
|
||||
|
||||
pub(crate) fn definition<'a>(state: &'a Value, id: &str, variant_id: &str) -> R<(&'a Value, &'a Value)> {
|
||||
variant(state, variant_id)?;
|
||||
for output in state["template"]["outputs"].as_array().into_iter().flatten() {
|
||||
for field in output["slots"].as_array().into_iter().flatten() {
|
||||
if field["kind"] == "image" && field["fieldId"].as_str().is_some_and(|f| slot_id(&state["template"]["contentHash"], variant_id, f) == id) {
|
||||
return Ok((output, field));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("图片目标不属于当前模板和花色".into())
|
||||
}
|
||||
|
||||
pub(crate) fn mapped_slot<'a>(state: &'a Value, id: &str, variant_id: &str) -> Option<&'a Value> {
|
||||
let mapping = &state["mappings"][state["activeMapping"].as_str()?];
|
||||
if mapping["variantId"] != variant_id {
|
||||
return None;
|
||||
}
|
||||
mapped_fields(mapping).find(|row| row["slotId"] == id)
|
||||
}
|
||||
|
||||
pub(crate) fn mapped_fields(mapping: &Value) -> impl Iterator<Item = &Value> {
|
||||
mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|o| o["mapping"]["fields"].as_array().into_iter().flatten().chain(o["fields"].as_array().into_iter().flatten()))
|
||||
.chain(mapping["fields"].as_array().into_iter().flatten())
|
||||
}
|
||||
|
||||
pub(crate) fn slot_text_regions(state: &Value, id: &str, variant_id: &str) -> Vec<Value> {
|
||||
let Some(image) = mapped_slot(state, id, variant_id) else { return Vec::new() };
|
||||
let rect = |frame: &Value| -> Option<[f64; 4]> {
|
||||
let x = frame["x"].as_f64()?;
|
||||
let y = frame["y"].as_f64()?;
|
||||
let w = frame["width"].as_f64().filter(|v| *v > 0.0)?;
|
||||
let h = frame["height"].as_f64().filter(|v| *v > 0.0)?;
|
||||
Some([x, y, w, h])
|
||||
};
|
||||
let Some([x, y, w, h]) = rect(&image["frame"]) else { return Vec::new() };
|
||||
let mapping = &state["mappings"][state["activeMapping"].as_str().unwrap_or_default()];
|
||||
mapped_fields(mapping).filter_map(|field| {
|
||||
if field["kind"] != "text" {
|
||||
return None;
|
||||
}
|
||||
let [left, top, width, height] = rect(&field["frame"])?;
|
||||
let [left_pct, top_pct, right_pct, bottom_pct] = [
|
||||
(left - x).clamp(0.0, w) / w * 100.0,
|
||||
(top - y).clamp(0.0, h) / h * 100.0,
|
||||
(left + width - x).clamp(0.0, w) / w * 100.0,
|
||||
(top + height - y).clamp(0.0, h) / h * 100.0,
|
||||
];
|
||||
(left_pct < right_pct && top_pct < bottom_pct).then(|| json!({
|
||||
"field":field["fieldId"],"bounds":[left_pct.floor() as u8,top_pct.floor() as u8,
|
||||
right_pct.ceil() as u8,bottom_pct.ceil() as u8]
|
||||
}))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn text_region_bounds(image: &egui::ColorImage, region: &Value) -> R<[usize; 4]> {
|
||||
let [width, height] = image.size;
|
||||
let [left, top, right, bottom]: [u8; 4] = serde_json::from_value(region["bounds"].clone())
|
||||
.map_err(|_| "实际文字框位置无效")?;
|
||||
let bounds = [(left, width), (top, height), (right, width), (bottom, height)]
|
||||
.map(|(percent, extent)| usize::from(percent.min(100)) * extent / 100);
|
||||
let [x0, y0, x1, y1] = bounds;
|
||||
if x0 >= x1 || y0 >= y1 {
|
||||
return Err("实际文字框没有可见像素".into());
|
||||
}
|
||||
Ok(bounds)
|
||||
}
|
||||
|
||||
pub(crate) fn text_edge_coverage(image: &egui::ColorImage, [x0, y0, x1, y1]: [usize; 4], vertical: bool) -> usize {
|
||||
let luma = |x, y| {
|
||||
let pixel: egui::Color32 = image[(x, y)];
|
||||
(i32::from(pixel.r()) * 77 + i32::from(pixel.g()) * 150 + i32::from(pixel.b()) * 29) / 256
|
||||
};
|
||||
let [width, height] = [x1 - x0, y1 - y0];
|
||||
let (across, along) = if vertical { (width, height) } else { (height, width) };
|
||||
if across < 18 || along < 12 {
|
||||
return 0;
|
||||
}
|
||||
let radius = (image.width().max(image.height()) / 320).clamp(2, 5);
|
||||
let margin = (across / 10).max(radius);
|
||||
(margin..across - margin).map(|position| {
|
||||
let mut dark_to_light = 0;
|
||||
let mut light_to_dark = 0;
|
||||
for scan in 1..along - 1 {
|
||||
let delta = if vertical {
|
||||
luma(x0 + position + radius, y0 + scan) - luma(x0 + position - radius, y0 + scan)
|
||||
} else {
|
||||
luma(x0 + scan, y0 + position + radius) - luma(x0 + scan, y0 + position - radius)
|
||||
};
|
||||
dark_to_light += usize::from(delta >= 40);
|
||||
light_to_dark += usize::from(delta <= -40);
|
||||
}
|
||||
dark_to_light.max(light_to_dark) * 100 / (along - 2)
|
||||
}).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn compare_text_region_edges(
|
||||
candidate: &egui::ColorImage, reference: &egui::ColorImage, regions: &[Value],
|
||||
) -> R<Vec<Value>> {
|
||||
let mut obstructions = Vec::new();
|
||||
for region in regions {
|
||||
let current = text_region_bounds(candidate, region)?;
|
||||
let pinned = text_region_bounds(reference, region)?;
|
||||
for (vertical, label) in [(true, "纵向"), (false, "横向")] {
|
||||
let coverage = text_edge_coverage(candidate, current, vertical);
|
||||
let allowance = text_edge_coverage(reference, pinned, vertical);
|
||||
if coverage >= 75 && coverage >= allowance + 20 {
|
||||
obstructions.push(json!({"field":region["field"],"direction":label,
|
||||
"coverage":coverage,"referenceCoverage":allowance}));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(obstructions)
|
||||
}
|
||||
|
||||
pub(crate) fn slot_frame<'a>(field: &'a Value, mapped: Option<&'a Value>) -> Option<&'a Value> {
|
||||
if field["nativeBounds"].is_object() {
|
||||
mapped.map(|row| &row["frame"]).filter(|frame| frame.is_object())
|
||||
} else {
|
||||
Some(&field["frame"])
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cover_review_preview(image: egui::ColorImage, frame: &Value) -> R<egui::ColorImage> {
|
||||
let extent = |key| frame[key].as_f64().filter(|value| value.is_finite() && *value > 0.0)
|
||||
.ok_or("候选缺少当前图位的实际图框");
|
||||
let (frame_width, frame_height) = (extent("width")?, extent("height")?);
|
||||
let [width, height] = image.size;
|
||||
let scale = (frame_width / width as f64).max(frame_height / height as f64);
|
||||
let visible_width = ((frame_width / scale).round() as usize).clamp(1, width);
|
||||
let visible_height = ((frame_height / scale).round() as usize).clamp(1, height);
|
||||
if [visible_width, visible_height] == image.size { return Ok(image); }
|
||||
let x = (width - visible_width) / 2;
|
||||
let y = (height - visible_height) / 2;
|
||||
let mut pixels = Vec::with_capacity(visible_width * visible_height);
|
||||
for row in y..y + visible_height {
|
||||
let start = row * width + x;
|
||||
pixels.extend_from_slice(&image.pixels[start..start + visible_width]);
|
||||
}
|
||||
Ok(egui::ColorImage::new([visible_width, visible_height], pixels))
|
||||
}
|
||||
|
||||
pub(crate) fn contain_review_preview(image: egui::ColorImage, frame: &Value) -> R<egui::ColorImage> {
|
||||
let ratio = frame["width"].as_f64().zip(frame["height"].as_f64()).map(|(w,h)| w/h)
|
||||
.filter(|ratio| ratio.is_finite() && *ratio > 0.0).ok_or("实拍标注缺少当前图框")?;
|
||||
let [width, height] = image.size;
|
||||
let long = width.max(height);
|
||||
let [w, h] = if ratio >= 1.0 { [long, ((long as f64 / ratio).round() as usize).max(1)] }
|
||||
else { [((long as f64 * ratio).round() as usize).max(1), long] };
|
||||
if [w, h] == image.size { return Ok(image); }
|
||||
let scale = (w as f64 / width as f64).min(h as f64 / height as f64);
|
||||
let (fit_w, fit_h) = (((width as f64 * scale).round() as usize).clamp(1,w),
|
||||
((height as f64 * scale).round() as usize).clamp(1,h));
|
||||
let (left, top) = ((w-fit_w)/2, (h-fit_h)/2);
|
||||
let mut result = egui::ColorImage::filled([w,h], egui::Color32::WHITE);
|
||||
for y in 0..fit_h {
|
||||
for x in 0..fit_w {
|
||||
result.pixels[(top+y)*w+left+x] = image.pixels[(y*height/fit_h)*width+x*width/fit_w];
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(crate) fn verify_adopted_source(dir: &Path, doc: &Document, mapped: &Value, artifact: &Value) -> R<()> {
|
||||
use photocraft_doc::{LayerContent, LayerId, SmartSource};
|
||||
let id = LayerId(mapped["nativeLayerId"].as_u64().ok_or("已回填图位没有图层身份")?);
|
||||
let layer = doc.layer(id).ok_or("已回填图层不可读取")?;
|
||||
let Some(path) = doc.path_of(id) else { return Err("已回填图层不在当前画布".into()) };
|
||||
if (1..=path.len()).any(|depth| !doc.layer_at(&path[..depth]).is_some_and(|layer| layer.visible && layer.opacity > 0.0)) {
|
||||
return Err("已回填图层已隐藏,保留当前编辑".into());
|
||||
}
|
||||
if mapped["embeddedTarget"].is_object() {
|
||||
return photocraft_ui_egui::jiansun::production_facts::read_embedded_layer(doc, &mapped["embeddedTarget"], |child, inner_id| {
|
||||
let inner = child.layer(inner_id).ok_or("已回填嵌入图层不可读取")?;
|
||||
let LayerContent::Smart(smart) = &inner.content else { return Err("已回填嵌入图层已改变,保留当前编辑".into()) };
|
||||
let SmartSource::Embedded { bytes, .. } = &smart.source else { return Err("已回填嵌入图层源文件已改变".into()) };
|
||||
if !matches_placed_candidate(dir, artifact, bytes) {
|
||||
return Err("已回填嵌入图层源图与候选不一致,保留当前编辑".into());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let LayerContent::Smart(smart) = &layer.content else { return Err("已回填图层已改变,保留当前编辑".into()) };
|
||||
let SmartSource::Embedded { bytes, .. } = &smart.source else { return Err("已回填图层源文件已改变".into()) };
|
||||
if !matches_placed_candidate(dir, artifact, bytes) {
|
||||
return Err("已回填图层源图与候选不一致,保留当前编辑".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn adopted_review_image(dir: &Path, doc: &Document, mapped: &Value, artifact: &Value, max_side: u32) -> R<egui::ColorImage> {
|
||||
use photocraft_geom::Rect;
|
||||
verify_adopted_source(dir, doc, mapped, artifact)?;
|
||||
let frame = &mapped["frame"];
|
||||
let coordinate = |key| frame[key].as_f64().filter(|value| value.is_finite() && *value >= 0.0)
|
||||
.ok_or("已回填图位没有实际图框");
|
||||
let (x, y, width, height) = (coordinate("x")?, coordinate("y")?, coordinate("width")?, coordinate("height")?);
|
||||
let bounds = doc.bounds();
|
||||
if width <= 0.0 || height <= 0.0 || x + width > f64::from(bounds.x1) || y + height > f64::from(bounds.y1) {
|
||||
return Err("已回填图框超出当前画布".into());
|
||||
}
|
||||
let area = Rect::new(x.floor() as i32, y.floor() as i32, (x + width).ceil() as i32, (y + height).ceil() as i32);
|
||||
let scale = (f64::from(max_side) / f64::from(area.width().max(area.height()))).min(1.0);
|
||||
let [w, h] = [area.width(), area.height()].map(|size| (f64::from(size) * scale).round().max(1.0) as u32);
|
||||
let image = photocraft_ui_egui::gpu_canvas::background_compose::render(doc, area, w, h).to_rgba8();
|
||||
Ok(egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &image.pixels))
|
||||
}
|
||||
|
||||
pub(crate) fn review_region_preview(image: &egui::ColorImage, bounds: [u8; 4]) -> R<Value> {
|
||||
let [width, height] = image.size;
|
||||
if bounds.iter().any(|&percent| percent > 100) {
|
||||
return Err("验图局部超出候选图框".into());
|
||||
}
|
||||
let [left, top, right, bottom] = bounds;
|
||||
let [x0, y0, x1, y1] = [(left, width), (top, height), (right, width), (bottom, height)]
|
||||
.map(|(percent, extent)| usize::from(percent) * extent / 100);
|
||||
if x0 >= x1 || y0 >= y1 {
|
||||
return Err("验图局部没有可见像素".into());
|
||||
}
|
||||
let crop_width = x1 - x0;
|
||||
let mut pixels = Vec::with_capacity(crop_width * (y1 - y0));
|
||||
for y in y0..y1 {
|
||||
let offset = y * width;
|
||||
pixels.extend_from_slice(image.pixels.get(offset + x0..offset + x1).ok_or("候选图像像素不完整")?);
|
||||
}
|
||||
let crop = egui::ColorImage::new([crop_width, y1 - y0], pixels);
|
||||
Ok(json!({"type":"image","data":photocraft_ui_egui::jiansun::reference_jpeg(&crop,768)?,"mimeType":"image/jpeg"}))
|
||||
}
|
||||
|
||||
pub(crate) fn swatch_has_white_backdrop(image: &egui::ColorImage) -> bool {
|
||||
let [width, height] = image.size;
|
||||
if width == 0 || height == 0 { return false; }
|
||||
let white = |px: &egui::Color32| px.r().min(px.g()).min(px.b()) >= 248;
|
||||
let white_count = image.pixels.iter().filter(|px| white(px)).count();
|
||||
if white_count * 50 < image.pixels.len() { return false; }
|
||||
let rows = image.pixels.chunks_exact(width);
|
||||
let horizontal = [rows.clone().next().unwrap_or(&[]), rows.clone().last().unwrap_or(&[])];
|
||||
let vertical = [0, width - 1];
|
||||
if white_count * 20 >= image.pixels.len() && (horizontal.iter()
|
||||
.any(|row| row.iter().filter(|px| white(px)).count() * 10 >= width * 9)
|
||||
|| vertical.iter().any(|&column|
|
||||
rows.clone().filter(|row| white(&row[column])).count() * 10 >= height * 9)) {
|
||||
return true;
|
||||
}
|
||||
// A small corner of the original background can reach only part of an
|
||||
// edge. Require a solid white run beside a visibly darker material.
|
||||
let center = rows.skip(height / 4).take(height.div_ceil(2))
|
||||
.flat_map(|row| row.iter().skip(width / 4).take(width.div_ceil(2)));
|
||||
let (dark, total) = center.fold((0, 0), |(dark, total), px| {
|
||||
(dark + usize::from(px.r().max(px.g()).max(px.b()) <= 232), total + 1)
|
||||
});
|
||||
if dark * 2 < total { return false; }
|
||||
fn has_run(mut values: impl Iterator<Item = bool>, length: usize) -> bool {
|
||||
let mut run = 0;
|
||||
values.any(|value| {
|
||||
run = if value { run + 1 } else { 0 };
|
||||
run >= length.div_ceil(5).max(4)
|
||||
})
|
||||
}
|
||||
horizontal.iter().any(|row| has_run(row.iter().map(white), width))
|
||||
|| vertical.iter().any(|&column|
|
||||
has_run(image.pixels.chunks_exact(width).map(|row| white(&row[column])), height))
|
||||
}
|
||||
|
||||
pub(crate) fn product_crop_mode<'a>(state: &'a Value, output: &Value, field: &Value) -> R<Option<&'a str>> {
|
||||
let profile = production_profile::select(&state["template"], output["component"].as_str().unwrap_or_default())?;
|
||||
Ok(field["fieldId"].as_str().and_then(|id|
|
||||
profile.and_then(|profile| profile["imageRules"][id]["cropMode"].as_str())))
|
||||
}
|
||||
|
||||
pub(crate) fn specified_image_ratio(field: &Value) -> Option<(u64, u64)> {
|
||||
let description = field["outputSpec"].as_str().or_else(|| field["requirements"].as_str())?;
|
||||
let text = description.split_once("标准比例")?.1.trim_start_matches([' ', ':', ':']);
|
||||
let left = text.split(&[':', ':'][..]).next()?;
|
||||
let right = text.get(left.len()..)?.trim_start_matches([':', ':', ' ']).chars().take_while(char::is_ascii_digit).collect::<String>();
|
||||
let width: u64 = left.trim().parse().ok()?;
|
||||
let height: u64 = right.parse().ok()?;
|
||||
((1..=21).contains(&width) && (1..=21).contains(&height)).then_some((width, height))
|
||||
}
|
||||
|
||||
pub(crate) fn references(dir: &Path, images: &Value) -> R<Vec<Value>> {
|
||||
let images = images.as_array().filter(|v| v.len() <= 8).ok_or("每花色最多8张产品/场景参考图")?;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for image in images {
|
||||
let source = image["source"].as_str().ok_or("参考图来源缺失")?;
|
||||
let hash = source.strip_prefix("local:").filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())).ok_or("参考图须为本项目本机资产")?;
|
||||
if !seen.insert((source, image["fieldKey"].as_str(), image["barcode"].as_str()))
|
||||
|| !matches!(image["purpose"].as_str(), Some("product" | "scene")) {
|
||||
return Err("参考图重复或用途无效".into());
|
||||
}
|
||||
let file = dir.join("creation-assets").join(format!("{hash}.png"));
|
||||
let root = dir.canonicalize().map_err(|_| "项目目录不可读取")?;
|
||||
let assets = dir.join("creation-assets");
|
||||
let assets_meta = assets.symlink_metadata().map_err(|_| "参考图目录不可读取")?;
|
||||
let meta = file.symlink_metadata().map_err(|_| "花色参考图尚未保存到本机项目")?;
|
||||
if !meta.is_file()
|
||||
|| meta.file_type().is_symlink()
|
||||
|| assets_meta.file_type().is_symlink()
|
||||
|| meta.len() > 10 * 1024 * 1024
|
||||
|| assets.canonicalize().map_err(|_| "参考图目录不可读取")?.parent() != Some(root.as_path())
|
||||
|| file.canonicalize().map_err(|_| "参考图不可读取")?.parent() != Some(assets.canonicalize().map_err(|_| "参考图目录不可读取")?.as_path())
|
||||
{
|
||||
return Err("参考图不属于本项目或超过限制".into());
|
||||
}
|
||||
let bytes = fs::read(&file).map_err(|_| "参考图不可读取")?;
|
||||
if format!("{:x}", Sha256::digest(&bytes)) != hash {
|
||||
return Err("参考图内容已变化,未使用错误花色图片".into());
|
||||
}
|
||||
let mut row = json!({"source":source,"purpose":image["purpose"],"name":text(&image["name"],200,"参考图名称")?});
|
||||
for key in ["imageRole","fieldKey","templateId","barcode"] {
|
||||
if let Some(value) = image.get(key) { row[key] = value.clone(); }
|
||||
}
|
||||
out.push(row);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
pub(crate) fn generation_references(dir: &Path, state: &Value, variant_id: &str) -> R<Value> {
|
||||
generation_references_for_output(dir, state, variant_id, state["activeOutput"].as_str().unwrap_or("detail"))
|
||||
}
|
||||
|
||||
pub(crate) fn generation_references_for_output(dir: &Path, state: &Value, variant_id: &str, component: &str) -> R<Value> {
|
||||
let selected = variant(state, variant_id)?;
|
||||
let brief = &state["brief"];
|
||||
let selected_barcode = (component == "detail").then(|| creation::detail_barcode(brief)).flatten();
|
||||
let sku_target = (component == "sku_images").then(|| resolve_sku_spec_target(brief, variant_id)).flatten();
|
||||
let color_id = selected["id"].as_str().unwrap_or(variant_id);
|
||||
let count = state["variants"].as_array().map_or(0, Vec::len);
|
||||
let barcode_matches = |code: &str| {
|
||||
selected_barcode.is_none_or(|selected| selected == code)
|
||||
&& sku_target.as_ref().map_or_else(
|
||||
|| creation::variant_barcodes(brief, color_id, count).any(|barcode| barcode == code),
|
||||
|target| target.barcodes.iter().any(|barcode| barcode == code),
|
||||
)
|
||||
};
|
||||
let entries = sku_target.as_ref().filter(|target| !target.entries.is_empty()).map_or_else(
|
||||
|| brief["barcodeEntries"].as_array().map_or(&[][..], Vec::as_slice),
|
||||
|target| target.entries.as_slice(),
|
||||
);
|
||||
let mut images = Vec::new();
|
||||
let mut add = |image: Value, priority| {
|
||||
if !images.iter().any(|(_, existing): &(u8, Value)| existing["source"] == image["source"]
|
||||
&& existing["fieldKey"] == image["fieldKey"] && existing["barcode"] == image["barcode"]) {
|
||||
images.push((priority, image));
|
||||
}
|
||||
};
|
||||
for entry in entries {
|
||||
let Some(code) = entry["barcode"].as_str().filter(|code| barcode_matches(code)) else { continue; };
|
||||
for mut image in entry["images"].as_array().into_iter().flatten().cloned() {
|
||||
image["barcode"] = json!(code);
|
||||
add(image, 0);
|
||||
}
|
||||
}
|
||||
for image in selected["images"].as_array().into_iter().flatten() {
|
||||
if image["barcode"].as_str().is_none_or(barcode_matches) {
|
||||
add(image.clone(), 1);
|
||||
}
|
||||
}
|
||||
for image in brief["images"].as_array().into_iter().flatten() {
|
||||
let use_image = if let Some(code) = image["barcode"].as_str() {
|
||||
barcode_matches(code)
|
||||
} else {
|
||||
image["purpose"] != "product" || !state["productTemplates"].is_object() || count <= 1
|
||||
};
|
||||
if use_image {
|
||||
add(image.clone(), if image["barcode"].is_string() { 0 } else { 2 });
|
||||
}
|
||||
}
|
||||
// This is also the order used by previews and the native generation index.
|
||||
images.sort_by_key(|(priority, image)| (image["purpose"] != "product", *priority));
|
||||
let images = references(dir, &json!(images.into_iter().take(8).map(|(_, image)| image).collect::<Vec<_>>()))?;
|
||||
if !images.iter().any(|image| image["purpose"] == "product") {
|
||||
return Err("请为当前花色添加至少一张产品实拍或CAD导出图片;场景图不能单独作为产品外观依据,未预留或发送请求".into());
|
||||
}
|
||||
Ok(json!(images))
|
||||
}
|
||||
|
||||
// Compatibility for older single-output drafts that were saved with empty copy.
|
||||
pub(crate) fn clear_sample_copy(layers: &mut [photocraft_doc::Layer]) {
|
||||
use photocraft_doc::LayerContent;
|
||||
for layer in layers {
|
||||
match &mut layer.content {
|
||||
LayerContent::Text(text) => {
|
||||
text.text.clear();
|
||||
text.cache = None;
|
||||
text.psd_raw = None;
|
||||
text.runs.truncate(1);
|
||||
text.paragraphs.truncate(1);
|
||||
for run in &mut text.runs { run.len = 0; }
|
||||
for run in &mut text.paragraphs { run.len = 0; }
|
||||
layer.psd_blocks.retain(|(key, _)| key != b"TySh");
|
||||
}
|
||||
LayerContent::Group(group) => clear_sample_copy(&mut group.children),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_product_template(native: &mut Document, meta: &mut Value, pack: &Value, component: &str) -> R<()> {
|
||||
let profile = production_profile::select(pack, component)?;
|
||||
meta["fidelityBaseline"] = fidelity::baseline(native, meta, profile);
|
||||
if let Some(profile) = profile {
|
||||
production_profile::apply(native, meta, profile)?;
|
||||
meta["productionProfile"] = production_profile::source(pack, component);
|
||||
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))
|
||||
{
|
||||
native.metadata.text.push(("jiansun.allowed-changes.v1".into(), policy.to_string()));
|
||||
}
|
||||
production_profile::bind_fixed_text(native, meta, profile);
|
||||
photocraft_ui_egui::jiansun::production_facts::bind_original_fixed_text(native, meta);
|
||||
if pack["enterprise"].is_object() {
|
||||
production_profile::hide_sample_photos(native, meta);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,390 @@
|
||||
use super::super::{Path, R, Uuid, Value, creation, fs, hash, images, json, read_json, read_json_with_missing, sync, template_slots, write_json};
|
||||
use super::{CANDIDATE, binding_is_canvas, candidate_path, candidate_pixels, check_image_context, definition, exists, image_output_state, load, local_candidate, mapped_slot, pending, persist_locked, project_candidate, reconcile_candidate, references, revision, text, uuid, variant};
|
||||
use photocraft_ui_egui::jiansun::production_facts::product_brief::{resolve_sku_spec_target, shared_variant_brief, variant_brief, variant_intake};
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
|
||||
pub(crate) fn variants(dir: &Path, brief: &Value, previous: Option<&Value>) -> R<Vec<Value>> {
|
||||
let empty = Vec::new();
|
||||
let raw = match brief.get("variants") {
|
||||
None => &empty,
|
||||
Some(value) => value.as_array().filter(|v| v.len() <= 64).ok_or("花色资料须为数组,最多64项")?,
|
||||
};
|
||||
if raw.is_empty() {
|
||||
if let Some(old) = previous {
|
||||
return Ok(old["variants"].as_array().ok_or("原花色记录无效")?.clone());
|
||||
}
|
||||
return Ok(vec![
|
||||
json!({"id":Uuid::new_v4().to_string(),"name":brief["variant"],"colorName":brief["colorName"],"colorMaterialId":brief["colorMaterialId"],"images":[],"dimensions":brief["dimensions"]}),
|
||||
]);
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for row in raw {
|
||||
let id = uuid(&row["id"], "花色")?;
|
||||
if !seen.insert(id.clone()) {
|
||||
return Err("花色编号重复,未覆盖资料".into());
|
||||
}
|
||||
let mut variant = json!({"id":id,"name":text(&row["name"],200,"花色名称")?,"colorName":text(&row["colorName"],200,"颜色")?,
|
||||
"colorMaterialId":text(&row["colorMaterialId"],150,"材质编号")?,"images":references(dir,&row["images"])? ,"dimensions":brief["dimensions"]});
|
||||
if let Some(colors) = row.get("outputColors") {
|
||||
variant["outputColors"] = colors.clone();
|
||||
}
|
||||
out.push(variant);
|
||||
}
|
||||
if let Some(old) = previous {
|
||||
for previous in old["variants"].as_array().into_iter().flatten() {
|
||||
if !seen.contains(previous["id"].as_str().unwrap_or("")) {
|
||||
return Err("已有花色不能在创建画布时移除;原候选和编辑稿已保留".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn skeleton_component<'a>(state: &'a Value, input: &'a Value) -> R<&'a str> {
|
||||
let enterprise = &state["template"]["enterprise"];
|
||||
if input["brief"].is_object() && !state["productTemplates"].is_object() && enterprise.is_object() {
|
||||
enterprise["component"].as_str().ok_or_else(|| "固定模板组件缺失".into())
|
||||
} else {
|
||||
Ok(input["outputId"].as_str().unwrap_or("detail"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_template(previous: Option<&Value>, selected: &Value, brand: &str, category: &str, fetch: impl FnOnce() -> R<Value>) -> R<Value> {
|
||||
// An existing project owns its immutable pack. A newer catalogue entry is
|
||||
// relevant only when explicitly creating another project/version.
|
||||
let pack = if let Some(previous) = previous { previous["template"].clone() } else { fetch()? };
|
||||
template_slots::validate_pack(&pack)?;
|
||||
if pack["brandId"] != brand || pack["categoryId"] != category {
|
||||
return Err("更换品牌或品类模板须另建项目版本,原候选和人工编辑保留".into());
|
||||
}
|
||||
for key in ["id", "version", "contentHash"] {
|
||||
if selected[key] != pack[key] {
|
||||
return Err(if previous.is_some() {
|
||||
"更换模板须另建项目版本,原候选和人工编辑保留"
|
||||
} else {
|
||||
"所选模板版本与真实目录不一致,请重新选择"
|
||||
}
|
||||
.into());
|
||||
}
|
||||
}
|
||||
Ok(pack)
|
||||
}
|
||||
|
||||
pub(crate) fn apply_saved_variant_edits(dir: &Path) -> R<()> {
|
||||
if !exists(dir) { return Ok(()); }
|
||||
let _guard = sync::context_guard();
|
||||
let mut state = load(dir)?;
|
||||
let creation = creation::load(dir)?;
|
||||
let brief = &creation["brief"];
|
||||
if !state["productTemplates"].is_object() || state["brief"] == *brief
|
||||
|| state["brief"]["templateSelection"] != brief["templateSelection"]
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let ids = |rows: &Value| rows.as_array().into_iter().flatten()
|
||||
.map(|row| &row["id"]).cloned().collect::<Vec<_>>();
|
||||
let old_ids = ids(&state["variants"]);
|
||||
let new_ids = ids(&brief["variants"]);
|
||||
if !new_ids.is_empty() && old_ids.iter().any(|id| !new_ids.contains(id)) { return Ok(()); }
|
||||
|
||||
state["variants"] = json!(variants(dir, brief, Some(&state))?);
|
||||
state["brief"] = brief.clone();
|
||||
let expected = revision(&state);
|
||||
persist_locked(dir, &mut state, expected)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) const VARIANT_INPUT_HASH: &str = "variant-v1:";
|
||||
|
||||
pub(crate) fn variant_input_hash(state: &Value, creation: &Value, variant_id: &str, component: &str, template: &Value, structure: &Value) -> R<String> {
|
||||
let selected = variant(state, variant_id)?;
|
||||
let live = &creation["brief"];
|
||||
let mut inputs = json!({"brief":shared_variant_brief(&state["brief"]),"liveBrief":shared_variant_brief(live),
|
||||
"liveVariant":variant_brief(live, variant_id),"variant":selected,
|
||||
"multiVariant":state["variants"].as_array().is_some_and(|rows| rows.len() > 1),
|
||||
"templateHash":template,"structureHash":structure,"rules":creation["designSnapshot"]});
|
||||
if component == "detail" && (state["brief"].get("detailBarcode").is_some() || live.get("detailBarcode").is_some()) {
|
||||
inputs["detailBarcode"] = json!(creation::detail_barcode(&state["brief"]));
|
||||
inputs["liveDetailBarcode"] = json!(creation::detail_barcode(live));
|
||||
}
|
||||
if let Some(fields) = variant_intake(&state["brief"], variant_id, component) { inputs["variantIntake"] = fields; }
|
||||
if let Some(fields) = variant_intake(live, variant_id, component) { inputs["liveVariantIntake"] = fields; }
|
||||
if component == "sku_images" {
|
||||
if let Some(target) = resolve_sku_spec_target(&state["brief"], variant_id)
|
||||
&& target.target_id != target.color_variant_id
|
||||
{
|
||||
inputs["specTarget"] = json!({"specId": target.spec_id, "barcodes": target.barcodes, "entries": target.entries});
|
||||
}
|
||||
if let Some(target) = resolve_sku_spec_target(live, variant_id)
|
||||
&& target.target_id != target.color_variant_id
|
||||
{
|
||||
inputs["liveSpecTarget"] = json!({"specId": target.spec_id, "barcodes": target.barcodes, "entries": target.entries});
|
||||
}
|
||||
}
|
||||
Ok(format!("{VARIANT_INPUT_HASH}{}", hash(&inputs.to_string())))
|
||||
}
|
||||
|
||||
pub(crate) fn input_hash(dir: &Path, state: &Value, variant_id: &str) -> R<String> {
|
||||
variant_input_hash(state, &creation::load(dir)?, variant_id, state["activeOutput"].as_str().unwrap_or("detail"), &state["template"]["contentHash"], &state["structureHash"])
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_uses_current_inputs(dir: &Path, state: &Value, record: &Value, variant_id: &str) -> R<bool> {
|
||||
candidate_matches_inputs(state, record, variant_id, state["activeOutput"].as_str().unwrap_or("detail"), &creation::load(dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_matches_inputs(state: &Value, record: &Value, variant_id: &str, component: &str, creation: &Value) -> R<bool> {
|
||||
let saved = &record["inputHash"];
|
||||
if saved.as_str().is_some_and(|value| value.starts_with(VARIANT_INPUT_HASH)) {
|
||||
return Ok(*saved == variant_input_hash(state, creation, variant_id, component, &state["template"]["contentHash"], &state["structureHash"])?);
|
||||
}
|
||||
let old = json!({"brief":state["brief"],"liveBrief":creation["brief"],"variant":variant(state,variant_id)?,
|
||||
"templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"rules":creation["designSnapshot"]});
|
||||
Ok(*saved == hash(&old.to_string()))
|
||||
}
|
||||
pub(crate) fn read_candidate(dir: &Path, id: &str) -> R<Value> {
|
||||
let path = candidate_path(dir, id)?;
|
||||
let mut record = read_json_with_missing(&path, "文件缺失")
|
||||
.map_err(|error| format!("候选 {id}({CANDIDATE}):{error}"))?;
|
||||
if record["version"] != 2
|
||||
|| record["id"] != id
|
||||
|| record["binding"]["candidateId"] != id
|
||||
|| record["binding"]["taskId"] != id
|
||||
|| !matches!(record["phase"].as_str(), Some("prepared" | "dispatched" | "running" | "unknown" | "complete" | "failed" | "expired"))
|
||||
{
|
||||
return Err("候选记录或原请求身份无效".into());
|
||||
}
|
||||
super::images::reopen_ambiguous_expiry(&mut record);
|
||||
Ok(record)
|
||||
}
|
||||
pub(crate) fn retired_archive(dir: &Path, id: &str) -> bool {
|
||||
read_candidate(dir, id).is_ok_and(|record| record["retirement"].is_object())
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_available(record: &Value) -> bool {
|
||||
record["phase"] == "complete" && record["retirement"].is_null()
|
||||
}
|
||||
|
||||
pub(crate) fn lock_candidate_dispatch(dir: &Path, id: &str) -> R<Option<fs::File>> {
|
||||
lock_image_dispatch(&candidate_path(dir, id)?.with_file_name("dispatch.lock"))
|
||||
}
|
||||
|
||||
pub(crate) fn lock_slot_dispatch(dir: &Path, slot: &Value) -> R<Option<fs::File>> {
|
||||
let id = slot["slotId"].as_str().filter(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
.ok_or("图片图位身份无效")?;
|
||||
lock_image_dispatch(&dir.join("image-jobs").join("slot-dispatch").join(id))
|
||||
}
|
||||
|
||||
pub(crate) fn lock_image_dispatch(path: &Path) -> R<Option<fs::File>> {
|
||||
fs::create_dir_all(path.parent().ok_or("原候选路径无效")?).map_err(|error| error.to_string())?;
|
||||
let file = fs::OpenOptions::new().read(true).write(true).create(true).truncate(false)
|
||||
.open(path).map_err(|error| error.to_string())?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Err(fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(fs::TryLockError::Error(error)) => Err(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_image_dispatch_cancelled(cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<(), BridgeFailure> {
|
||||
if cancellation.is_some_and(|token| token.load(std::sync::atomic::Ordering::SeqCst)) {
|
||||
return Err(BridgeFailure::new("cancelled", false, false, "原制作回合已停止,生图未派发"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pending_candidate(record: &Value) -> Value {
|
||||
let mut pending = record.clone();
|
||||
pending["phase"] = json!("unknown");
|
||||
pending["message"] = json!("原任务尚待确认,请继续核查原候选");
|
||||
pending
|
||||
}
|
||||
|
||||
// The caller owns the dispatch lock and has checked that task.json is absent.
|
||||
pub(crate) fn recover_candidate_without_task(dir: &Path, record: &Value) -> R<Value> {
|
||||
match record["phase"].as_str() {
|
||||
Some("failed" | "expired") => Ok(record.clone()),
|
||||
Some("prepared") if record["requestId"].is_null() =>
|
||||
reconcile_candidate(dir, &json!({"id":record["id"],"slotBinding":record["binding"],
|
||||
"phase":"prepared","notDispatched":true,"message":"这张图未提交生成,可以重新发起"})),
|
||||
_ => {
|
||||
let mut pending = pending_candidate(record);
|
||||
pending["message"] = json!(format!("候选 {} 缺少 task.json,原结果仍待核查", record["id"]));
|
||||
Ok(pending)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unindexed_candidate_ids(dir: &Path, seen: &std::collections::HashSet<String>) -> R<Vec<String>> {
|
||||
let jobs = dir.join("image-jobs");
|
||||
let mut ids = Vec::new();
|
||||
if jobs.exists() {
|
||||
for entry in fs::read_dir(jobs).map_err(|_| "候选归档目录不可读取")? {
|
||||
let entry = entry.map_err(|_| "候选归档目录读取中断")?;
|
||||
let id = entry.file_name().to_string_lossy().into_owned();
|
||||
if entry.path().join(CANDIDATE).exists() && !seen.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ids.sort_unstable();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(crate) fn records(dir: &Path, state: &Value) -> R<Vec<Value>> {
|
||||
read_records(dir, state, false)
|
||||
}
|
||||
|
||||
pub(crate) fn read_records(dir: &Path, state: &Value, include_completed_orphans: bool) -> R<Vec<Value>> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in state["candidates"].as_array().ok_or("候选索引无效")? {
|
||||
let id = uuid(id, "候选")?;
|
||||
if !seen.insert(id.clone()) {
|
||||
return Err("候选索引重复,原历史保留".into());
|
||||
}
|
||||
let record = read_candidate(dir, &id)?;
|
||||
if record["binding"]["workspaceId"] != state["id"] {
|
||||
return Err("候选不属于当前项目,原记录保留".into());
|
||||
}
|
||||
out.push(record);
|
||||
}
|
||||
for id in unindexed_candidate_ids(dir, &seen)? {
|
||||
if include_completed_orphans
|
||||
&& let Ok(record) = read_candidate(dir, &id)
|
||||
&& let Some((mut record, _)) = completed_candidate(dir, state, record, false)
|
||||
{
|
||||
record["unindexed"] = json!(true);
|
||||
out.push(record);
|
||||
} else {
|
||||
return Err("发现未完成写入的候选预留,原记录保留;未开始新请求".into());
|
||||
}
|
||||
}
|
||||
if include_completed_orphans { out.sort_by_key(|record| record["sequence"].as_u64()); }
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// An unindexed record is only evidence of a result when the independent
|
||||
// task journal agrees. Indexed terminal records retain their own pixel digest.
|
||||
pub(crate) fn completed_candidate(dir: &Path, state: &Value, mut record: Value, indexed: bool) -> Option<(Value, Vec<u8>)> {
|
||||
let binding = &record["binding"];
|
||||
let variant_id = uuid(&binding["variantId"], "花色").ok()?;
|
||||
if !binding_is_canvas(binding) || binding["workspaceId"] != state["id"]
|
||||
|| variant(state, &variant_id).is_err() || record["retirement"].is_object()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let id = uuid(&record["id"], "候选").ok()?;
|
||||
if !indexed || matches!(record["phase"].as_str(), Some("prepared" | "dispatched" | "running" | "unknown")) {
|
||||
let task = read_json(&candidate_path(dir, &id).ok()?.with_file_name("task.json")).ok()?;
|
||||
if task["id"] != id || task["slotBinding"] != *binding
|
||||
|| !matches!(task["phase"].as_str(), Some("complete" | "applied"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if record["phase"] == "complete" {
|
||||
if record["artifact"] != template_slots::artifact(dir, &id, &task).ok()? {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
record = project_candidate(dir, &record, &task).ok()?;
|
||||
}
|
||||
}
|
||||
if !candidate_available(&record) || record["artifact"]["taskId"] != id {
|
||||
return None;
|
||||
}
|
||||
let pixels = candidate_pixels(dir, &record["artifact"]).ok()?;
|
||||
Some((record, pixels))
|
||||
}
|
||||
|
||||
pub(crate) fn pending_production_image(record: &Value, task: &Value) -> R<Option<Value>> {
|
||||
let binding = &record["binding"];
|
||||
if binding["detailBatch"] != true || !task["outputScope"].is_string() || !record["sourceType"].is_null()
|
||||
|| !record["retirement"].is_null()
|
||||
|| !matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = uuid(&record["id"], "原候选")?;
|
||||
if task["id"] != id || task["slotBinding"] != *binding {
|
||||
return Err("原候选任务与图位记录不一致".into());
|
||||
}
|
||||
Ok(Some(json!({"candidateId":id,"operationId":record["workflowOperationId"].as_str().unwrap_or(&id),
|
||||
"slotId":binding["slotId"],"variantId":binding["variantId"],"outputId":task["outputScope"],
|
||||
"phase":task["phase"],"reason":task["message"]})))
|
||||
}
|
||||
|
||||
pub(crate) fn pending_production_images(dir: &Path, state: &Value) -> R<Value> {
|
||||
let mut pending = Vec::new();
|
||||
for record in records(dir, state)? {
|
||||
let binding = &record["binding"];
|
||||
if binding["detailBatch"] != true || !record["sourceType"].is_null()
|
||||
|| !record["retirement"].is_null()
|
||||
|| matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
|
||||
continue;
|
||||
}
|
||||
let id = uuid(&record["id"], "原候选")?;
|
||||
let file = dir.join("image-jobs").join(&id).join("task.json");
|
||||
if !file.try_exists().map_err(|error| error.to_string())? { continue; }
|
||||
pending.extend(pending_production_image(&record, &read_json(&file)?)?);
|
||||
}
|
||||
Ok(json!(pending))
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scoped: bool) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
let original = load(dir)?;
|
||||
let binding = &record["binding"];
|
||||
let batch = (binding["detailBatch"] == true).then_some(binding);
|
||||
let user = binding["origin"] == "human" || record["origin"] == "human";
|
||||
if record["phase"] == "complete" && (record["sourceType"] == "archived-candidate"
|
||||
|| record["origin"] == "human" && local_candidate(record))
|
||||
{
|
||||
let operator_reuse = record["origin"] == "human" && record["sourceType"] == "archived-candidate";
|
||||
if !operator_reuse && creation::load(dir)?["brief"] != original["brief"] {
|
||||
return Err("产品资料已变化,未添加候选".into());
|
||||
}
|
||||
} else {
|
||||
let manual = user.then_some(binding);
|
||||
check_image_context(dir, None, batch.or(manual))?;
|
||||
}
|
||||
if project_scoped || user {
|
||||
let scoped = image_output_state(original.clone(), binding)?;
|
||||
let variant = binding["variantId"].as_str().ok_or("花色缺失")?;
|
||||
let slot = binding["slotId"].as_str().ok_or("图片图位缺失")?;
|
||||
let (output, field) = definition(&scoped, slot, variant)?;
|
||||
if binding["workspaceId"] != scoped["id"] || binding["outputId"] != output["id"]
|
||||
|| binding["fieldId"] != field["fieldId"]
|
||||
|| user && mapped_slot(&state, slot, variant) != mapped_slot(&scoped, slot, variant)
|
||||
|| !candidate_uses_current_inputs(dir, &scoped, record, variant)? {
|
||||
return Err("商品资料或制作依据已变化,请重新准备请求".into());
|
||||
}
|
||||
state = original;
|
||||
} else if revision(&state) != revision(&original) {
|
||||
if batch.is_none() || ["structureHash", "id", "activeVariantId", "activeOutput", "mappings"].iter().any(|key| original[*key] != state[*key])
|
||||
|| !candidate_uses_current_inputs(dir, &original, record, binding["variantId"].as_str().ok_or("花色身份无效")?)?
|
||||
{
|
||||
return Err("图片目标在准备期间有改动,候选未添加。".into());
|
||||
}
|
||||
state = original;
|
||||
}
|
||||
let expected = revision(&state);
|
||||
let file = candidate_path(dir, record["id"].as_str().ok_or("候选身份缺失")?)?;
|
||||
if file.exists() {
|
||||
return Err("候选已存在,未重复预留".into());
|
||||
}
|
||||
let candidates = state["candidates"].as_array_mut().ok_or("候选索引无效")?;
|
||||
let mut record = record.clone();
|
||||
record["sequence"] = json!(candidates.len() + 1);
|
||||
candidates.push(record["id"].clone());
|
||||
// A crash between these writes is default-deny: records() detects orphans.
|
||||
write_json(&file, &record)?;
|
||||
if let Err(error) = persist_locked(dir, &mut state, expected) {
|
||||
if record["canvasTransform"].is_object() {
|
||||
let _ = fs::remove_file(&file);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,887 @@
|
||||
use super::super::{json, Document, Instant, LayerContent, PhotocraftApp, Request, Ui, Value, Workspace};
|
||||
use super::document::{adopted, document_mapping, manual_image, native_layer};
|
||||
use super::projection::{native_selection_subject, target_summary};
|
||||
use super::bound_project;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) static ADOPTION_WORKER_BUSY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
pub(crate) static ADOPTION_PREWARM_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
pub(crate) struct AdoptionWorker {
|
||||
pub(crate) meta: Value,
|
||||
pub(crate) pending: Value,
|
||||
pub(crate) project: Option<String>,
|
||||
pub(crate) write_mode: Value,
|
||||
pub(crate) active_layer: Option<photocraft_doc::LayerId>,
|
||||
pub(crate) selected_layers: Vec<photocraft_doc::LayerId>,
|
||||
pub(crate) source_ticket: photocraft_engine::smart_cmds::SourceTicket,
|
||||
pub(crate) manual_basis: Option<Arc<Document>>,
|
||||
pub(crate) approve_recheck: std::sync::mpsc::SyncSender<bool>,
|
||||
pub(crate) prepared: Option<(Document, Option<AdoptionSnapshot>)>,
|
||||
pub(crate) prewarm_id: Option<u64>,
|
||||
pub(crate) prewarm_ready: bool,
|
||||
pub(crate) post_source_check: Option<std::sync::mpsc::Receiver<Result<[u8;32], String>>>,
|
||||
pub(crate) result: std::sync::mpsc::Receiver<AdoptionProgress>,
|
||||
}
|
||||
|
||||
pub(crate) enum AdoptionProgress {
|
||||
Prepared,
|
||||
Done(Result<Box<(Document, Option<AdoptionSnapshot>)>, String>),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_ADOPTION_SOURCE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
pub(crate) struct AdoptionSnapshot {
|
||||
pub(crate) before_doc: std::sync::Arc<Document>,
|
||||
pub(crate) source_digest: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
pub(crate) fn embedded_replacement_frame(doc: &Document, layer: &photocraft_doc::Layer) -> bool {
|
||||
layer.vector_mask.as_ref().is_some_and(|mask|mask.enabled)
|
||||
&& matches!(&layer.content,LayerContent::Smart(smart) if match &smart.source {
|
||||
photocraft_doc::SmartSource::Embedded {..} => true,
|
||||
photocraft_doc::SmartSource::Linked {path} => photocraft_io::linked::embedded_file_name(&doc.metadata,path).is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
pub struct PreparedAdoption {
|
||||
pub document: Document,
|
||||
pub(crate) before: Option<std::sync::Arc<Document>>,
|
||||
pub(crate) source_digest: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
pub(crate) fn visible_retouch_layers(doc: &Document, target: u64) -> impl Iterator<Item = photocraft_doc::LayerId> + '_ {
|
||||
let key = format!("photocraft.remove.{target}");
|
||||
doc.metadata.text.iter().filter(move |(name, _)| *name == key)
|
||||
.filter_map(|(_, value)| value.parse().ok().map(photocraft_doc::LayerId))
|
||||
.filter(move |id| doc.layer(*id).is_some_and(|layer| layer.visible))
|
||||
}
|
||||
|
||||
pub(crate) fn apply_opaque_white_background(bytes: Vec<u8>, contain: bool, target_frame: Option<(u32, u32)>) -> Result<Vec<u8>, String> {
|
||||
let image = photocraft_codecs::decode(&bytes).map_err(|_| "候选图片无法解码,请更换图片后重试".to_string())?;
|
||||
let (nw, nh) = image.dimensions();
|
||||
if nw == 0 || nh == 0 {
|
||||
return Err("候选图片尺寸无效".into());
|
||||
}
|
||||
let mut rgba = image.to_rgba8();
|
||||
let has_transparency = rgba.chunks_exact(4).any(|px| px[3] < 255);
|
||||
if !contain && !has_transparency {
|
||||
return Ok(bytes);
|
||||
}
|
||||
if !contain {
|
||||
for px in rgba.chunks_exact_mut(4) {
|
||||
let a = px[3] as u32;
|
||||
if a < 255 {
|
||||
let inv = 255 - a;
|
||||
px[0] = ((px[0] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[1] = ((px[1] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[2] = ((px[2] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[3] = 255;
|
||||
}
|
||||
}
|
||||
let flattened = photocraft_codecs::Image::from_u8(nw, nh, photocraft_codecs::ChannelLayout::Rgba, rgba)
|
||||
.map_err(|_| "白底合成失败,请稍后重试".to_string())?;
|
||||
return photocraft_codecs::encode(&flattened, photocraft_codecs::Format::Png, &Default::default())
|
||||
.map_err(|_| "白底合成编码失败,请稍后重试".to_string());
|
||||
}
|
||||
let (tw, th) = target_frame.filter(|&(w, h)| w > 0 && h > 0).unwrap_or((nw, nh));
|
||||
let (cw, ch, dst_w, dst_h) = if (nw as u64) * (th as u64) >= (nh as u64) * (tw as u64) {
|
||||
let dst_w = nw.max(tw).min(8192);
|
||||
let cw = dst_w;
|
||||
let ch = ((cw as u64 * th as u64) / tw as u64).clamp(1, 8192) as u32;
|
||||
let dst_h = ((dst_w as u64 * nh as u64) / nw as u64).clamp(1, ch as u64) as u32;
|
||||
(cw, ch, dst_w, dst_h)
|
||||
} else {
|
||||
let dst_h = nh.max(th).min(8192);
|
||||
let ch = dst_h;
|
||||
let cw = ((ch as u64 * tw as u64) / th as u64).clamp(1, 8192) as u32;
|
||||
let dst_w = ((dst_h as u64 * nw as u64) / nh as u64).clamp(1, cw as u64) as u32;
|
||||
(cw, ch, dst_w, dst_h)
|
||||
};
|
||||
if !has_transparency && cw == nw && ch == nh && dst_w == nw && dst_h == nh {
|
||||
return Ok(bytes);
|
||||
}
|
||||
let mut canvas = vec![255u8; (cw as usize) * (ch as usize) * 4];
|
||||
let ox = (cw - dst_w) / 2;
|
||||
let oy = (ch - dst_h) / 2;
|
||||
let sample_over_white = |x: u32, y: u32| -> [f32; 3] {
|
||||
let idx = ((y * nw + x) * 4) as usize;
|
||||
let a = rgba[idx + 3] as f32 / 255.0;
|
||||
let inv = 1.0 - a;
|
||||
[
|
||||
rgba[idx] as f32 * a + 255.0 * inv,
|
||||
rgba[idx + 1] as f32 * a + 255.0 * inv,
|
||||
rgba[idx + 2] as f32 * a + 255.0 * inv,
|
||||
]
|
||||
};
|
||||
for dy in 0..dst_h {
|
||||
let sy_f = ((dy as f32 + 0.5) * (nh as f32) / (dst_h as f32) - 0.5).clamp(0.0, (nh - 1) as f32);
|
||||
let y0 = sy_f.floor() as u32;
|
||||
let y1 = (y0 + 1).min(nh - 1);
|
||||
let fy = sy_f - y0 as f32;
|
||||
for dx in 0..dst_w {
|
||||
let sx_f = ((dx as f32 + 0.5) * (nw as f32) / (dst_w as f32) - 0.5).clamp(0.0, (nw - 1) as f32);
|
||||
let x0 = sx_f.floor() as u32;
|
||||
let x1 = (x0 + 1).min(nw - 1);
|
||||
let fx = sx_f - x0 as f32;
|
||||
let w00 = (1.0 - fx) * (1.0 - fy);
|
||||
let w10 = fx * (1.0 - fy);
|
||||
let w01 = (1.0 - fx) * fy;
|
||||
let w11 = fx * fy;
|
||||
let c00 = sample_over_white(x0, y0);
|
||||
let c10 = sample_over_white(x1, y0);
|
||||
let c01 = sample_over_white(x0, y1);
|
||||
let c11 = sample_over_white(x1, y1);
|
||||
let di = (((oy + dy) * cw + (ox + dx)) * 4) as usize;
|
||||
for ch_idx in 0..3 {
|
||||
let val = c00[ch_idx] * w00 + c10[ch_idx] * w10 + c01[ch_idx] * w01 + c11[ch_idx] * w11;
|
||||
canvas[di + ch_idx] = val.round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
canvas[di + 3] = 255;
|
||||
}
|
||||
}
|
||||
let composited = photocraft_codecs::Image::from_u8(cw, ch, photocraft_codecs::ChannelLayout::Rgba, canvas)
|
||||
.map_err(|_| "白底合成失败,请稍后重试".to_string())?;
|
||||
photocraft_codecs::encode(&composited, photocraft_codecs::Format::Png, &Default::default())
|
||||
.map_err(|_| "白底合成编码失败,请稍后重试".to_string())
|
||||
}
|
||||
|
||||
/// Prepare the same slot replacement for a read-only preview and a committed adoption.
|
||||
pub fn prepare_adoption_document(
|
||||
doc: &Document, meta: &Value, bytes: Vec<u8>, ticket: &photocraft_engine::smart_cmds::SourceTicket,
|
||||
retain_before: bool,
|
||||
) -> Result<PreparedAdoption, String> {
|
||||
let batch = meta["detailBatch"] == true;
|
||||
let layer = meta["nativeLayerId"].as_u64().ok_or("图位图层身份缺失")?;
|
||||
let slot = meta["slotId"].as_str().ok_or("图位身份缺失")?;
|
||||
let candidate = meta["candidateId"].as_str().ok_or("候选身份缺失")?;
|
||||
let variant = meta["variantId"].as_str().ok_or("花色身份缺失")?;
|
||||
let target = doc.layer(photocraft_doc::LayerId(layer)).ok_or("原图位不存在")?;
|
||||
let require_opaque = super::production_facts::slot_requires_opaque(meta)
|
||||
|| document_mapping(doc).is_some_and(|mapping| {
|
||||
mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.any(|field| {
|
||||
(field["nativeLayerId"].as_u64() == Some(layer) || field["slotId"].as_str() == Some(slot))
|
||||
&& super::production_facts::slot_requires_opaque(field)
|
||||
})
|
||||
});
|
||||
let key = format!("jiansun.adopted.{variant}.{slot}");
|
||||
let same_adopted_key = doc.metadata.text.iter().any(|(k, value)| *k == key && value == candidate);
|
||||
let same_raw_bytes = matches!(&target.content, LayerContent::Smart(smart)
|
||||
if matches!(&smart.source, photocraft_doc::SmartSource::Embedded { bytes: current, .. }
|
||||
if current.as_slice() == bytes.as_slice()));
|
||||
if same_adopted_key && (same_raw_bytes || require_opaque)
|
||||
&& meta["fitRequested"] != true && visible_retouch_layers(doc, layer).next().is_some()
|
||||
&& matches!(&target.content, LayerContent::Smart(smart)
|
||||
if matches!(&smart.source, photocraft_doc::SmartSource::Embedded { .. }))
|
||||
{
|
||||
// Reapplying the same source must preserve the placement sampled by the repair.
|
||||
return Ok(PreparedAdoption {
|
||||
document: doc.clone(),
|
||||
before: retain_before.then(|| std::sync::Arc::new(doc.clone())),
|
||||
source_digest: None,
|
||||
});
|
||||
}
|
||||
let bytes = if require_opaque {
|
||||
let target_frame = meta["frame"]["width"].as_f64().zip(meta["frame"]["height"].as_f64())
|
||||
.and_then(|(w, h)| (w > 0.0 && h > 0.0).then_some((w.round() as u32, h.round() as u32)));
|
||||
apply_opaque_white_background(bytes, meta["fit"] == "contain", target_frame)?
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
if meta["embeddedTarget"].is_object() {
|
||||
let mut updated = doc.clone();
|
||||
let embedded = &meta["embeddedTarget"];
|
||||
let before_snapshot = retain_before.then(|| std::sync::Arc::new(doc.clone()));
|
||||
let candidate_source = photocraft_engine::smart_cmds::prepare_bounded_source("candidate.png", std::sync::Arc::new(bytes))
|
||||
.map_err(|error| error.to_string())?;
|
||||
let inner_first_placement = !doc.metadata.text.iter().any(|(k, _)| *k == key);
|
||||
super::production_facts::with_embedded_target(&mut updated, embedded, |child, inner_id| {
|
||||
if child.effective_locks(inner_id).any() {
|
||||
return Err("当前图层或其父组已锁定".into());
|
||||
}
|
||||
let inner_layer = child.layer(inner_id).ok_or("嵌入原图位不存在")?;
|
||||
let LayerContent::Smart(inner_smart) = &inner_layer.content else {
|
||||
return Err("嵌入目标图层不是可替换智能对象".into());
|
||||
};
|
||||
let inner_original = match &inner_smart.source {
|
||||
photocraft_doc::SmartSource::Embedded { file_name, bytes } => {
|
||||
Some(photocraft_engine::smart_cmds::prepare_bounded_source(file_name, bytes.clone()).map_err(|e| e.to_string())?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut prepared = photocraft_engine::Session::new();
|
||||
prepared.add_document(child.clone(), None);
|
||||
let replace = if batch {
|
||||
photocraft_engine::smart_cmds::replace_template_instance_bounded_fit
|
||||
} else {
|
||||
photocraft_engine::smart_cmds::replace_instance_bounded_fit
|
||||
};
|
||||
replace(&mut prepared, inner_id, inner_original.as_ref(), &candidate_source, meta["fit"] == "contain")
|
||||
.map_err(|error| error.to_string())?;
|
||||
*child = prepared.active().ok_or("嵌入候选无法准备")?.doc.as_ref().clone();
|
||||
if inner_first_placement
|
||||
&& let Some(target_mut) = child.layer_mut(inner_id)
|
||||
&& !target_mut.visible
|
||||
{
|
||||
target_mut.visible = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let manual = format!("jiansun.manual-image.{variant}.{slot}");
|
||||
updated.metadata.text.retain(|(k, _)| *k != key && *k != manual);
|
||||
updated.metadata.text.push((key, candidate.into()));
|
||||
return Ok(PreparedAdoption { document: updated, before: before_snapshot, source_digest: None });
|
||||
}
|
||||
let embedded_frame = embedded_replacement_frame(doc, target);
|
||||
// A registered mask defines placement for an embedded template.
|
||||
// The source ticket still binds the object, even when its old bytes are unnecessary.
|
||||
let source = (!embedded_frame).then(|| ticket.read())
|
||||
.transpose().map_err(|error|error.to_string())?;
|
||||
let original = source.as_ref()
|
||||
.map(|source| photocraft_engine::smart_cmds::prepare_bounded_source(&source.file_name,source.bytes.clone()))
|
||||
.transpose().map_err(|error|error.to_string())?;
|
||||
let candidate_source = photocraft_engine::smart_cmds::prepare_bounded_source("candidate.png", std::sync::Arc::new(bytes)).map_err(|error| error.to_string())?;
|
||||
let mut before = doc.clone();
|
||||
if let Some(source) = &source {
|
||||
let mut target = before.layer(photocraft_doc::LayerId(layer)).cloned().ok_or("原图位不存在")?;
|
||||
let LayerContent::Smart(smart) = &mut target.content else { return Err("目标不是智能图层".into()) };
|
||||
smart.source = photocraft_doc::SmartSource::Embedded {file_name:source.file_name.clone(),bytes:source.bytes.clone()};
|
||||
if let Some(original)=original.as_ref() {
|
||||
photocraft_engine::smart_cmds::refresh_layer_with_bounded_source(&before, &mut target, original).map_err(|error|error.to_string())?;
|
||||
}
|
||||
*before.layer_mut(photocraft_doc::LayerId(layer)).ok_or("原图位不存在")? = target;
|
||||
}
|
||||
let before_snapshot = retain_before.then(|| std::sync::Arc::new(before.clone()));
|
||||
let mut prepared = photocraft_engine::Session::new();
|
||||
prepared.add_document(before, None);
|
||||
let replace = if batch {
|
||||
photocraft_engine::smart_cmds::replace_template_instance_bounded_fit
|
||||
} else {
|
||||
photocraft_engine::smart_cmds::replace_instance_bounded_fit
|
||||
};
|
||||
replace(&mut prepared, photocraft_doc::LayerId(layer), original.as_ref(), &candidate_source, meta["fit"] == "contain")
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut updated = prepared.active().ok_or("候选无法准备")?.doc.as_ref().clone();
|
||||
let first_placement = !updated.metadata.text.iter().any(|(k, _)| *k == key);
|
||||
if !first_placement {
|
||||
for id in visible_retouch_layers(doc, layer) {
|
||||
if let Some(repair) = updated.layer_mut(id) {
|
||||
repair.visible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if first_placement && document_mapping(&updated).is_some_and(|mapping|
|
||||
mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.any(|field| field["nativeLayerId"].as_u64() == Some(layer)
|
||||
&& field["kind"] == "image" && field["hiddenTemplateSample"] == true))
|
||||
{
|
||||
updated.layer_mut(photocraft_doc::LayerId(layer)).ok_or("待回填图位不存在")?.visible = true;
|
||||
}
|
||||
let manual = format!("jiansun.manual-image.{variant}.{slot}");
|
||||
updated.metadata.text.retain(|(k, _)| *k != key && *k != manual);
|
||||
updated.metadata.text.push((key, candidate.into()));
|
||||
Ok(PreparedAdoption { document:updated, before:before_snapshot, source_digest:source.map(|source| source.digest) })
|
||||
}
|
||||
|
||||
pub(crate) fn detail_write_waiting(w: &Workspace, app: &PhotocraftApp) -> bool {
|
||||
if w.product_target_hidden { return w.saving.is_some(); }
|
||||
app.ui.text_edit.is_some() || app.saving() || adoption_write_mode(w, app).is_none()
|
||||
}
|
||||
|
||||
// A prepared detail adoption stays valid while the target layer is untouched. Product brief edits
|
||||
// do not expire it here: the agent already receives them as a product update and decides whether
|
||||
// the candidate still fits.
|
||||
pub(crate) fn valid_detail_adoption(w: &Workspace, doc: &Document, meta: &Value) -> bool {
|
||||
let Some(layer) = meta["nativeLayerId"].as_u64().map(photocraft_doc::LayerId) else { return false; };
|
||||
let checked_container = meta["embeddedTarget"].is_object()
|
||||
&& w.canvas_workspace.adoption_worker.as_ref().is_some_and(|worker| {
|
||||
worker.meta["slotId"] == meta["slotId"] && worker.manual_basis.as_ref()
|
||||
.is_some_and(|before| std::ptr::eq(before.as_ref(), doc))
|
||||
});
|
||||
super::pi_bridge::production_workspace_active(w) && w.pi_run.is_some()
|
||||
&& !w.pi_write_blocked && !w.agent_effects_paused
|
||||
&& document_mapping(doc).is_some_and(|mapping|
|
||||
mapping["component"] == meta["outputId"] && mapping["variantId"] == meta["variantId"]
|
||||
&& meta["workspaceId"].as_str().or_else(|| w.pi_request_scope["project"]["workspaceId"].as_str())
|
||||
.is_none_or(|workspace| mapping["workspaceId"] == workspace))
|
||||
&& doc.layer(layer).is_some()
|
||||
&& (checked_container || adoption_rejection(w, doc, layer, meta).is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn manual_target_unchanged(before: &Document, current: &Document, meta: &Value) -> bool {
|
||||
let (Some(layer), Some(variant), Some(slot)) = (
|
||||
meta["nativeLayerId"].as_u64().map(photocraft_doc::LayerId),
|
||||
meta["variantId"].as_str(),
|
||||
meta["slotId"].as_str(),
|
||||
) else { return false; };
|
||||
before.id == current.id
|
||||
&& super::same_canvas_target(&super::product_document_key(before), &super::product_document_key(current))
|
||||
&& (if let Some(embedded) = meta.get("embeddedTarget").filter(|value| value.is_object()) {
|
||||
let inner = |doc: &Document| super::production_facts::read_embedded_layer(doc, embedded, |child, id| {
|
||||
Ok((child.layer(id).cloned(), child.effective_locks(id)))
|
||||
});
|
||||
let same_container = before.layer(layer).zip(current.layer(layer)).is_some_and(|(old, new)| old == new);
|
||||
same_container || inner(before).is_ok_and(|old| inner(current).is_ok_and(|new| old == new))
|
||||
} else {
|
||||
before.layer(layer).zip(current.layer(layer)).is_some_and(|(old, new)| old == new)
|
||||
})
|
||||
&& before.effective_locks(layer) == current.effective_locks(layer)
|
||||
&& adopted(before, slot, variant) == adopted(current, slot, variant)
|
||||
&& manual_image(before, slot, variant) == manual_image(current, slot, variant)
|
||||
}
|
||||
|
||||
pub(crate) fn user_adopted(doc: &Document, slot: &str, variant: &str) -> bool {
|
||||
let key = format!("jiansun.user-adopted.{variant}.{slot}");
|
||||
adopted(doc, slot, variant).is_some_and(|candidate|
|
||||
doc.metadata.text.iter().any(|(name, value)| *name == key && value == candidate))
|
||||
}
|
||||
|
||||
pub(crate) fn user_adoption_matches(doc: &Document, adoption: &Value) -> bool {
|
||||
adoption["slotId"].as_str().zip(adoption["variantId"].as_str()).is_some_and(|(slot, variant)|
|
||||
user_adopted(doc, slot, variant) && adopted(doc, slot, variant) == adoption["adoptedCandidateId"].as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn protected_user_image(doc: &Document, meta: &Value) -> bool {
|
||||
meta["slotId"].as_str().zip(meta["variantId"].as_str()).is_some_and(|(slot, variant)|
|
||||
user_adopted(doc, slot, variant) || manual_image(doc, slot, variant).is_some())
|
||||
}
|
||||
|
||||
pub(crate) fn adoption_rejection(w: &Workspace, doc: &Document, layer: photocraft_doc::LayerId, meta: &Value)
|
||||
-> Option<super::product_production::LayerRejection>
|
||||
{
|
||||
use super::product_production::LayerRejection;
|
||||
let Some(embedded) = meta.get("embeddedTarget").filter(|value| value.is_object()) else {
|
||||
return w.production_layer_rejection(doc, layer);
|
||||
};
|
||||
if doc.effective_locks(layer).any() {
|
||||
return Some(LayerRejection::UserLock);
|
||||
}
|
||||
if protected_user_image(doc, meta) {
|
||||
return Some(LayerRejection::UserEdit);
|
||||
}
|
||||
super::production_facts::read_embedded_layer(doc, embedded, |child, inner_id| {
|
||||
if child.effective_locks(inner_id).any() {
|
||||
return Ok(Some(LayerRejection::UserLock));
|
||||
}
|
||||
let text_key = format!("jiansun.manual-text.{}", layer.0);
|
||||
let edited = doc.metadata.text.iter().any(|(key, value)| key == &text_key
|
||||
&& serde_json::from_str::<Value>(value).is_ok_and(|mark| mark["embedded"] == true
|
||||
&& mark["source"] == "human" && mark["innerLayerIds"].as_array().is_some_and(|ids| {
|
||||
ids.iter().any(|id| id.as_u64() == Some(inner_id.0))
|
||||
})));
|
||||
Ok(if edited { Some(LayerRejection::UserEdit) } else { w.production_layer_rejection(child, inner_id) })
|
||||
}).ok().flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn adoption_block_reason(w: &Workspace, app: &PhotocraftApp, meta: &mut Value) -> Option<String> {
|
||||
if meta["detailBatch"] != true {
|
||||
return (meta["workflowRun"].is_string() && protected_user_image(&app.session.active()?.doc, meta))
|
||||
.then(|| "目标图位已由你编辑或确认,原图和候选均已保留。".into());
|
||||
}
|
||||
let state = app.session.active()?;
|
||||
let layer = meta["nativeLayerId"].as_u64().map(photocraft_doc::LayerId)?;
|
||||
let reason = adoption_rejection(w, &state.doc, layer, meta)?;
|
||||
meta["writeBlockReason"] = json!(reason.code());
|
||||
Some(format!("{},候选已保留", reason.message()))
|
||||
}
|
||||
|
||||
pub(crate) fn adoption_write_mode(w: &Workspace, app: &PhotocraftApp) -> Option<Value> {
|
||||
let state = app.session.active()?;
|
||||
if app.layer_mask_targeted() || app.ui.mask_target || app.ui.vector_mask_target || app.ui.transform.is_some()
|
||||
|| state.floating.is_some() || w.professional_mode || w.saving.is_some() || w.pending_project_open.is_some()
|
||||
|| w.pending_slot_apply.is_some() { return None; }
|
||||
Some(json!({"channel":format!("{:?}", state.channel_view), "piBlocked":w.pi_write_blocked,
|
||||
"unknown":w.unknown, "paused":w.agent_effects_paused}))
|
||||
}
|
||||
|
||||
pub fn update_structure_guides(doc: &mut Document, image: photocraft_doc::LayerId, meta: &Value) -> Result<(), photocraft_engine::EngineError> {
|
||||
use photocraft_doc::{Color, Fill, Layer, LayerContent, LayerId, LineCap, LineJoin, Path, ShapeLayer, ShapeStroke, Subpath};
|
||||
use photocraft_engine::EngineError;
|
||||
|
||||
let key = format!("jiansun.structure-guides.{}.{}", meta["variantId"].as_str().unwrap_or(""), meta["slotId"].as_str().unwrap_or(""));
|
||||
let name = "实物标注";
|
||||
let mut layers = Vec::new();
|
||||
if let Some(guides) = meta["structureGuides"].as_array() {
|
||||
let mapping = document_mapping(doc).ok_or_else(|| EngineError::Other("实物标注缺少原生图框".into()))?;
|
||||
let [x, y, right, bottom]: [f64; 4] = mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.find(|field| field["kind"] == "image" && field["nativeLayerId"].as_u64() == Some(image.0))
|
||||
.and_then(|field| serde_json::from_value(field["nativeFrame"].clone()).ok())
|
||||
.ok_or_else(|| EngineError::Other("实物标注缺少原生图框".into()))?;
|
||||
let (w, h) = (right - x, bottom - y);
|
||||
if w <= 0.0 || h <= 0.0 { return Err(EngineError::Other("实物标注的原生图框无效".into())); }
|
||||
let width = (w.min(h) / 280.0).clamp(1.5, 5.0);
|
||||
for guide in guides {
|
||||
let points: Vec<[u16; 2]> = serde_json::from_value(guide["points"].clone())
|
||||
.map_err(|_| EngineError::Other("结构虚线坐标无效".into()))?;
|
||||
let points = points.into_iter().map(|[left, top]| {
|
||||
(x + w * f64::from(left) / 1000.0, y + h * f64::from(top) / 1000.0)
|
||||
}).collect::<Vec<_>>();
|
||||
let kind = guide["kind"].as_str().unwrap_or("outline");
|
||||
let outline = kind == "outline";
|
||||
let color = if outline { Color::WHITE } else { Color::BLACK };
|
||||
let stroke = guide["styleLayerId"].as_u64().and_then(|source| {
|
||||
doc.walk().into_iter().find_map(|(_, _, layer)| {
|
||||
if layer.psd_id.map(u64::from) != Some(source) { return None; }
|
||||
if let LayerContent::Shape(shape) = &layer.content { return shape.stroke.clone(); }
|
||||
None
|
||||
})
|
||||
}).unwrap_or_else(|| ShapeStroke {
|
||||
width:width as f32, paint:Fill::Solid(color), cap:LineCap::Round, join:LineJoin::Round,
|
||||
dashes:if outline { vec![2.5, 2.0] } else { vec![] }, ..Default::default()
|
||||
});
|
||||
let mut paths = vec![Subpath::polyline(&points)];
|
||||
let diameter = f64::from(stroke.width) * 3.5;
|
||||
let ends = if kind == "leader" { &points[..1] } else if kind == "measurement" { &points[..] } else { &[] };
|
||||
for &(x, y) in ends {
|
||||
paths.extend(photocraft_vector::shapes::ellipse(x-diameter/2.0, y-diameter/2.0, diameter, diameter).subpaths);
|
||||
}
|
||||
let mut layer = ShapeLayer { path:Path::new(paths), stroke:Some(stroke), ..Default::default() };
|
||||
layer.cache = Some(photocraft_vector::render_shape(&layer, doc.pixel_format(), doc.bounds()));
|
||||
let label = guide["label"].as_str().unwrap_or(name);
|
||||
layers.push(Layer::new(label, LayerContent::Shape(layer)));
|
||||
if kind == "measurement" {
|
||||
use photocraft_doc::text::{ParagraphRun, ParagraphStyle, TextAlign};
|
||||
use photocraft_doc::{Affine, TextLayer};
|
||||
let [(ax, ay), (bx, by)] = points.as_slice() else { return Err(EngineError::Other("测量示意缺少端点".into())); };
|
||||
let size = (w.min(h) / 42.0).clamp(10.0, 30.0);
|
||||
let vertical = (ay-by).abs() > (ax-bx).abs()*2.0;
|
||||
let (x, y) = ((ax+bx)/2.0 + if vertical { size } else { 0.0 },
|
||||
(ay+by)/2.0 - if vertical { 0.0 } else { width * 2.0 });
|
||||
let mut caption = TextLayer { text:label.to_owned(), size_pt:(size * 72.0 / f64::from(doc.resolution_dpi)) as f32,
|
||||
color, transform:Affine::translate(x,y), paragraphs:vec![ParagraphRun { len:label.len(),
|
||||
style:ParagraphStyle { align:TextAlign::Center,..Default::default() } }], ..Default::default() };
|
||||
photocraft_engine::type_cmds::refresh(doc, &mut caption);
|
||||
layers.push(Layer::new(label, LayerContent::Text(caption)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(id) = doc.metadata.text.iter().find(|(field, _)| field == &key).and_then(|(_, id)| id.parse::<u64>().ok()).map(LayerId)
|
||||
&& doc.layer(id).is_some_and(|layer| matches!(layer.name.as_str(), "实物标注" | "结构虚线") && matches!(layer.content, LayerContent::Group(_)))
|
||||
{
|
||||
doc.remove(id);
|
||||
}
|
||||
doc.metadata.text.retain(|(field, _)| field != &key);
|
||||
if !layers.is_empty() {
|
||||
let mut anchor = image;
|
||||
if let Some(mut path) = doc.path_of(image) {
|
||||
let index = path.len() - 1;
|
||||
path[index] += 1;
|
||||
while let Some(layer) = doc.layer_at(&path).filter(|layer| layer.clipped) {
|
||||
anchor = layer.id;
|
||||
path[index] += 1;
|
||||
}
|
||||
}
|
||||
let id = doc.insert_above(Some(anchor), Layer::group(name, layers));
|
||||
doc.metadata.text.push((key, id.0.to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn canvas_adopt(&mut self, app: &mut PhotocraftApp, bytes: Vec<u8>, mut meta: Value) -> Option<(Value, bool)> {
|
||||
use std::sync::atomic::Ordering;
|
||||
self.record_manual_layers_from_observer(app);
|
||||
let pending = self.canvas_workspace.pending_adoption.clone()?;
|
||||
let batch = meta["detailBatch"] == true;
|
||||
let manual = meta["manualAdoption"] == true;
|
||||
let candidate = meta.get("sourceCandidateId").unwrap_or(&meta["candidateId"]);
|
||||
let write_mode = adoption_write_mode(self, app);
|
||||
if pending["workflowOperationId"] != meta["workflowOperationId"] || pending["workflowRun"] != meta["workflowRun"] {
|
||||
return Some((meta, false));
|
||||
}
|
||||
let manual_basis = manual.then(|| self.canvas_workspace.manual_adoption_basis.clone()).flatten();
|
||||
let valid = pending["manualAdoption"] == meta["manualAdoption"]
|
||||
&& (!meta["workflowOperationId"].is_string() || meta["workflowRun"].as_str() == self.pi_run.as_deref())
|
||||
&& (batch || write_mode.is_some()) && self.enforce_canvas_scope(app) && app.session.active().is_some_and(|state| {
|
||||
meta["accountId"] == self.account["id"] && meta["origin"] == self.origin
|
||||
&& meta["doc"].as_u64() == Some(state.doc.id.0)
|
||||
&& (if manual { manual_basis.as_ref().is_some_and(|before| manual_target_unchanged(before, &state.doc, &meta)) }
|
||||
else if batch { valid_detail_adoption(self, &state.doc, &meta) }
|
||||
else { meta["baseRevision"].as_u64() == Some(state.revision)
|
||||
&& (!meta["workflowRun"].is_string() || !protected_user_image(&state.doc, &meta)) })
|
||||
&& pending["slotId"] == meta["slotId"] && pending["candidateId"] == *candidate && pending["variantId"] == meta["variantId"]
|
||||
&& (pending["historicalCandidate"] == true) == meta["sourceCandidateId"].is_string()
|
||||
&& pending["previewExport"] == meta["previewExport"]
|
||||
&& meta["nativeLayerId"].as_u64().is_some_and(|layer| meta["slotId"].as_str().and_then(|slot| native_layer(&state.doc, slot)) == Some(layer))
|
||||
});
|
||||
if !valid {
|
||||
if pending["slotId"] == meta["slotId"] && pending["candidateId"] == *candidate && pending["variantId"] == meta["variantId"] {
|
||||
self.canvas_workspace.pending_adoption = None;
|
||||
self.canvas_workspace.manual_adoption_basis = None;
|
||||
}
|
||||
self.error = adoption_block_reason(self, app, &mut meta)
|
||||
.unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into());
|
||||
return Some((meta, false));
|
||||
}
|
||||
if self.canvas_workspace.adoption_worker.is_some() { return None; }
|
||||
if manual { self.canvas_workspace.manual_adoption_basis = None; }
|
||||
if ADOPTION_WORKER_BUSY.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
self.canvas_workspace.pending_adoption = None;
|
||||
self.error = "上一张图片仍在准备,请稍后再试".into();
|
||||
return Some((meta, false));
|
||||
}
|
||||
let Some(state) = app.session.active() else { ADOPTION_WORKER_BUSY.store(false, Ordering::Release); return Some((meta, false)); };
|
||||
let Some(layer_id) = meta["nativeLayerId"].as_u64() else { ADOPTION_WORKER_BUSY.store(false, Ordering::Release); return Some((meta, false)); };
|
||||
let Some(LayerContent::Smart(smart)) = state.doc.layer(photocraft_doc::LayerId(layer_id)).map(|layer| &layer.content) else {
|
||||
ADOPTION_WORKER_BUSY.store(false, Ordering::Release); self.error = "目标不是智能图层".into(); return Some((meta, false));
|
||||
};
|
||||
let source_ticket = match photocraft_engine::smart_cmds::freeze_source(&app.session, state.doc.id, state.revision, photocraft_doc::LayerId(layer_id), smart.contents_id) {
|
||||
Ok(ticket) => ticket,
|
||||
Err(error) => { ADOPTION_WORKER_BUSY.store(false, Ordering::Release); self.error = error.to_string(); return Some((meta, false)); }
|
||||
};
|
||||
let worker_ticket = source_ticket.clone();
|
||||
let doc = state.doc.clone();
|
||||
let active_layer = state.active_layer;
|
||||
let selected_layers = state.selected_layers();
|
||||
let project = bound_project(self, state.doc.id.0).map(str::to_owned);
|
||||
let animate_original = !batch && !manual && !self.reduce_motion && matches!(&smart.source, photocraft_doc::SmartSource::Linked { .. });
|
||||
let recheck_source = matches!(&smart.source, photocraft_doc::SmartSource::Linked { .. });
|
||||
let manual_basis = if batch && meta["embeddedTarget"].is_object() { Some(doc.clone()) } else { manual_basis };
|
||||
let worker_meta = meta.clone();
|
||||
let (sender, result) = std::sync::mpsc::sync_channel(1);
|
||||
let (approve_recheck, approval) = std::sync::mpsc::sync_channel(1);
|
||||
let spawned = std::thread::Builder::new().name("agent-adoption-prepare".into()).spawn(move || {
|
||||
let prepared = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<(Document, Option<AdoptionSnapshot>), String> {
|
||||
let PreparedAdoption { document:updated, before, source_digest } = prepare_adoption_document(
|
||||
&doc, &worker_meta, bytes, &worker_ticket, animate_original || recheck_source && (batch || manual))?;
|
||||
let snapshot = before.filter(|_| source_digest.is_some()
|
||||
|| animate_original && doc.layer(photocraft_doc::LayerId(layer_id))
|
||||
.is_some_and(|target| matches!(&target.content, LayerContent::Smart(smart) if smart.cache.is_some())))
|
||||
.map(|before_doc| AdoptionSnapshot { before_doc, source_digest });
|
||||
if let Some(digest) = source_digest.filter(|_| recheck_source) {
|
||||
sender.send(AdoptionProgress::Prepared).map_err(|_| "采纳准备已取消")?;
|
||||
if !approval.recv_timeout(std::time::Duration::from_secs(30)).unwrap_or(false) { return Err("采纳准备已取消".into()); }
|
||||
let again = worker_ticket.read().map_err(|error|error.to_string())?;
|
||||
if again.digest != digest { return Err("原智能对象源文件已变化,未采纳".into()); }
|
||||
}
|
||||
Ok((updated, snapshot))
|
||||
})).unwrap_or_else(|_| Err("图片准备失败,原画布已保留".into()));
|
||||
ADOPTION_WORKER_BUSY.store(false, Ordering::Release);
|
||||
let _ = sender.send(AdoptionProgress::Done(prepared.map(Box::new)));
|
||||
});
|
||||
if spawned.is_err() {
|
||||
ADOPTION_WORKER_BUSY.store(false, Ordering::Release);
|
||||
self.error = "图片准备服务无法启动,原画布已保留".into();
|
||||
return Some((meta, false));
|
||||
}
|
||||
self.canvas_workspace.adoption_worker = Some(AdoptionWorker { meta, pending, project, write_mode: write_mode.unwrap_or(Value::Null), active_layer, selected_layers, source_ticket, manual_basis, approve_recheck, prepared:None, prewarm_id:None, prewarm_ready:false, post_source_check:None, result });
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn adoption_worker_valid(&self, app: &PhotocraftApp, worker: &AdoptionWorker) -> bool {
|
||||
let batch = worker.meta["detailBatch"] == true;
|
||||
let manual = worker.meta["manualAdoption"] == true;
|
||||
let embedded = worker.meta["embeddedTarget"].is_object();
|
||||
let source_ok = if embedded {
|
||||
worker.source_ticket.validate_container(&app.session)
|
||||
} else if batch || manual {
|
||||
worker.source_ticket.validate_source(&app.session)
|
||||
} else {
|
||||
worker.source_ticket.validate(&app.session)
|
||||
};
|
||||
source_ok.is_ok()
|
||||
&& self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending)
|
||||
&& (!worker.meta["workflowOperationId"].is_string() || worker.meta["workflowRun"].as_str() == self.pi_run.as_deref())
|
||||
&& (batch || if manual { adoption_write_mode(self, app).is_some() } else { adoption_write_mode(self, app).as_ref() == Some(&worker.write_mode) })
|
||||
&& self.canvas_scope_valid(app)
|
||||
&& worker.meta["accountId"] == self.account["id"] && worker.meta["origin"] == self.origin
|
||||
&& app.session.active().is_some_and(|state| worker.meta["doc"].as_u64() == Some(state.doc.id.0)
|
||||
&& (if manual { worker.manual_basis.as_ref().is_some_and(|before| manual_target_unchanged(before, &state.doc, &worker.meta)) }
|
||||
else if batch { valid_detail_adoption(self, &state.doc, &worker.meta)
|
||||
&& (!embedded || worker.manual_basis.as_ref().is_some_and(|before| manual_target_unchanged(before, &state.doc, &worker.meta))) }
|
||||
else { worker.meta["baseRevision"].as_u64() == Some(state.revision)
|
||||
&& (!worker.meta["workflowRun"].is_string() || !protected_user_image(&state.doc, &worker.meta)) })
|
||||
&& bound_project(self, state.doc.id.0).map(str::to_owned) == worker.project
|
||||
&& worker.meta["nativeLayerId"].as_u64().is_some_and(|layer| worker.meta["slotId"].as_str()
|
||||
.and_then(|slot| native_layer(&state.doc, slot)) == Some(layer)))
|
||||
}
|
||||
|
||||
pub(crate) fn poll_canvas_adoption(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, painting: bool) -> Option<(Value, bool)> {
|
||||
self.canvas_workspace.adoption_worker.as_ref()?;
|
||||
self.record_manual_layers_from_observer(app);
|
||||
let worker = self.canvas_workspace.adoption_worker.as_ref()?;
|
||||
if self.sensitive_ui_open() && (worker.meta["detailBatch"] == true || worker.meta["workflowRun"].is_string()) {
|
||||
return None;
|
||||
}
|
||||
if worker.meta["detailBatch"] == true && !self.pi_write_blocked && !self.agent_effects_paused && detail_write_waiting(self, app) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
return None;
|
||||
}
|
||||
if !self.adoption_worker_valid(app, worker) {
|
||||
let source_error = worker.source_ticket.validate(&app.session).err().map(|error| error.to_string());
|
||||
let worker = self.canvas_workspace.adoption_worker.take()?;
|
||||
let _ = worker.approve_recheck.try_send(false);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(id) = worker.prewarm_id { crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id); }
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
let mut meta = worker.meta;
|
||||
self.error = adoption_block_reason(self, app, &mut meta).or(source_error)
|
||||
.unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into());
|
||||
return Some((meta, false));
|
||||
}
|
||||
let prewarm_id = worker.prewarm_id;
|
||||
let prepared = if let Some(id) = prewarm_id {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if !painting && !worker.prewarm_ready {
|
||||
// The crossfade has no consumer in a logic-only pass. Keep the
|
||||
// prepared write and its final linked-source check.
|
||||
crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id);
|
||||
let worker = self.canvas_workspace.adoption_worker.as_mut()?;
|
||||
worker.prewarm_ready = true;
|
||||
} else if !worker.prewarm_ready {
|
||||
match crate::canvas::poll_agent_adoption_prewarm(app, ctx, id) {
|
||||
crate::canvas::AgentAdoptionPrepare::Pending => return None,
|
||||
crate::canvas::AgentAdoptionPrepare::Failed => {
|
||||
let worker = self.canvas_workspace.adoption_worker.take()?;
|
||||
crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id);
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
self.error = "画布对比准备失败,原图已保留".into();
|
||||
return Some((worker.meta, false));
|
||||
}
|
||||
crate::canvas::AgentAdoptionPrepare::Ready => {
|
||||
self.canvas_workspace.adoption_worker.as_mut()?.prewarm_ready = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let worker = self.canvas_workspace.adoption_worker.as_ref()?;
|
||||
let source_digest = worker.prepared.as_ref().and_then(|(_, snapshot)| snapshot.as_ref()).and_then(|snapshot| snapshot.source_digest);
|
||||
if source_digest.is_some() && worker.post_source_check.is_none() {
|
||||
use std::sync::atomic::Ordering;
|
||||
if ADOPTION_WORKER_BUSY.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(32));
|
||||
return None;
|
||||
}
|
||||
let ticket = worker.source_ticket.clone();
|
||||
let wake = ctx.clone();
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
let spawned = std::thread::Builder::new().name("agent-adoption-source-recheck".into()).spawn(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(||ticket.read().map(|source|source.digest).map_err(|error|error.to_string())))
|
||||
.unwrap_or_else(|_| Err("原图源校验失败".into()));
|
||||
ADOPTION_WORKER_BUSY.store(false, Ordering::Release);
|
||||
let _ = tx.send(result);
|
||||
wake.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
if spawned.is_err() {
|
||||
ADOPTION_WORKER_BUSY.store(false, Ordering::Release);
|
||||
let worker = self.canvas_workspace.adoption_worker.take()?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id);
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
self.error = "原图源校验服务无法启动,原图已保留".into();
|
||||
return Some((worker.meta, false));
|
||||
}
|
||||
self.canvas_workspace.adoption_worker.as_mut()?.post_source_check = Some(rx);
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(32));
|
||||
return None;
|
||||
}
|
||||
if let Some(expected) = source_digest {
|
||||
match worker.post_source_check.as_ref()?.try_recv() {
|
||||
Ok(Ok(digest)) if digest == expected => {}
|
||||
Ok(Ok(_)) | Ok(Err(_)) | Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
let worker = self.canvas_workspace.adoption_worker.take()?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id);
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
self.error = "原图源已变化或不可读取,原图已保留".into();
|
||||
return Some((worker.meta, false));
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => { ctx.request_repaint_after(std::time::Duration::from_millis(32)); return None; }
|
||||
}
|
||||
}
|
||||
self.canvas_workspace.adoption_worker.as_mut()?.prepared.take().map(Ok).unwrap_or_else(|| Err("画布准备结果缺失".into()))
|
||||
} else {
|
||||
match worker.result.try_recv() {
|
||||
Ok(AdoptionProgress::Prepared) => {
|
||||
let _ = worker.approve_recheck.send(true);
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(32));
|
||||
return None;
|
||||
}
|
||||
Ok(AdoptionProgress::Done(Ok(payload))) => {
|
||||
let (updated, snapshot) = *payload;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(old) = snapshot.as_ref().filter(|_| painting && worker.meta["detailBatch"] != true && worker.meta["manualAdoption"] != true) {
|
||||
let id = ADOPTION_PREWARM_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let mut lease = worker.meta.clone();
|
||||
lease["project"] = json!(worker.project);
|
||||
crate::canvas::begin_agent_adoption_prewarm(app, ctx, old.before_doc.clone(), std::sync::Arc::new(updated.clone()), lease, id);
|
||||
let worker = self.canvas_workspace.adoption_worker.as_mut()?;
|
||||
worker.prewarm_id = Some(id);
|
||||
worker.prepared = Some((updated, snapshot));
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(32));
|
||||
return None;
|
||||
}
|
||||
Ok((updated, snapshot))
|
||||
}
|
||||
Ok(AdoptionProgress::Done(Err(error))) => Err(error),
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => { ctx.request_repaint_after(std::time::Duration::from_millis(32)); return None; }
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("图片准备服务已停止,原画布已保留".into()),
|
||||
}
|
||||
};
|
||||
let worker = self.canvas_workspace.adoption_worker.take()?;
|
||||
let valid = self.adoption_worker_valid(app, &worker);
|
||||
let mut meta = worker.meta;
|
||||
let (updated, snapshot) = match prepared {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(id) = worker.prewarm_id { crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id); }
|
||||
self.error = error;
|
||||
return Some((meta, false));
|
||||
}
|
||||
};
|
||||
if !valid {
|
||||
if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; }
|
||||
self.error = adoption_block_reason(self, app, &mut meta)
|
||||
.unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into());
|
||||
return Some((meta, false));
|
||||
}
|
||||
self.canvas_workspace.pending_adoption = None;
|
||||
let Some(layer) = meta["nativeLayerId"].as_u64().map(photocraft_doc::LayerId) else { self.error = "图位图层身份缺失".into(); return Some((meta, false)); };
|
||||
let batch = meta["detailBatch"] == true;
|
||||
let manual = meta["manualAdoption"] == true;
|
||||
let before_revision = app.session.active().map(|state| state.revision);
|
||||
let checkpoint = before_revision.zip(worker.project.as_deref())
|
||||
.and_then(|(revision, project)| super::workflow_bridge::adoption_checkpoint(&meta, project, revision));
|
||||
let selection_unchanged = !batch && app.session.active().is_some_and(|state|
|
||||
state.active_layer == worker.active_layer && state.selected_layers() == worker.selected_layers);
|
||||
let marker = format!("jiansun.adopted.{}.{}", meta["variantId"].as_str().unwrap_or(""), meta["slotId"].as_str().unwrap_or(""));
|
||||
let candidate = meta["candidateId"].as_str().unwrap_or("").to_owned();
|
||||
let repairs = app.session.active().map(|state| {
|
||||
let doc = &state.doc;
|
||||
let changing_candidate = doc.metadata.text.iter().any(|(key, value)| key == &marker && value != &candidate);
|
||||
visible_retouch_layers(doc, layer.0)
|
||||
.filter(|id| changing_candidate || updated.layer(*id).is_some_and(|repair| !repair.visible))
|
||||
.collect::<Vec<_>>()
|
||||
}).unwrap_or_default();
|
||||
if !repairs.is_empty() {
|
||||
meta["hiddenRetouchLayers"] = json!(repairs.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
}
|
||||
let guide_meta = json!({"variantId":meta["variantId"],"slotId":meta["slotId"],"structureGuides":meta["structureGuides"]});
|
||||
let manual_marker = marker.replacen("jiansun.adopted.", "jiansun.manual-image.", 1);
|
||||
let user_marker = marker.replacen("jiansun.adopted.", "jiansun.user-adopted.", 1);
|
||||
self.record_manual_layers_from_observer(app);
|
||||
let embedded = meta.get("embeddedTarget").filter(|value| value.is_object()).cloned();
|
||||
if let Err(error) = app.session.edit("采纳图片", move |doc, selected| {
|
||||
if batch || manual {
|
||||
if let Some(embedded) = &embedded {
|
||||
let mut prepared_inner = super::production_facts::read_embedded_layer(&updated, embedded, |child, id| {
|
||||
child.layer(id).cloned().ok_or_else(|| "嵌入候选图层不存在".into())
|
||||
}).map_err(photocraft_engine::EngineError::Other)?;
|
||||
super::production_facts::with_embedded_target(doc, embedded, |child, id| {
|
||||
if child.effective_locks(id).any() { return Err("当前图层或其父组已锁定".into()); }
|
||||
let target = child.layer_mut(id).ok_or("嵌入原图位不存在")?;
|
||||
prepared_inner.id = id;
|
||||
*target = prepared_inner.clone();
|
||||
Ok(())
|
||||
}).map_err(photocraft_engine::EngineError::Other)?;
|
||||
} else {
|
||||
*doc.layer_mut(layer).ok_or(photocraft_engine::EngineError::NoLayer(layer))? =
|
||||
updated.layer(layer).cloned().ok_or(photocraft_engine::EngineError::NoLayer(layer))?;
|
||||
}
|
||||
doc.metadata.text.retain(|(key, _)| key != &marker && key != &manual_marker && key != &user_marker);
|
||||
if manual { doc.metadata.text.push((user_marker, candidate.clone())); }
|
||||
doc.metadata.text.push((marker, candidate));
|
||||
if manual && selection_unchanged { *selected = Some(layer); }
|
||||
} else {
|
||||
*doc = updated;
|
||||
if selection_unchanged { *selected = Some(layer); }
|
||||
}
|
||||
for id in repairs {
|
||||
if let Some(repair) = doc.layer_mut(id) {
|
||||
repair.visible = false;
|
||||
}
|
||||
}
|
||||
update_structure_guides(doc, layer, &guide_meta)?;
|
||||
if let Some((key, value)) = checkpoint {
|
||||
doc.metadata.text.push((key, value));
|
||||
}
|
||||
Ok(())
|
||||
}) { self.error = error.to_string(); return Some((meta, false)); }
|
||||
if batch { meta["commitBaseRevision"] = json!(before_revision); }
|
||||
if let Some(active) = app.session.active() {
|
||||
let doc = active.doc.clone();
|
||||
let revision = active.revision;
|
||||
app.clear_slot_preview(&doc, layer);
|
||||
self.canvas_workspace.adoption_save_pending = Some((doc.id.0, revision));
|
||||
meta["localSave"] = json!({"state":"pending","revision":revision});
|
||||
if manual {
|
||||
self.canvas_workspace.manual_adoption_saved = before_revision.map(|before| (before, revision, json!({
|
||||
"outputId":meta["outputId"],"variantId":meta["variantId"],"slotId":meta["slotId"],
|
||||
"layerId":layer.0,"adoptedCandidateId":meta["candidateId"],"origin":"human","kinds":["imageSource"],
|
||||
})));
|
||||
}
|
||||
}
|
||||
self.observe_host_canvas(app);
|
||||
if !self.product_target_hidden { app.sync_views(); }
|
||||
let mut effect = meta.clone();
|
||||
effect["afterRevision"] = json!(app.session.active().map(|s| s.revision));
|
||||
effect["effectProject"] = json!(bound_project(self, meta["doc"].as_u64().unwrap_or_default()));
|
||||
let started = std::time::Instant::now();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(snapshot) = snapshot.as_ref().filter(|_| painting && !batch) {
|
||||
crate::canvas::set_agent_adoption(ctx, Some(crate::canvas::AgentAdoptionFade {
|
||||
old_doc:snapshot.before_doc.clone(), lease:effect.clone(), started, request_id:worker.prewarm_id.unwrap_or_default(),
|
||||
}));
|
||||
}
|
||||
if !batch {
|
||||
self.canvas_workspace.adoption_effect = Some((effect, started));
|
||||
}
|
||||
self.canvas_workspace.adoption_snapshot = if batch { None } else { snapshot };
|
||||
self.draft_changed = true;
|
||||
self.sync_dirty = true;
|
||||
let mut ack = meta.clone();
|
||||
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();
|
||||
}
|
||||
self.autosave_project(app, ctx);
|
||||
Some((meta, true))
|
||||
}
|
||||
pub(crate) fn canvas_adoption_valid(&self, app: &PhotocraftApp, lease: &Value, started: std::time::Instant) -> bool {
|
||||
self.canvas_workspace.adoption_effect.as_ref().is_some_and(|(current, at)| current == lease && *at == started)
|
||||
&& started.elapsed() < std::time::Duration::from_millis(200)
|
||||
&& lease["accountId"] == self.account["id"] && lease["origin"] == self.origin
|
||||
&& app.session.active().is_some_and(|state| lease["doc"].as_u64() == Some(state.doc.id.0)
|
||||
&& lease["afterRevision"].as_u64() == Some(state.revision)
|
||||
&& lease["effectProject"] == json!(bound_project(self, state.doc.id.0)))
|
||||
&& lease["templateHash"] == self.template_workflow["templateHash"]
|
||||
&& lease["outputId"] == self.canvas_workspace.output && lease["variantId"] == self.canvas_workspace.variant
|
||||
&& app.session.active().is_some_and(|state| {
|
||||
let Some(slot) = lease["slotId"].as_str() else { return false };
|
||||
let Some(variant) = lease["variantId"].as_str() else { return false };
|
||||
native_layer(&state.doc, slot) == lease["nativeLayerId"].as_u64()
|
||||
&& adopted(&state.doc, slot, variant) == lease["candidateId"].as_str()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn expire_workspace_adoption(&mut self, app: &PhotocraftApp, ui: &Ui, doc_id: u64) {
|
||||
if self.canvas_workspace.adoption_effect.as_ref().is_some_and(|(effect, started)| {
|
||||
effect["doc"].as_u64() != Some(doc_id) || effect["accountId"] != self.account["id"] || effect["origin"] != self.origin
|
||||
|| effect["effectProject"] != json!(bound_project(self, doc_id))
|
||||
|| app.session.active().is_none_or(|state| effect["afterRevision"].as_u64() != Some(state.revision))
|
||||
|| started.elapsed().as_secs_f64() >= 0.2
|
||||
}) {
|
||||
self.canvas_workspace.adoption_effect = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::canvas::set_agent_adoption(ui.ctx(), None);
|
||||
}
|
||||
if self.canvas_workspace.adoption_effect.as_ref().is_none_or(|(_, started)| started.elapsed().as_secs_f64() >= 0.2) {
|
||||
self.canvas_workspace.adoption_snapshot = None;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,715 @@
|
||||
use super::super::{LayerContent, json, PhotocraftApp, Request, Tokens, Ui, Value, Workspace};
|
||||
use super::super::stitch_ui as kit;
|
||||
use super::adoption::{user_adopted, user_adoption_matches};
|
||||
use super::document::{adopted, document_mapping, manual_image, FrameDocIndex};
|
||||
use super::projection::{
|
||||
candidate_adoption_input, candidate_can_adopt, candidate_group, candidate_is_running,
|
||||
candidate_task_id, candidates, card, first_generated_preview, fit_candidate, frame,
|
||||
includes_target, native_selection_subject, preview_rejected, rows, scope, short_slot_label,
|
||||
slot_hit_is_obscured, status, world_rect, Row,
|
||||
};
|
||||
use super::{bound_project, CARD_WIDTH};
|
||||
use crate::canvas::ViewXform;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Vec2, pos2, vec2};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(crate) fn constrain_candidate_menu_width(ui: &mut Ui) {
|
||||
// The shared row fills the available UI width. Constrain both minimum
|
||||
// and maximum here so the popup cannot inherit the whole canvas width.
|
||||
// Leave room for the popup frame and viewport edge on narrow windows.
|
||||
let width = 176.0_f32.min((ui.ctx().content_rect().width() - 32.0).max(0.0));
|
||||
ui.set_width(width);
|
||||
}
|
||||
|
||||
pub(crate) struct CandidateDrawInput<'a> {
|
||||
pub(crate) row: &'a Row<'a>, pub(crate) width: f32, pub(crate) index: usize, pub(crate) xf: ViewXform, pub(crate) pointer: Option<egui::Pos2>, pub(crate) doc_id: u64,
|
||||
pub(crate) variant: &'a str, pub(crate) variant_label: &'a str, pub(crate) mapping_layer: Option<u64>, pub(crate) painter: &'a egui::Painter,
|
||||
pub(crate) t: Tokens, pub(crate) workflow: &'a Value, pub(crate) output: &'a str, pub(crate) now: f64, pub(crate) reference_owns_pointer: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct CandidateDrawResult {
|
||||
pub(crate) blocked: bool, pub(crate) pointer_on_image: bool, pub(crate) menu_shown: bool, pub(crate) trace_target: Option<Value>,
|
||||
pub(crate) action: Option<(&'static str, Value)>, pub(crate) professional_request: Option<Option<u64>>,
|
||||
}
|
||||
|
||||
pub(crate) struct SlotDrawInput<'a> {
|
||||
pub(crate) row: &'a Row<'a>,
|
||||
pub(crate) mapping_layer: Option<u64>,
|
||||
pub(crate) xf: ViewXform,
|
||||
pub(crate) doc_id: u64,
|
||||
pub(crate) variant: &'a str,
|
||||
pub(crate) variant_label: &'a str,
|
||||
pub(crate) world_pointer: Option<[f64; 2]>,
|
||||
pub(crate) now: f64,
|
||||
pub(crate) painter: &'a egui::Painter,
|
||||
pub(crate) frame_index: Option<&'a FrameDocIndex<'a>>,
|
||||
}
|
||||
|
||||
pub(crate) type CandidateMenuResult = (Option<(&'static str, Value)>, Option<Option<u64>>, bool);
|
||||
|
||||
pub(crate) struct CandidateMenuInput<'a> {
|
||||
pub(crate) response: &'a egui::Response,
|
||||
pub(crate) candidate: &'a Value,
|
||||
pub(crate) adopted: bool,
|
||||
pub(crate) mapping_layer: Option<u64>,
|
||||
pub(crate) task_id: &'a str,
|
||||
pub(crate) has_image: bool,
|
||||
pub(crate) doc_id: u64,
|
||||
pub(crate) workflow: &'a Value,
|
||||
pub(crate) output: &'a str,
|
||||
pub(crate) variant: &'a str,
|
||||
pub(crate) slot_id: &'a str,
|
||||
pub(crate) candidate_id: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CandidateMenu {
|
||||
pub(crate) popup: egui::Id,
|
||||
pub(crate) account: Value,
|
||||
pub(crate) origin: String,
|
||||
pub(crate) project: Option<String>,
|
||||
pub(crate) doc: u64,
|
||||
pub(crate) workspace: Value,
|
||||
pub(crate) template: Value,
|
||||
pub(crate) output: String,
|
||||
pub(crate) variant: String,
|
||||
pub(crate) slot: String,
|
||||
pub(crate) candidate: Value,
|
||||
pub(crate) rect: Rect,
|
||||
pub(crate) rows: Vec<(&'static str, bool)>,
|
||||
}
|
||||
|
||||
|
||||
impl CandidateMenu {
|
||||
pub(crate) fn current(&self, w: &Workspace, workflow: &Value, doc: u64) -> bool {
|
||||
let Some(project) = self.project.as_deref().filter(|id| !id.is_empty()) else { return false };
|
||||
self.account.as_str().is_some_and(|id| !id.is_empty())
|
||||
&& self.workspace.as_str().is_some_and(|id| !id.is_empty())
|
||||
&& self.candidate["id"].as_str().is_some_and(|id| !id.is_empty())
|
||||
&& !self.slot.is_empty() && !self.output.is_empty() && !self.variant.is_empty()
|
||||
&& self.doc == doc
|
||||
&& self.account == w.account["id"]
|
||||
&& self.origin == w.origin
|
||||
&& bound_project(w, doc) == Some(project)
|
||||
&& self.workspace == workflow["workspaceId"]
|
||||
&& self.template == json!([workflow["templateId"], workflow["templateVersion"], workflow["templateHash"]])
|
||||
&& self.output == w.canvas_workspace.output
|
||||
&& self.variant == w.canvas_workspace.variant
|
||||
&& w.canvas_workspace.context.as_ref().is_some_and(|target| {
|
||||
target["slotId"] == self.slot
|
||||
&& target["candidateId"] == self.candidate["id"]
|
||||
&& target["productVariantId"] == self.variant
|
||||
&& target["outputId"] == self.output
|
||||
})
|
||||
&& rows(workflow, &self.output, &self.variant).iter().any(|row| {
|
||||
row.slot["id"] == self.slot && candidates(row.slot).iter().any(|candidate| candidate == &self.candidate)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_image_shape(ctx: &egui::Context, texture: egui::TextureId, image: [f32; 4], xf: ViewXform, opacity: f32) -> egui::Shape {
|
||||
let radius = 5.0;
|
||||
if xf.rotation.abs() < 1e-8 && !xf.flip {
|
||||
return super::agent_motion::rounded_image_entry_blur(texture, world_rect(xf, image), opacity, radius);
|
||||
}
|
||||
// Tessellate the same rounded samples in their screen-sized local frame,
|
||||
// then carry the vertices through the existing rotated/mirrored view.
|
||||
// This uncommon path retains the native orientation without sampling a
|
||||
// screenshot or modifying any image/document data.
|
||||
let sx = xf.zoom_x();
|
||||
let sy = xf.zoom;
|
||||
if !sx.is_finite() || !sy.is_finite() || sx <= 0.0 || sy <= 0.0 {
|
||||
return egui::Shape::Noop;
|
||||
}
|
||||
let local = Rect::from_min_size(pos2(0.0, 0.0), vec2(image[2] * sx, image[3] * sy));
|
||||
let shape = super::agent_motion::rounded_image_entry_blur(texture, local, opacity, radius);
|
||||
let origin = xf.to_screen(image[0], image[1]);
|
||||
let clipped = egui::epaint::ClippedShape::new(Rect::EVERYTHING, shape);
|
||||
let shapes = ctx.tessellate(vec![clipped], ctx.pixels_per_point()).into_iter().filter_map(|primitive| {
|
||||
let egui::epaint::Primitive::Mesh(mut mesh) = primitive.primitive else { return None };
|
||||
for vertex in &mut mesh.vertices {
|
||||
vertex.pos = origin + xf.map_vec(vec2(vertex.pos.x / sx, vertex.pos.y / sy));
|
||||
}
|
||||
Some(egui::Shape::mesh(mesh))
|
||||
}).collect();
|
||||
egui::Shape::Vec(shapes)
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn candidate_context_menu(&mut self, ui: &mut Ui, input: CandidateMenuInput<'_>) -> CandidateMenuResult {
|
||||
let CandidateMenuInput { response, candidate: c, adopted, mapping_layer, task_id, has_image, doc_id, workflow, output, variant, slot_id, candidate_id: id } = input;
|
||||
let mut action = None;
|
||||
let mut professional_request = None;
|
||||
let mut menu_shown = false;
|
||||
let popup_id = egui::Popup::default_response_id(response);
|
||||
if bound_project(self, doc_id).is_some() {
|
||||
let opening = response.secondary_clicked() || (egui::Popup::is_id_open(ui.ctx(), popup_id) && !response.clicked());
|
||||
let visual = opening.then(|| super::stitch_ui::overlay_transition(ui.ctx(), popup_id, true, self.reduce_motion));
|
||||
let popup_frame = visual.map_or_else(
|
||||
|| super::stitch_ui::menu_frame(ui.ctx()),
|
||||
|visual| super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu, visual.opacity),
|
||||
);
|
||||
let shown = egui::Popup::context_menu(response).frame(egui::Frame::NONE).show(|ui| {
|
||||
super::stitch_ui::material_frame_over(ui,popup_frame,super::stitch_ui::menu_base(),
|
||||
super::stitch_ui::menu_rim(Tokens::get(ui.ctx()).agent()),|ui| {
|
||||
super::stitch_ui::scope(ui, |ui| {
|
||||
if let Some(visual) = visual {
|
||||
ui.set_opacity(visual.opacity);
|
||||
}
|
||||
constrain_candidate_menu_width(ui);
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
let adopt_enabled = candidate_can_adopt(c, mapping_layer) && !adopted
|
||||
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none();
|
||||
if super::stitch_ui::menu_item(
|
||||
ui,
|
||||
"采纳",
|
||||
adopt_enabled,
|
||||
)
|
||||
.on_disabled_hover_text(c["adoptionError"].as_str().unwrap_or("当前无法采纳"))
|
||||
.clicked()
|
||||
{
|
||||
action = Some(("slot-adopt-prep", candidate_adoption_input(c, slot_id, variant, mapping_layer)));
|
||||
ui.close();
|
||||
}
|
||||
if matches!(c["status"].as_str(), Some("unknown" | "prepared" | "dispatched" | "running"))
|
||||
&& super::stitch_ui::menu_item(ui, "核查原结果", true).clicked()
|
||||
{
|
||||
action = Some(("slot-recover", json!({"slotId":slot_id,"candidateId":id,"candidate":c["variant"],"variantId":variant})));
|
||||
ui.close();
|
||||
}
|
||||
if workflow["canvasFirst"] == true && c["status"] == "complete" && c["historical"] != true {
|
||||
let regenerate = super::stitch_ui::menu_item(ui, "重新生成", true);
|
||||
let rect = regenerate.rect;
|
||||
self.canvas_workspace.geometry.insert("candidate-menu-regenerate".into(),
|
||||
[rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
if regenerate.clicked()
|
||||
&& let Some(slot) = workflow["slots"].as_array().into_iter().flatten().find(|slot| slot["id"] == slot_id)
|
||||
{
|
||||
let mut target = scope(slot, Some(c), variant, "");
|
||||
target["nativeLayerId"] = json!(mapping_layer);
|
||||
self.canvas_workspace.open_regen(target, workflow);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if c["status"] == "complete" && c["archivePreview"] != true
|
||||
&& super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked()
|
||||
&& let Some(slot) = workflow["slots"].as_array().into_iter().flatten().find(|slot| slot["id"] == slot_id)
|
||||
{
|
||||
let mut target = scope(slot, Some(c), variant, "");
|
||||
target["nativeLayerId"] = json!(mapping_layer);
|
||||
target["documentId"] = json!(doc_id);
|
||||
target["taskId"] = json!(task_id);
|
||||
ui.data_mut(|data| data.insert_temp(egui::Id::unique("xiaoyi-image-reference"), target));
|
||||
ui.close();
|
||||
}
|
||||
if has_image && super::stitch_ui::menu_item(ui, "放大预览", true).clicked() {
|
||||
ui.data_mut(|data| data.insert_temp(egui::Id::unique("jiansun-image-expanded"), task_id.to_owned()));
|
||||
ui.close();
|
||||
}
|
||||
if super::stitch_ui::menu_item(ui, "专业编辑图片", c["status"] == "complete" && c["historical"] != true && mapping_layer.is_some())
|
||||
.on_hover_text("用原始图片打开独立原生画布,编辑后明确回填到此图位")
|
||||
.clicked()
|
||||
{
|
||||
professional_request = Some(mapping_layer);
|
||||
ui.close();
|
||||
}
|
||||
if !has_image && c["status"] == "complete" && super::stitch_ui::menu_item(ui, "重新加载预览", true).clicked() {
|
||||
self.requested_previews.remove(task_id);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if let Some(shown) = shown {
|
||||
let mut menu_rows = vec![("采纳", candidate_can_adopt(c, mapping_layer) && !adopted
|
||||
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none())];
|
||||
if matches!(c["status"].as_str(), Some("unknown" | "prepared" | "dispatched" | "running")) {
|
||||
menu_rows.push(("核查原结果", true));
|
||||
}
|
||||
if workflow["canvasFirst"] == true && c["status"] == "complete" { menu_rows.push(("重新生成", true)); }
|
||||
if c["status"] == "complete" { menu_rows.push(("引用到小壹", true)); }
|
||||
if has_image { menu_rows.push(("放大预览", true)); }
|
||||
menu_rows.push(("专业编辑图片", c["status"] == "complete" && mapping_layer.is_some()));
|
||||
if !has_image && c["status"] == "complete" { menu_rows.push(("重新加载预览", true)); }
|
||||
self.canvas_workspace.candidate_menu = Some(CandidateMenu {
|
||||
popup: popup_id, account: self.account["id"].clone(), origin: self.origin.clone(),
|
||||
project: self.open_projects.get(&doc_id).cloned(), doc: doc_id,
|
||||
workspace: workflow["workspaceId"].clone(),
|
||||
template: json!([workflow["templateId"], workflow["templateVersion"], workflow["templateHash"]]),
|
||||
output: output.to_owned(), variant: variant.to_owned(), slot: slot_id.to_owned(),
|
||||
candidate: c.clone(), rect: shown.response.rect, rows: menu_rows,
|
||||
});
|
||||
menu_shown = true;
|
||||
}
|
||||
} else {
|
||||
egui::Popup::close_id(ui.ctx(), popup_id);
|
||||
if response.secondary_clicked() {
|
||||
self.error = "当前本地项目身份尚未确认,暂无法打开候选菜单".into();
|
||||
}
|
||||
}
|
||||
(action, professional_request, menu_shown)
|
||||
}
|
||||
|
||||
pub(crate) fn draw_workspace_slot(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, input: SlotDrawInput<'_>, action: &mut Option<(&'static str, Value)>) -> (bool, bool) {
|
||||
let SlotDrawInput { row, mapping_layer, xf, doc_id, variant, variant_label, world_pointer, now, painter, frame_index } = input;
|
||||
let slot_id = row.slot["id"].as_str().unwrap_or("");
|
||||
let mut blocked = false;
|
||||
let mut pointer_on_image = false;
|
||||
if let Some(f) = frame(row) {
|
||||
let rect = world_rect(xf, f);
|
||||
let on_screen = rect.intersects(xf.rect);
|
||||
// 供自动化/验收定位:文档坐标与屏幕坐标都暴露出来,
|
||||
// 空图位额外标记,便于精确截图核对占位标签可读性。
|
||||
self.canvas_workspace.geometry.insert(format!("slot-doc:{slot_id}"), f);
|
||||
if on_screen {
|
||||
self.canvas_workspace.geometry.insert(format!("slot:{slot_id}"), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
}
|
||||
let empty = frame_index.is_some_and(|index| {
|
||||
mapping_layer
|
||||
.and_then(|id| index.layers.get(&id).copied())
|
||||
.is_some_and(|layer| {
|
||||
index.is_hidden_unfilled_sample(layer, slot_id)
|
||||
|| matches!(&layer.content, LayerContent::Smart(smart) if matches!(&smart.source, photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "template-empty.png"))
|
||||
})
|
||||
});
|
||||
if empty {
|
||||
// 单独标记空图位,验收工具无需渲染判断即可直接定位空槽。
|
||||
self.canvas_workspace.geometry.insert(format!("slot-empty:{slot_id}"), f);
|
||||
}
|
||||
if !on_screen {
|
||||
return (false, false);
|
||||
}
|
||||
let first_preview = first_generated_preview(row.slot);
|
||||
if let Some(layer) = mapping_layer.map(photocraft_doc::LayerId)
|
||||
&& let Some(candidate) = first_preview.and_then(|row| row["id"].as_str())
|
||||
&& app.session.active().is_some_and(|state| {
|
||||
state.doc.id.0 == doc_id
|
||||
&& !frame_index.is_some_and(|index| index.adopted_slots.contains(slot_id))
|
||||
&& empty && frame_index.and_then(|index| index.layers.get(&layer.0).copied()).is_some_and(|layer| layer.visible)
|
||||
&& self.detail_layer_unchanged(&state.doc, layer)
|
||||
})
|
||||
{
|
||||
app.queue_slot_preview(&self.tx, layer,
|
||||
json!({"doc":doc_id,"slotId":slot_id,"candidateId":candidate,"nativeLayerId":layer.0}));
|
||||
}
|
||||
if let Some((effect, started)) = self.canvas_workspace.adoption_effect.as_ref()
|
||||
&& effect["slotId"] == slot_id && effect["variantId"] == variant
|
||||
&& effect["doc"].as_u64() == Some(doc_id)
|
||||
&& app.session.active().is_some_and(|state| effect["afterRevision"].as_u64() == Some(state.revision))
|
||||
{
|
||||
let started = now - started.elapsed().as_secs_f64();
|
||||
if now - started < 0.2 {
|
||||
ui.scope(|ui| {
|
||||
ui.set_clip_rect(ui.clip_rect().intersect(xf.rect));
|
||||
let effect_id = ui.scope_id().with(("adoption-ripple", doc_id, slot_id));
|
||||
super::agent_motion::adoption_ripple(ui, effect_id, rect, started, self.reduce_motion);
|
||||
});
|
||||
}
|
||||
}
|
||||
let has_preview = mapping_layer.map(photocraft_doc::LayerId).is_some_and(|layer|
|
||||
app.session.active().is_some_and(|state| adopted(&state.doc, slot_id, variant).is_none()
|
||||
&& state.doc.layer(layer).is_some_and(|node| node.visible) && app.has_slot_preview(&state.doc, layer)));
|
||||
let visible = rect.intersect(xf.rect).intersect(ui.clip_rect());
|
||||
if has_preview && visible.is_positive() {
|
||||
let accent = Tokens::get(ui.ctx()).agent().accent;
|
||||
painter.extend(egui::Shape::dashed_line(&[rect.left_top(), rect.right_top(), rect.right_bottom(),
|
||||
rect.left_bottom(), rect.left_top()], Stroke::new(2.0, accent), 6.0, 4.0));
|
||||
let label = painter.layout_no_wrap("预览 · 未采纳".into(), FontId::proportional(12.0), Color32::WHITE);
|
||||
let chip = Rect::from_min_size(visible.left_top() + vec2(6.0, 6.0), label.size() + vec2(12.0, 8.0));
|
||||
if visible.contains_rect(chip) {
|
||||
let badge = ui.interact(chip, ui.scope_id().with(("unadopted-preview", doc_id, slot_id)), Sense::hover());
|
||||
badge.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, "预览 · 未采纳"));
|
||||
self.canvas_workspace.geometry.insert(format!("slot-preview:{slot_id}"), [chip.min.x, chip.min.y, chip.width(), chip.height()]);
|
||||
painter.rect_filled(chip, 4.0, Color32::from_black_alpha(205));
|
||||
painter.galley(chip.min + vec2(6.0, 4.0), label, Color32::WHITE);
|
||||
}
|
||||
if let Some(candidate) = first_preview.and_then(|row| row["id"].as_str()) {
|
||||
let pill = Rect::from_min_size(chip.right_top() + vec2(6.0, 0.0), vec2(46.0, chip.height()));
|
||||
if visible.contains_rect(pill) {
|
||||
let mut overlay = ui.new_child(egui::UiBuilder::new()
|
||||
.id_salt(("adopt-preview", doc_id, slot_id)).max_rect(pill));
|
||||
let response = super::stitch_ui::action_button_height(&mut overlay, "采纳",
|
||||
super::stitch_ui::ButtonRole::Secondary, true, pill.height());
|
||||
blocked |= response.hovered() || response.clicked();
|
||||
if response.clicked() {
|
||||
*action = Some(("slot-adopt-prep",
|
||||
json!({"slotId":slot_id,"candidateId":candidate,"variantId":variant,"nativeLayerId":mapping_layer})));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_preview
|
||||
&& first_preview.is_some_and(|row| preview_rejected(row, slot_id, self.workflow.production_progress()))
|
||||
&& visible.width() >= 104.0 && visible.height() >= 36.0
|
||||
{
|
||||
let chip = Rect::from_min_size(visible.left_bottom() + vec2(6.0, -30.0), vec2(92.0, 24.0));
|
||||
super::stitch_ui::paint_badge(ui, ui.scope_id().with(("rejected-first-preview", slot_id)),
|
||||
chip, super::stitch_ui::BadgeKind::Warning, "首图已退回", self.reduce_motion);
|
||||
self.canvas_workspace.geometry.insert(format!("rejected-preview:{slot_id}"),
|
||||
[chip.min.x, chip.min.y, chip.width(), chip.height()]);
|
||||
}
|
||||
if empty && !has_preview && rect.intersects(xf.rect) {
|
||||
// 空图位画在作品页面之上,页面底色由模板决定(当前为白色),
|
||||
// 不能用界面主题的 text_dim:深色主题下它接近白色,在页面上不可见。
|
||||
// 用与主题无关的深色标签底 + 白字,保证任何页面底色都可读。
|
||||
painter.rect_filled(rect, 0.0, Color32::from_black_alpha(10));
|
||||
painter.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::from_black_alpha(70)), egui::StrokeKind::Inside);
|
||||
if rect.width() > 90.0 && rect.height() > 40.0 {
|
||||
let galley = painter.layout_no_wrap("图片图位".to_owned(), FontId::proportional(12.0), Color32::WHITE);
|
||||
let chip = Rect::from_center_size(rect.center(), galley.size() + vec2(16.0, 8.0));
|
||||
painter.rect_filled(chip, 4.0, Color32::from_black_alpha(150));
|
||||
painter.galley(chip.center() - galley.size() * 0.5, galley, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
let selected = includes_target(self.canvas_workspace.context.as_ref(), slot_id, None);
|
||||
if selected && rect.intersects(xf.rect) {
|
||||
super::agent_motion::role_light(ui, super::agent_motion::Surface::new(ui.scope_id().with(("selected-slot", doc_id, slot_id)), rect, 0.0).clipped_to(xf.rect), self.reduce_motion, super::agent_motion::LightRole::CanvasTarget);
|
||||
}
|
||||
if world_pointer.is_some_and(|p| p[0] >= f[0] as f64 && p[0] <= (f[0] + f[2]) as f64 && p[1] >= f[1] as f64 && p[1] <= (f[1] + f[3]) as f64) {
|
||||
pointer_on_image = true;
|
||||
// The empty Smart slot is an Agent target, not a paintable
|
||||
// raster. Navigation has a separate owner in canvas.rs.
|
||||
let native_owns_click = app.ui.tool != crate::state::Tool::Move || app.ui.text_edit.is_some()
|
||||
|| app.ui.transform.is_some() || world_pointer.is_some_and(|point| app.session.active().is_some_and(|state|
|
||||
slot_hit_is_obscured(&state.doc, point, mapping_layer.map(photocraft_doc::LayerId))));
|
||||
blocked |= empty && !native_owns_click;
|
||||
if !native_owns_click && ui.input(|i| i.pointer.primary_clicked())
|
||||
{
|
||||
let mut target = scope(row.slot, None, variant, variant_label);
|
||||
target["nativeLayerId"] = json!(mapping_layer);
|
||||
self.canvas_workspace.context = Some(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
(blocked, pointer_on_image)
|
||||
}
|
||||
|
||||
pub(crate) fn paint_adopted_badge(&self, app: &PhotocraftApp, ui: &Ui, t: &Tokens, target: (&str, &str, &str, Rect, f64), has_preview: bool) -> bool {
|
||||
let (slot_id, variant, id, rect, now) = target;
|
||||
let adopted = app.session.active().is_some_and(|s| adopted(&s.doc, slot_id, variant) == Some(id));
|
||||
let minimum_width = if has_preview { 126.0 } else { 96.0 };
|
||||
if adopted && rect.width() > minimum_width && rect.height() > 40.0 {
|
||||
let mut badge = Rect::from_min_size(rect.right_top() + vec2(if has_preview { -118.0 } else { -84.0 }, 8.0), vec2(76.0, 24.0));
|
||||
if let Some((effect, started)) = self.canvas_workspace.adoption_effect.as_ref()
|
||||
&& effect["candidateId"] == id && effect["slotId"] == slot_id && effect["variantId"] == variant
|
||||
{
|
||||
let scale = super::agent_motion::adoption_badge_scale(now, now - started.elapsed().as_secs_f64(), self.reduce_motion);
|
||||
badge = Rect::from_center_size(badge.center(), badge.size() * scale);
|
||||
}
|
||||
let _=t;
|
||||
super::stitch_ui::paint_badge(ui,ui.scope_id().with(("adopted",slot_id,variant,id)),badge,super::stitch_ui::BadgeKind::Adopted,"已采纳",self.reduce_motion);
|
||||
}
|
||||
adopted
|
||||
}
|
||||
|
||||
pub(crate) fn paint_candidate_task_badge(&self,ui:&Ui,id:egui::Id,rect:Rect,candidate:&Value,processing:bool,adopted:bool) {
|
||||
use super::stitch_ui::{self as kit,BadgeKind};
|
||||
if processing || adopted || rect.width()<=112.0 || rect.height()<=50.0 {return;}
|
||||
let status=candidate["status"].as_str().unwrap_or("");
|
||||
let pending = self.canvas_workspace.pending_adoption.as_ref().is_some_and(|pending| pending["candidateId"] == candidate["id"]);
|
||||
let (kind,label)=if pending {(BadgeKind::Running,"正在采纳")}
|
||||
else if status == "unknown" {(BadgeKind::Warning,"待核查")}
|
||||
else if status == "failed" {(BadgeKind::Warning,"生成失败")}
|
||||
else if candidate["historical"] == true {(BadgeKind::Neutral,"历史候选")}
|
||||
else if self.agent_effects_paused && matches!(status,"prepared"|"dispatched"|"running") {(BadgeKind::Neutral,"已停止")}
|
||||
else {return;};
|
||||
let badge = if candidate["historical"] == true {
|
||||
Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(68.0, 24.0))
|
||||
} else {
|
||||
Rect::from_min_size(rect.right_top() + vec2(-92.0, 8.0), vec2(84.0, 24.0))
|
||||
};
|
||||
kit::paint_badge(ui,id.with("badge"),badge,kind,label,self.reduce_motion);
|
||||
}
|
||||
|
||||
pub(crate) fn mark_workspace_candidate_visible(&mut self, task_id: &str, candidate: Option<&Value>) {
|
||||
if !task_id.is_empty() {
|
||||
if candidate.is_some_and(|candidate| candidate["status"] == "complete" && candidate["archivePreview"] != true) { self.agent_images.mark_visible(task_id); }
|
||||
else { self.agent_images.mark_visible_existing(task_id); }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn draw_workspace_candidate(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, input: CandidateDrawInput<'_>) -> CandidateDrawResult {
|
||||
let CandidateDrawInput { row, width, index, xf, pointer, doc_id, variant, variant_label, mapping_layer, painter, t, workflow, output, now, reference_owns_pointer } = input;
|
||||
let slot_id = row.slot["id"].as_str().unwrap_or("");
|
||||
let all = candidates(row.slot);
|
||||
let mut result = CandidateDrawResult::default();
|
||||
let candidate = all.get(index);
|
||||
let world = card(row, width, index);
|
||||
let task_id = candidate.map_or("", candidate_task_id);
|
||||
let preview = if candidate.is_some() {
|
||||
self.agent_images.peek(task_id)
|
||||
} else {
|
||||
// Match the last available preview in this row. A new slot
|
||||
// with no previews still uses the template frame.
|
||||
all.iter().rev().find_map(|c| self.agent_images.peek(candidate_task_id(c)))
|
||||
};
|
||||
let image_world = preview.map_or(world, |texture| fit_candidate(world, texture.size_vec2()));
|
||||
let image_rect = world_rect(xf, image_world);
|
||||
let rect = image_rect;
|
||||
if !rect.intersects(xf.rect) {
|
||||
return result;
|
||||
}
|
||||
let visible = rect.intersect(xf.rect).intersect(ui.clip_rect());
|
||||
if !visible.is_positive() { return result; }
|
||||
self.mark_workspace_candidate_visible(task_id, candidate);
|
||||
result.pointer_on_image |= pointer.is_some_and(|point| visible.contains(point));
|
||||
let id = candidate.and_then(|c| c["id"].as_str()).unwrap_or("empty");
|
||||
let key = format!("{slot_id}/{id}");
|
||||
self.canvas_workspace.geometry.insert(key.clone(), [visible.min.x, visible.min.y, visible.width(), visible.height()]);
|
||||
let sense = if reference_owns_pointer { Sense::empty() } else { Sense::click() };
|
||||
let response = ui.interact(visible, ui.scope_id().with(("canvas-candidate", &self.canvas_workspace.binding, doc_id, &variant, slot_id, id)), sense);
|
||||
response.widget_info(|| {
|
||||
let field = row.slot["label"].as_str().unwrap_or("图片");
|
||||
let label = if candidate.is_some_and(|row| row["sourceType"] == "product-reference") {
|
||||
format!("{field},产品原图")
|
||||
} else if candidate.is_some_and(|row| row["historical"] == true) {
|
||||
format!("{field},历史候选 {}", index + 1)
|
||||
} else if candidate.is_some() {
|
||||
format!("{field},候选 {}", index + 1)
|
||||
} else {
|
||||
format!("{field},生成图片")
|
||||
};
|
||||
egui::WidgetInfo::labeled(egui::Role::Button, true, label)
|
||||
});
|
||||
if result.pointer_on_image {
|
||||
result.blocked = true;
|
||||
}
|
||||
let selected = includes_target(self.canvas_workspace.context.as_ref(), slot_id, Some(id));
|
||||
let footer_height = if rect.width() >= 180.0 && rect.height() >= 110.0 { 42.0 } else { 0.0 };
|
||||
let screen_scale = (rect.width() / image_world[2]).max(0.001);
|
||||
if candidate.is_some() && !self.agent_images.contains_key(task_id) {
|
||||
painter.rect_filled(image_rect, 5.0, t.field);
|
||||
}
|
||||
let mut has_image = false;
|
||||
if let Some(c) = candidate {
|
||||
let adoption_error = c["adoptionError"].as_str();
|
||||
if let Some(error) = adoption_error {
|
||||
let _ = response.clone().on_hover_text(error);
|
||||
}
|
||||
if let Some(texture) = self.agent_images.get(task_id) {
|
||||
let (ease, _) = self.canvas_workspace.appeared.get(task_id)
|
||||
.map(|start| super::agent_motion::image_enter(now - *start, screen_scale, self.reduce_motion))
|
||||
.unwrap_or((1.0, 0.0));
|
||||
if ease < 1.0 {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
painter.add(candidate_image_shape(ui.ctx(), texture.id(), image_world, xf, ease));
|
||||
has_image = true;
|
||||
} else if c["status"] == "complete" && c["adoptionError"].is_null() && !task_id.is_empty()
|
||||
&& self.agent_images.can_insert(task_id) && self.requested_previews.insert(task_id.to_owned()) {
|
||||
let request = if c["historical"] == true || c["archivePreview"] == true {
|
||||
Request::Action("slot-read".into(), json!({"doc":doc_id,"previewCandidateId":task_id,
|
||||
"viewOutputId":output,"viewVariantId":variant,"viewTemplateHash":workflow["templateHash"]}))
|
||||
} else {
|
||||
Request::Action("agent-image-preview".into(), json!({"doc":doc_id,"taskId":task_id}))
|
||||
};
|
||||
if self.tx.send(request).is_err() {
|
||||
self.requested_previews.remove(task_id);
|
||||
}
|
||||
}
|
||||
let processing = !has_image && matches!(c["status"].as_str(), Some("prepared" | "dispatched" | "running"))
|
||||
&& candidate_is_running(self, doc_id, slot_id, c);
|
||||
let waiting_id = ui.scope_id().with(("candidate-processing", doc_id, &variant, slot_id, id, task_id));
|
||||
if processing {
|
||||
ui.scope(|ui| {
|
||||
ui.set_clip_rect(visible);
|
||||
let background = super::agent_motion::reserve_background(ui);
|
||||
super::stitch_ui::material(ui, waiting_id, image_rect, 8.0, 0.0, background);
|
||||
let start = ui.data_mut(|data| *data.get_temp_mut_or_insert_with(waiting_id, || now));
|
||||
let elapsed = (now - start) * 0.55;
|
||||
let pulse = if self.reduce_motion { super::glow_pill::Pulse::default() } else { super::glow_pill::waiting(elapsed) };
|
||||
super::glow_pill::paint(ui, super::glow_pill::Surface { id: waiting_id, rect: image_rect, radius: 8.0,
|
||||
time: if self.reduce_motion { 2.4 } else { elapsed }, pulse, opacity: 1.0, background: Some(background), text_range: None, flanks: 0.0 });
|
||||
if image_rect.width() >= 92.0 && image_rect.height() >= 48.0 {
|
||||
let orb = Rect::from_min_size(image_rect.min + vec2(10.0, 10.0), vec2(20.0, 20.0));
|
||||
super::siri_orb::paint(ui, waiting_id.with("orb"), orb, super::siri_orb::Motion::Thinking, self.reduce_motion);
|
||||
ui.painter().text(orb.right_center() + vec2(7.0, 0.0), Align2::LEFT_CENTER, "正在生成", FontId::proportional(12.0), t.text);
|
||||
}
|
||||
if !self.reduce_motion { super::agent_motion::schedule(ui, image_rect, super::agent_motion::Pace::Idle); }
|
||||
});
|
||||
self.canvas_workspace.geometry.insert(format!("generating:{key}"), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
} else {
|
||||
ui.data_mut(|data| data.remove::<f64>(waiting_id));
|
||||
}
|
||||
if !has_image && !processing {
|
||||
let text = if adoption_error.is_some() {
|
||||
"历史图片不可用"
|
||||
} else if self.agent_effects_paused && matches!(c["status"].as_str(), Some("prepared" | "dispatched" | "running")) {
|
||||
"已停止修改 · 原请求保留"
|
||||
} else if c["status"] == "complete" {
|
||||
"已生成 · 预览未载入"
|
||||
} else {
|
||||
super::stitch_ui::processing_label(
|
||||
self.canvas_workspace.progress.get(task_id).map(String::as_str).unwrap_or_else(|| status(c, self.busy.is_some())),
|
||||
)
|
||||
};
|
||||
painter.text(
|
||||
image_rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
text,
|
||||
FontId::proportional(13.0),
|
||||
if c["status"] == "unknown" || adoption_error.is_some() { t.warning } else { t.text_dim },
|
||||
);
|
||||
}
|
||||
let can_expand = has_image && rect.width() >= 42.0 && rect.height() >= 42.0
|
||||
&& visible.contains(rect.right_top() + vec2(-6.0, 6.0));
|
||||
let adopted = self.paint_adopted_badge(app, ui, &t, (slot_id, variant, id, rect, now), can_expand);
|
||||
self.paint_candidate_task_badge(ui,waiting_id,rect,c,processing,adopted);
|
||||
let expand = (can_expand && !reference_owns_pointer).then(|| super::agent_panel::image_preview_button(ui, rect, task_id));
|
||||
if let Some(button) = &expand {
|
||||
self.canvas_workspace.geometry.insert(format!("preview:{key}"), [button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
|
||||
}
|
||||
let locate = !reference_owns_pointer && response.clicked() && !expand.is_some_and(|button| button.clicked());
|
||||
if locate || !reference_owns_pointer && response.secondary_clicked() {
|
||||
let mut target = scope(row.slot, Some(c), variant, variant_label);
|
||||
target["nativeLayerId"] = json!(mapping_layer);
|
||||
if locate {
|
||||
result.trace_target = Some(target.clone());
|
||||
let mut locate_target = target.clone();
|
||||
locate_target["locateImageSlot"] = json!(true);
|
||||
self.canvas_workspace.locate_request = Some(locate_target);
|
||||
}
|
||||
self.canvas_workspace.context = Some(target);
|
||||
}
|
||||
if !processing && footer_height > 0.0 && (result.pointer_on_image || selected) {
|
||||
let button_rect = Rect::from_min_size(rect.right_bottom() + vec2(-72.0, -40.0), vec2(64.0, 34.0));
|
||||
if c["status"] == "complete" && !adopted {
|
||||
let mut controls = ui.new_child(egui::UiBuilder::new()
|
||||
.id_salt(("candidate-adopt", &key)).max_rect(button_rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
let pending = self.canvas_workspace.pending_adoption.as_ref().is_some_and(|pending| pending["candidateId"] == id);
|
||||
let enabled = candidate_can_adopt(c, mapping_layer) && !reference_owns_pointer
|
||||
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none()
|
||||
&& app.ui.dialogs.is_empty() && !egui::Popup::is_any_open(ui.ctx())
|
||||
&& ui.memory(|memory| memory.top_modal_layer().is_none());
|
||||
let response = super::stitch_ui::action_button(&mut controls, if pending { "采纳中…" } else { "采纳" }, super::stitch_ui::ButtonRole::Primary, enabled)
|
||||
.on_disabled_hover_text(c["adoptionError"].as_str().unwrap_or("当前无法采纳"));
|
||||
self.canvas_workspace
|
||||
.geometry
|
||||
.insert(format!("adopt:{key}"), [response.rect.min.x, response.rect.min.y, response.rect.width(), response.rect.height()]);
|
||||
// The canvas is also an interactive widget. Keep the exact
|
||||
// button press across frames even when it takes canvas focus.
|
||||
let press = response.id.with("adopt-press");
|
||||
let (start, finish, down) = ui.input(|input| {
|
||||
let start = input.events.iter().any(|event| matches!(event,
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. }
|
||||
if response.rect.contains(*pos) && xf.rect.contains(*pos)));
|
||||
let finish = input.pointer.primary_clicked() && input.pointer.interact_pos().is_some_and(|pos| response.rect.contains(pos));
|
||||
(start, finish, input.pointer.primary_down())
|
||||
});
|
||||
let clicked = ui.data_mut(|data| {
|
||||
if enabled && start { data.insert_temp(press, true); }
|
||||
let clicked = enabled && finish && data.get_temp::<bool>(press) == Some(true);
|
||||
if !down || !enabled { data.remove::<bool>(press); }
|
||||
clicked
|
||||
});
|
||||
if response.clicked() || clicked {
|
||||
result.action = Some(("slot-adopt-prep", candidate_adoption_input(c, slot_id, variant, mapping_layer)));
|
||||
}
|
||||
} else if c["status"] != "complete" {
|
||||
painter.text(
|
||||
button_rect.right_center(),
|
||||
Align2::RIGHT_CENTER,
|
||||
status(c, self.busy.is_some()),
|
||||
FontId::proportional(12.0),
|
||||
if c["status"] == "unknown" { t.warning } else { t.text_dim },
|
||||
);
|
||||
}
|
||||
}
|
||||
let menu = self.candidate_context_menu(ui, CandidateMenuInput {
|
||||
response: &response, candidate: c, adopted, mapping_layer, task_id, has_image, doc_id,
|
||||
workflow, output, variant, slot_id, candidate_id: id,
|
||||
});
|
||||
if menu.0.is_some() { result.action = menu.0; }
|
||||
if menu.1.is_some() { result.professional_request = menu.1; }
|
||||
result.menu_shown |= menu.2;
|
||||
} else {
|
||||
kit::paint_generation_placeholder(ui, &response, image_rect, self.reduce_motion);
|
||||
let response = response.on_hover_text(format!("为{}生成图片", short_slot_label(row.slot)));
|
||||
if !reference_owns_pointer && response.clicked() {
|
||||
let mut target = scope(row.slot, None, variant, variant_label);
|
||||
target["nativeLayerId"] = json!(mapping_layer);
|
||||
self.canvas_workspace.context = Some(target.clone());
|
||||
self.canvas_workspace.open_regen(target, workflow);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if selected {
|
||||
super::agent_motion::role_light(ui, super::agent_motion::Surface::new(response.id.with("selection-light"), rect, 5.0).clipped_to(xf.rect), self.reduce_motion, super::agent_motion::LightRole::CanvasTarget);
|
||||
}
|
||||
let hover = ui.scope(|ui| {
|
||||
ui.set_clip_rect(ui.clip_rect().intersect(xf.rect));
|
||||
super::agent_motion::hover_amount(ui, response.id.with("hover"), rect, response.hovered(), self.reduce_motion)
|
||||
}).inner;
|
||||
if hover > 0.0 {
|
||||
let hover_painter = painter.with_clip_rect(xf.rect);
|
||||
hover_painter.rect_filled(rect, 5.0, t.accent.gamma_multiply(0.06 * hover));
|
||||
hover_painter.rect_stroke(rect, 5.0, Stroke::new(1.0, t.accent.gamma_multiply(0.38 * hover)), egui::StrokeKind::Outside);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn finish_candidate_menu(&mut self, ui: &mut Ui, workflow: &Value, doc_id: u64, menu_shown: bool) {
|
||||
if let Some(menu) = self.canvas_workspace.candidate_menu.clone() {
|
||||
if !menu.current(self, workflow, doc_id) {
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
self.canvas_workspace.candidate_menu = None;
|
||||
} else if !menu_shown {
|
||||
// The native popup has already closed (or scrolled away). Keep
|
||||
// only its immutable visual snapshot while it exits; this Area
|
||||
// cannot receive input or dispatch an action.
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
let visual = super::stitch_ui::overlay_transition(ui.ctx(), menu.popup, false, self.reduce_motion);
|
||||
if visual.render {
|
||||
egui::Area::new(menu.popup.with("exit"))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(menu.rect.min)
|
||||
.interactable(false)
|
||||
.show(ui.ctx(), |ui| {
|
||||
super::stitch_ui::material_frame_over(ui,super::stitch_ui::overlay_frame(ui.ctx(), super::stitch_ui::SurfaceRole::Menu, visual.opacity),
|
||||
super::stitch_ui::menu_base(), super::stitch_ui::menu_rim(Tokens::get(ui.ctx()).agent()), |ui| {
|
||||
super::stitch_ui::overlay_contents(ui, visual, |ui| super::stitch_ui::scope(ui, |ui| {
|
||||
constrain_candidate_menu_width(ui);
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
for (label, enabled) in &menu.rows {
|
||||
super::stitch_ui::menu_item(ui, label, *enabled);
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
} else {
|
||||
self.canvas_workspace.candidate_menu = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn workspace_canvas_allowed(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, doc_id: u64) -> bool {
|
||||
if self.professional_mode {
|
||||
self.canvas_workspace.clear_canvas_geometry();
|
||||
if let Some(menu) = self.canvas_workspace.candidate_menu.take() {
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if self.library || self.material || (self.creation_open && self.creation_step != 3) {
|
||||
self.canvas_workspace.clear_canvas_geometry();
|
||||
if let Some(menu) = self.canvas_workspace.candidate_menu.take() {
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if app.session.active().is_none_or(|state| state.doc.id.0 != doc_id) || !self.enforce_canvas_scope(app)
|
||||
|| self.canvas_workspace.scope_blocked {
|
||||
self.canvas_workspace.clear_canvas_geometry();
|
||||
if let Some(menu) = self.canvas_workspace.candidate_menu.take() {
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,170 @@
|
||||
use super::super::{LayerContent, Document, Value};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) fn document_mapping_arc(doc: &Document) -> Option<std::sync::Arc<Value>> {
|
||||
use std::cell::RefCell;
|
||||
struct CachedMapping {
|
||||
pub(crate) doc_id: u64,
|
||||
pub(crate) raw: String,
|
||||
pub(crate) value: Option<std::sync::Arc<Value>>,
|
||||
}
|
||||
thread_local! {
|
||||
static CACHE: RefCell<Option<CachedMapping>> = const { RefCell::new(None) };
|
||||
}
|
||||
let (_, raw) = doc.metadata.text.iter().find(|(key, _)| key == "jiansun.slot-mapping.v1")?;
|
||||
CACHE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
if let Some(cached) = guard.as_ref()
|
||||
&& cached.doc_id == doc.id.0
|
||||
&& cached.raw == raw.as_str()
|
||||
{
|
||||
return cached.value.clone();
|
||||
}
|
||||
let parsed = serde_json::from_str::<Value>(raw).ok().map(std::sync::Arc::new);
|
||||
*guard = Some(CachedMapping {
|
||||
doc_id: doc.id.0,
|
||||
raw: raw.clone(),
|
||||
value: parsed.clone(),
|
||||
});
|
||||
parsed
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn document_mapping(doc: &Document) -> Option<Value> {
|
||||
document_mapping_arc(doc).map(|v| (*v).clone())
|
||||
}
|
||||
|
||||
pub(crate) fn document_scope_matches(doc: &Document, workflow: &Value, output: &str, variant: &str) -> bool {
|
||||
document_mapping_arc(doc).is_some_and(|mapping| mapping["canvasFirst"] == true
|
||||
&& mapping["workspaceId"].is_string() && mapping["workspaceId"] == workflow["workspaceId"]
|
||||
&& mapping["component"] == output && mapping["variantId"] == variant)
|
||||
}
|
||||
|
||||
pub(crate) fn native_layer(doc: &Document, slot: &str) -> Option<u64> {
|
||||
native_layers(doc).get(slot).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn native_layers_from_mapping(mapping: &Value) -> BTreeMap<String, u64> {
|
||||
mapping["fields"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(mapping["outputs"].as_array().into_iter().flatten().flat_map(|o| o["mapping"]["fields"].as_array().into_iter().flatten()))
|
||||
.filter_map(|field| Some((field["slotId"].as_str()?.to_owned(), field["nativeLayerId"].as_u64()?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn native_layers(doc: &Document) -> BTreeMap<String, u64> {
|
||||
document_mapping_arc(doc).as_deref().map(native_layers_from_mapping).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) struct FrameDocIndex<'a> {
|
||||
pub(crate) layers: HashMap<u64, &'a photocraft_doc::Layer>,
|
||||
pub(crate) adopted_slots: HashSet<&'a str>,
|
||||
pub(crate) manual_image_slots: HashSet<&'a str>,
|
||||
pub(crate) processed_layers: HashSet<u64>,
|
||||
pub(crate) hidden_sample_layers: HashSet<u64>,
|
||||
}
|
||||
|
||||
impl<'a> FrameDocIndex<'a> {
|
||||
pub(crate) fn build(doc: &'a Document, variant: &str, mapping: Option<&Value>) -> Self {
|
||||
fn collect_layers<'b>(layers: &'b [photocraft_doc::Layer], out: &mut HashMap<u64, &'b photocraft_doc::Layer>) {
|
||||
for layer in layers {
|
||||
out.insert(layer.id.0, layer);
|
||||
if let Some(children) = layer.children() {
|
||||
collect_layers(children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut layers = HashMap::new();
|
||||
collect_layers(&doc.layers, &mut layers);
|
||||
|
||||
let mut adopted_slots = HashSet::new();
|
||||
let mut manual_image_slots = HashSet::new();
|
||||
let mut processed_layers = HashSet::new();
|
||||
for (key, value) in &doc.metadata.text {
|
||||
if let Some(rest) = key.strip_prefix("jiansun.adopted.")
|
||||
&& let Some(slot) = rest.strip_prefix(variant).and_then(|s| s.strip_prefix('.'))
|
||||
{
|
||||
adopted_slots.insert(slot);
|
||||
} else if let Some(rest) = key.strip_prefix("jiansun.manual-image.")
|
||||
&& let Some(slot) = rest.strip_prefix(variant).and_then(|s| s.strip_prefix('.'))
|
||||
&& serde_json::from_str::<Value>(value).ok().is_some_and(|v| v["sha256"].is_string())
|
||||
{
|
||||
manual_image_slots.insert(slot);
|
||||
} else if let Some(id_str) = key.strip_prefix("jiansun.processed.")
|
||||
&& let Ok(id) = id_str.parse::<u64>()
|
||||
{
|
||||
processed_layers.insert(id);
|
||||
}
|
||||
}
|
||||
|
||||
let mut hidden_counts: HashMap<u64, Option<bool>> = HashMap::new();
|
||||
if let Some(mapping) = mapping {
|
||||
let root = mapping["fields"].as_array().into_iter().flatten();
|
||||
let pages = mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten());
|
||||
for field in root.chain(pages) {
|
||||
if let Some(id) = field["nativeLayerId"].as_u64() {
|
||||
let is_hidden = field["hiddenTemplateSample"] == true;
|
||||
hidden_counts
|
||||
.entry(id)
|
||||
.and_modify(|state| *state = None)
|
||||
.or_insert(Some(is_hidden));
|
||||
}
|
||||
}
|
||||
}
|
||||
let hidden_sample_layers = hidden_counts
|
||||
.into_iter()
|
||||
.filter_map(|(id, state)| (state == Some(true)).then_some(id))
|
||||
.collect();
|
||||
|
||||
Self { layers, adopted_slots, manual_image_slots, processed_layers, hidden_sample_layers }
|
||||
}
|
||||
|
||||
pub(crate) fn is_hidden_unfilled_sample(&self, layer: &photocraft_doc::Layer, slot: &str) -> bool {
|
||||
!layer.visible
|
||||
&& !self.adopted_slots.contains(slot)
|
||||
&& !self.manual_image_slots.contains(slot)
|
||||
&& self.hidden_sample_layers.contains(&layer.id.0)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn adopted<'a>(doc: &'a Document, slot: &str, variant: &str) -> Option<&'a str> {
|
||||
let key = format!("jiansun.adopted.{variant}.{slot}");
|
||||
doc.metadata.text.iter().find(|(k, _)| *k == key).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn manual_image(doc: &Document, slot: &str, variant: &str) -> Option<Value> {
|
||||
let key = format!("jiansun.manual-image.{variant}.{slot}");
|
||||
let (_, value) = doc.metadata.text.iter().find(|(name, _)| *name == key)?;
|
||||
serde_json::from_str(value).ok().filter(|value: &Value| value["sha256"].is_string())
|
||||
}
|
||||
|
||||
pub(crate) fn hidden_unfilled_sample(doc: &Document, layer: &photocraft_doc::Layer, slot: &str, variant: &str) -> bool {
|
||||
!layer.visible && adopted(doc, slot, variant).is_none() && manual_image(doc, slot, variant).is_none()
|
||||
&& super::agent_canvas_read::template_field(doc, layer)["hiddenTemplateSample"] == true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn processing_status(doc: &Document, field: &Value, variant: &str, messages: &[Value]) -> &'static str {
|
||||
let layer=field["nativeLayerId"].as_u64().unwrap_or(0);
|
||||
let key=format!("jiansun.processed.{layer}");
|
||||
if doc.metadata.text.iter().any(|(name,_)|name==&key)
|
||||
|| field["slotId"].as_str().and_then(|slot|adopted(doc,slot,variant)).is_some() {
|
||||
return "小壹已处理";
|
||||
}
|
||||
if let Some(node)=doc.layer(photocraft_doc::LayerId(layer))
|
||||
&& let LayerContent::Text(text)=&node.content {
|
||||
if messages.iter().filter(|message|message["kind"]=="copywriting-fields")
|
||||
.flat_map(|message|message["items"].as_array().into_iter().flatten())
|
||||
.any(|item|item["layer"].as_u64()==Some(layer) && item["field"]["slotId"]==field["slotId"] && item["applied"]==true && item["text"]==text.text && item["original"]!=text.text) {
|
||||
return "小壹已处理";
|
||||
}
|
||||
if field["originalText"].as_str().is_some_and(|original|text.text!=original) {return "已修改";}
|
||||
}
|
||||
"原稿 · 未处理"
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,472 @@
|
||||
use super::super::{json, Instant, PhotocraftApp, Request, Value, Workspace};
|
||||
use super::document::{adopted, document_mapping, document_mapping_arc, document_scope_matches, manual_image};
|
||||
use super::projection::{
|
||||
candidates, receipt_matches_target, rows, same_generation_target, scope, scoped_candidate_ids,
|
||||
short_slot_label, target_summary, GenerationIdentity, SubmittedComposer, SubmittedRegen,
|
||||
};
|
||||
use super::{bound_project, State};
|
||||
use egui::Rect;
|
||||
use std::collections::HashSet;
|
||||
|
||||
impl State {
|
||||
/// Read the immutable image-generation target, never the current canvas
|
||||
/// selection. A changed document/account/origin cannot borrow the old task.
|
||||
pub(crate) fn submitted_generation_target(&self, account: &Value, origin: &str, doc: Option<u64>) -> Option<&Value> {
|
||||
account.as_str().filter(|value| !value.is_empty())?;
|
||||
let binding = format!("{}|{}|{}", account, origin, doc?);
|
||||
if self.binding != binding {
|
||||
return None;
|
||||
}
|
||||
self.submitted_composer.as_ref().map(|submitted| &submitted.target).or_else(|| self.submitted_regen.as_ref().map(|submitted| &submitted.target))
|
||||
}
|
||||
|
||||
pub(crate) fn composer_edited(&mut self) {
|
||||
self.composer_edit_version = self.composer_edit_version.wrapping_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn regen_edited(&mut self) {
|
||||
self.regen_edit_version = self.regen_edit_version.wrapping_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn generation_submission_failed(&mut self, error: &str) {
|
||||
self.submitted_composer = None;
|
||||
if let Some(submitted) = self.submitted_regen.take()
|
||||
&& self.is_current_regen(&submitted)
|
||||
{
|
||||
self.regen_error = error.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_current_regen(&self, submitted: &SubmittedRegen) -> bool {
|
||||
self.regen_session == submitted.session
|
||||
&& self.regen_edit_version == submitted.edit_version
|
||||
&& self.prompt == submitted.text
|
||||
&& self.regen.as_ref().is_some_and(|current| same_generation_target(&submitted.target, current))
|
||||
}
|
||||
|
||||
pub(crate) fn close_dispatched_regen(&mut self, candidate: &Value) {
|
||||
if let Some(submitted) = self.submitted_regen.as_ref()
|
||||
&& submitted.identity.matches(candidate, &submitted.target)
|
||||
&& self.is_current_regen(submitted)
|
||||
{
|
||||
self.regen_drafts.remove(&self.draft_key(&submitted.target));
|
||||
self.regen = None;
|
||||
self.prompt.clear();
|
||||
self.regen_error.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_regen_submission(&mut self, candidate: &Value, complete: bool, error: Option<&str>) {
|
||||
if complete {
|
||||
self.close_dispatched_regen(candidate);
|
||||
}
|
||||
if let Some(submitted) = self.submitted_regen.take_if(|submitted| submitted.identity.matches(candidate, &submitted.target))
|
||||
&& self.is_current_regen(&submitted)
|
||||
&& let Some(error) = error
|
||||
{
|
||||
self.regen_error = error.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn image_dispatched(&mut self, progress: &Value) {
|
||||
let candidate = json!({"id":progress["taskId"],"slotId":progress["slotId"],"variantId":progress["variantId"]});
|
||||
self.close_dispatched_regen(&candidate);
|
||||
}
|
||||
|
||||
pub(crate) fn expect_fresh_preview(&mut self, id: &str) {
|
||||
if id.is_empty() || self.pending_entry.contains(id) || self.appeared.contains_key(id) {
|
||||
return;
|
||||
}
|
||||
if self.pending_entry.len() >= 128 {
|
||||
self.pending_entry.clear();
|
||||
}
|
||||
self.pending_entry.insert(id.to_owned());
|
||||
}
|
||||
|
||||
pub(crate) fn preview_arrival(&self, id: &str) -> Option<f64> {
|
||||
self.appeared.get(id).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn preview_arrived(&mut self, id: &str, now: f64) {
|
||||
if self.pending_entry.remove(id) && now.is_finite() {
|
||||
self.appeared.retain(|_, started| now - *started < 0.3);
|
||||
if self.appeared.len() >= 128 {
|
||||
self.appeared.clear();
|
||||
}
|
||||
self.appeared.insert(id.to_owned(), now);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn remember_native_selection(&mut self, app: &PhotocraftApp) {
|
||||
self.selection = app.session.active().map(|state| state.selected_layers().iter().map(|id| id.0).collect()).unwrap_or_default();
|
||||
self.locate_request = None;
|
||||
self.locate_motion = None;
|
||||
self.locate_highlight = None;
|
||||
}
|
||||
|
||||
pub(crate) fn active_candidate_target(&self, workflow: &Value) -> Value {
|
||||
workflow["slots"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|slot| {
|
||||
let candidate = candidates(slot)
|
||||
.iter()
|
||||
.find(|candidate| ["id", "taskId"].iter().filter_map(|key| candidate[*key].as_str()).any(|id| self.progress.contains_key(id)))?;
|
||||
let variant = candidate["variantId"].as_str().or(slot["variantId"].as_str()).unwrap_or(&self.variant);
|
||||
Some(target_summary(&scope(slot, Some(candidate), variant, "")))
|
||||
})
|
||||
.unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
pub(crate) fn draft_key(&self, target: &Value) -> String {
|
||||
format!("{}|{}|{}|{}", self.binding, target["productVariantId"], target["slotId"], target["candidateId"])
|
||||
}
|
||||
pub(crate) fn invalidate_regen(&mut self) {
|
||||
self.regen_selected_refs.clear();
|
||||
self.regen_use_template_base = false;
|
||||
self.regen_picking_original = false;
|
||||
if let Some(target) = self.regen.take() {
|
||||
self.regen_drafts.insert(self.draft_key(&target), self.prompt.clone());
|
||||
}
|
||||
self.prompt.clear();
|
||||
self.regen_error.clear();
|
||||
}
|
||||
pub(crate) fn open_regen(&mut self, target: Value, workflow: &Value) {
|
||||
self.invalidate_regen();
|
||||
self.regen_session = self.regen_session.wrapping_add(1);
|
||||
self.regen_edit_version = 0;
|
||||
self.prompt = self.regen_drafts.get(&self.draft_key(&target)).cloned().unwrap_or_default();
|
||||
if let Some(items) = workflow["productReferences"].as_array() {
|
||||
for (fallback_idx, item) in items.iter().enumerate() {
|
||||
if item["purpose"] == "product" {
|
||||
let idx = item["index"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(fallback_idx);
|
||||
self.regen_selected_refs.insert(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.regen = Some(target);
|
||||
}
|
||||
pub(crate) fn regeneration_input(&self, workflow: &Value) -> Result<Value, String> {
|
||||
let target = self.regen.as_ref().ok_or("没有待提交的图片目标")?;
|
||||
if target["productVariantId"] != self.variant
|
||||
|| target["outputId"] != self.output
|
||||
|| !workflow["slots"].as_array().is_some_and(|rows| rows.iter().any(|s| s["id"] == target["slotId"] && s["outputId"] == self.output))
|
||||
{
|
||||
return Err("图片或花色已切换,要求已保留,请在当前图片重新打开生成".into());
|
||||
}
|
||||
let mut request = json!({
|
||||
"slotId": target["slotId"],
|
||||
"variantId": target["productVariantId"],
|
||||
"instructions": self.prompt,
|
||||
"replaceTemplatePrompt": true,
|
||||
"manualImage": true,
|
||||
"useTemplateBase": self.regen_use_template_base,
|
||||
});
|
||||
if !self.regen_selected_refs.is_empty() {
|
||||
let indices: Vec<usize> = self.regen_selected_refs.iter().copied().collect();
|
||||
request["referenceIndexes"] = json!(indices);
|
||||
}
|
||||
if target["nativeLayerId"].is_u64() {
|
||||
request["nativeLayerId"] = target["nativeLayerId"].clone();
|
||||
}
|
||||
if target["candidateId"].is_string() {
|
||||
request["parentCandidateId"] = target["candidateId"].clone();
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
pub(crate) fn take_product_original_adopt(&mut self, receipt: &Value) -> Option<Value> {
|
||||
let candidate = &receipt["candidateResult"];
|
||||
if candidate["status"] != "complete" || candidate["sourceType"] != "product-reference" {
|
||||
return None;
|
||||
}
|
||||
let candidate_id = candidate["id"].as_str()?;
|
||||
let pending = self.pending_product_original_adopt.as_ref()?;
|
||||
if pending["doc"] != receipt["doc"]
|
||||
|| pending["slotId"] != candidate["slotId"]
|
||||
|| pending["variantId"] != candidate["variantId"]
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let pending = self.pending_product_original_adopt.take()?;
|
||||
let mut adopt = json!({
|
||||
"slotId": pending["slotId"],
|
||||
"candidateId": candidate_id,
|
||||
"variantId": pending["variantId"],
|
||||
});
|
||||
if pending["nativeLayerId"].is_u64() {
|
||||
adopt["nativeLayerId"] = pending["nativeLayerId"].clone();
|
||||
}
|
||||
Some(adopt)
|
||||
}
|
||||
pub(crate) fn inspect(&self) -> Value {
|
||||
json!({"context":self.context,"outputId":self.output,"variantId":self.variant,"geometry":self.geometry,"professionalControls":self.professional_controls,"regenerateOpen":self.regen.is_some(),"scopeReady":!self.scope_blocked,"adoptionPending":self.pending_adoption.is_some(),"adoptionPreparing":self.adoption_preparing()})
|
||||
}
|
||||
|
||||
/// Called with the native dock's other per-frame geometry reset. Hidden
|
||||
/// navigation and toolbar controls must never leave clickable old bounds.
|
||||
pub(crate) fn clear_frame_geometry(&mut self) {
|
||||
self.geometry.clear();
|
||||
self.professional_controls.clear();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_canvas_geometry(&mut self) {
|
||||
// The workspace chrome is laid out before the document overlays.
|
||||
self.geometry.retain(|name, _| {
|
||||
matches!(name.as_str(), "professionalEnter" | "professionalApply" | "professionalReturn"
|
||||
| "referenceDock" | "referenceDockPopover" | "productDockToggle" | "imageResourcesToggle")
|
||||
|| name.starts_with("product-dock:")
|
||||
});
|
||||
}
|
||||
|
||||
/// 收纳坞浮在画布上:落在按钮组或打开的浮层里的指针,不属于下面的图片与卡片。
|
||||
pub(crate) fn on_canvas(&self, canvas: Rect, point: egui::Pos2) -> bool {
|
||||
canvas.contains(point) && !self.reference_dock_cover.iter().any(|rect| rect.contains(point))
|
||||
}
|
||||
|
||||
pub(crate) fn adoption_preparing(&self) -> bool { self.adoption_worker.is_some() }
|
||||
|
||||
pub(crate) fn finish_reference_intro(&mut self) {
|
||||
if self.reference_intro {
|
||||
self.reference_intro = false;
|
||||
self.reference_cards.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bind(&mut self, binding: String, workflow: &Value) {
|
||||
if self.binding == binding {
|
||||
return;
|
||||
}
|
||||
self.invalidate_regen();
|
||||
let regen_drafts = std::mem::take(&mut self.regen_drafts);
|
||||
let output = workflow["outputId"].as_str().unwrap_or(if self.output.is_empty() { "detail" } else { &self.output }).to_owned();
|
||||
*self = Self { binding, output, variant: workflow["variantId"].as_str().unwrap_or("").into(), initial_focus: true, regen_drafts, ..Self::default() };
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn canvas_scope_valid(&self, app: &PhotocraftApp) -> bool {
|
||||
let Some(state) = app.session.active() else { return false; };
|
||||
if self.professional_child_active(app) || self.production_canvas_unbound(app) { return false; }
|
||||
let mapping = document_mapping_arc(&state.doc);
|
||||
if let Some(binding) = self.product_production.as_ref().and_then(super::product_production::Run::working_output)
|
||||
.filter(|_| self.pi_product_production)
|
||||
{
|
||||
let Some(mapping) = mapping else { return self.template_workflow["canvasFirst"] != true; };
|
||||
return mapping["component"] == binding["outputId"] && mapping["variantId"] == binding["variantId"]
|
||||
&& self.conversation_canvas_mapping(&state.doc).is_some();
|
||||
}
|
||||
match mapping {
|
||||
Some(mapping) if mapping["canvasFirst"] == true => self.conversation_canvas_mapping(&state.doc).is_some(),
|
||||
_ => self.template_workflow["canvasFirst"] != true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn toolbar_output_and_variant(&self, app: &PhotocraftApp) -> (String, String) {
|
||||
let doc_mapping = app.session.active().and_then(|state| document_mapping(&state.doc));
|
||||
fn non_empty(value: Option<&str>) -> Option<&str> {
|
||||
value.filter(|text| !text.is_empty())
|
||||
}
|
||||
let output = (!self.canvas_workspace.scope_blocked)
|
||||
.then(|| non_empty(Some(self.canvas_workspace.output.as_str())))
|
||||
.flatten()
|
||||
.or_else(|| non_empty(doc_mapping.as_ref().and_then(|mapping| mapping["component"].as_str())))
|
||||
.or_else(|| non_empty(Some(self.canvas_workspace.output.as_str())))
|
||||
.or_else(|| non_empty(self.template_workflow["outputId"].as_str()))
|
||||
.unwrap_or("detail")
|
||||
.to_owned();
|
||||
let variant = (!self.canvas_workspace.scope_blocked)
|
||||
.then(|| non_empty(Some(self.canvas_workspace.variant.as_str())))
|
||||
.flatten()
|
||||
.or_else(|| non_empty(doc_mapping.as_ref().and_then(|mapping| mapping["variantId"].as_str())))
|
||||
.or_else(|| non_empty(Some(self.canvas_workspace.variant.as_str())))
|
||||
.or_else(|| non_empty(self.template_workflow["variantId"].as_str()))
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
(output, variant)
|
||||
}
|
||||
|
||||
pub(crate) fn enforce_canvas_scope(&mut self, app: &PhotocraftApp) -> bool {
|
||||
// The editor's controls may still describe the last viewed output. Hide those
|
||||
// controls until their projection catches up, while writes use the actual target.
|
||||
if self.professional_child_active(app) || self.production_canvas_unbound(app) { return false; }
|
||||
let valid = self.canvas_scope_valid(app);
|
||||
let view_matches = self.template_workflow["canvasFirst"] != true
|
||||
|| app.session.active().is_some_and(|state| {
|
||||
let output = self.template_workflow["outputId"].as_str().unwrap_or("");
|
||||
let variant = self.template_workflow["variantId"].as_str().unwrap_or("");
|
||||
document_scope_matches(&state.doc, &self.template_workflow, output, variant)
|
||||
});
|
||||
if valid && view_matches {
|
||||
if let Some(state) = app.session.active().filter(|_| self.template_workflow["canvasFirst"] == true) {
|
||||
self.canvas_workspace.bind(format!("{}|{}|{}", self.account["id"], self.origin, state.doc.id.0), &self.template_workflow);
|
||||
}
|
||||
self.canvas_workspace.scope_blocked = false;
|
||||
return true;
|
||||
}
|
||||
self.canvas_workspace.scope_blocked = true;
|
||||
self.canvas_workspace.context = None;
|
||||
self.canvas_workspace.locate_request = None;
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
self.canvas_workspace.locate_highlight = None;
|
||||
self.canvas_workspace.invalidate_regen();
|
||||
if !valid || self.canvas_workspace.pending_adoption.as_ref().is_some_and(|pending| !pending["workflowRun"].is_string()) {
|
||||
self.canvas_workspace.pending_adoption = None;
|
||||
self.canvas_workspace.manual_adoption_basis = None;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.cancel_preview_export();
|
||||
self.canvas_workspace.submitted_composer = None;
|
||||
self.canvas_workspace.submitted_regen = None;
|
||||
self.canvas_workspace.clear_canvas_geometry();
|
||||
self.canvas_workspace.initial_focus = false;
|
||||
valid
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_generate_selected(&mut self, app: &PhotocraftApp) -> Result<(), String> {
|
||||
if !self.enforce_canvas_scope(app) {
|
||||
return Err("画布与当前模板或花色不一致,请重新选择输出或花色;原编辑已保留".into());
|
||||
}
|
||||
let target = self.canvas_workspace.context.clone().ok_or("先选择要生成的图片图位")?;
|
||||
if target["kind"] == "selection" {
|
||||
return Err("已选择多个对象,请先选择一个图片图位再生成候选".into());
|
||||
}
|
||||
let slot = target["slotId"].as_str().ok_or("先选择要生成的图片图位")?;
|
||||
if target["productVariantId"] != self.canvas_workspace.variant {
|
||||
return Err("花色已变化,请重新选择图片".into());
|
||||
}
|
||||
let text = self.composer.clone();
|
||||
let mut input = json!({"slotId":slot,"variantId":self.canvas_workspace.variant,"instructions":text,"nativeLayerId":target["nativeLayerId"]});
|
||||
if target["candidateId"].is_string() {
|
||||
input["parentCandidateId"] = target["candidateId"].clone();
|
||||
}
|
||||
let attachments = self.composer_attachment_snapshot(app)?;
|
||||
if !attachments.is_empty() {
|
||||
input["attachments"] = json!(attachments);
|
||||
input["projectId"] = json!(self.composer_attachment_project(app)?);
|
||||
}
|
||||
self.slot_action(app, "slot-append", input)?;
|
||||
self.composer_reference_clear(app);
|
||||
self.canvas_workspace.submitted_regen = None;
|
||||
self.canvas_workspace.submitted_composer = Some(SubmittedComposer {
|
||||
edit_version: self.canvas_workspace.composer_edit_version,
|
||||
target: target_summary(&target),
|
||||
text: text.clone(),
|
||||
identity: GenerationIdentity::new(&self.template_workflow, &target),
|
||||
});
|
||||
self.messages.push(json!({"role":"user","text":text,"target":target}));
|
||||
self.draft_changed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn submit_regeneration(&mut self, app: &PhotocraftApp) -> Result<(), String> {
|
||||
let target = self.canvas_workspace.regen.clone().ok_or("没有待提交的图片目标")?;
|
||||
let request = self.canvas_workspace.regeneration_input(&self.template_workflow)?;
|
||||
self.slot_action(app, "slot-append", request)?;
|
||||
self.canvas_workspace.submitted_composer = None;
|
||||
self.canvas_workspace.submitted_regen = Some(SubmittedRegen {
|
||||
session: self.canvas_workspace.regen_session,
|
||||
edit_version: self.canvas_workspace.regen_edit_version,
|
||||
target: target_summary(&target),
|
||||
text: self.canvas_workspace.prompt.clone(),
|
||||
identity: GenerationIdentity::new(&self.template_workflow, &target),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_opened(&mut self, meta: &Value) {
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.canvas_workspace.invalidate_regen();
|
||||
self.canvas_workspace.output = meta["outputId"].as_str().or(meta["component"].as_str()).unwrap_or("detail").into();
|
||||
self.canvas_workspace.variant = meta["variantId"].as_str().unwrap_or("").into();
|
||||
self.canvas_workspace.context = None;
|
||||
self.canvas_workspace.initial_focus = true;
|
||||
self.creation_open = false;
|
||||
}
|
||||
|
||||
pub(crate) fn running_workflow_generation(&self, doc: u64) -> Option<&Value> {
|
||||
self.workflow.running_generation(self.pi_run.as_deref(), &self.account["id"], &self.origin,
|
||||
doc, bound_project(self, doc))
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_receipt(&mut self, method: &str, value: &Value) {
|
||||
let candidate = &value["candidateResult"];
|
||||
if method == "slot-progress" {
|
||||
self.workflow.generation_prepared(value);
|
||||
if let Some(submitted) = self.canvas_workspace.submitted_regen.as_mut() {
|
||||
submitted.identity.bind_prepared(&value["workflow"], &submitted.target);
|
||||
}
|
||||
if let Some(submitted) = self.canvas_workspace.submitted_composer.as_mut() {
|
||||
submitted.identity.bind_prepared(&value["workflow"], &submitted.target);
|
||||
}
|
||||
}
|
||||
if let Some(id) = candidate["id"].as_str() {
|
||||
self.canvas_workspace.progress.remove(id);
|
||||
let finished = match candidate["status"].as_str() {
|
||||
Some("failed" | "rejected" | "not_dispatched") => Some("生成未完成"),
|
||||
Some("unknown") => Some("等待原请求结果"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(job) = self.messages.iter_mut().rev().find(|item| item["kind"] == "image-job" && item["taskId"] == id)
|
||||
&& let Some(label) = finished
|
||||
{
|
||||
job["finished"] = json!(label);
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
if matches!(method, "slot-append" | "slot-recover") && candidate["status"] == "complete" && candidate["id"].is_string() {
|
||||
if method == "slot-append"
|
||||
&& let Some(id) = candidate["id"].as_str()
|
||||
&& !self.agent_images.contains_key(id)
|
||||
{
|
||||
self.canvas_workspace.expect_fresh_preview(id);
|
||||
}
|
||||
if candidate["sourceType"] != "product-reference" {
|
||||
let fresh = !self.messages.iter().any(|message| message["kind"] == "image" && message["taskId"] == candidate["id"]);
|
||||
self.register_image(json!({"doc":value["doc"],"taskId":candidate["id"],"slotId":candidate["slotId"],"variantId":candidate["variantId"]}));
|
||||
if fresh && let Some(doc) = value["doc"].as_u64() {
|
||||
self.queue_canvas_feedback(doc, json!({"slotId":candidate["slotId"],"locateImageSlot":true}), "图片已生成");
|
||||
}
|
||||
}
|
||||
}
|
||||
if method == "slot-append" {
|
||||
let complete = value["error"].is_null() && candidate["status"] == "complete";
|
||||
self.canvas_workspace.finish_regen_submission(candidate, complete, value["error"].as_str());
|
||||
if let Some(submitted) = self.canvas_workspace.submitted_composer.take_if(|submitted| submitted.identity.matches(candidate, &submitted.target))
|
||||
&& complete
|
||||
&& self.canvas_workspace.composer_edit_version == submitted.edit_version
|
||||
&& self.composer == submitted.text
|
||||
&& self.canvas_workspace.context.as_ref().is_some_and(|current| same_generation_target(&submitted.target, current))
|
||||
{
|
||||
self.composer.clear();
|
||||
self.canvas_workspace.composer_edited();
|
||||
self.draft_changed = true;
|
||||
self.touched = Instant::now();
|
||||
}
|
||||
}
|
||||
// A task receipt updates its original candidate, never the user's view.
|
||||
// Only an acknowledged skeleton switch or initial document bind navigates.
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn slot_generation_busy(&self, target: &Value) -> bool {
|
||||
if self.canvas_workspace.submitted_regen.as_ref().is_some_and(|submitted| same_generation_target(&submitted.target, target)) {
|
||||
return true;
|
||||
}
|
||||
let slot_id = target["slotId"].as_str().unwrap_or_default();
|
||||
let output_id = target["outputId"].as_str().unwrap_or_default();
|
||||
let variant_id = target["productVariantId"].as_str().unwrap_or_default();
|
||||
self.template_workflow["slots"].as_array().into_iter().flatten()
|
||||
.find(|slot| slot["id"] == slot_id && slot["outputId"] == output_id && slot["variantId"] == variant_id)
|
||||
.is_some_and(|slot| {
|
||||
candidates(slot).iter().any(|candidate| {
|
||||
matches!(candidate["status"].as_str(), Some("prepared" | "dispatched" | "running"))
|
||||
|| ["id", "taskId"].iter().filter_map(|key| candidate[*key].as_str())
|
||||
.any(|id| self.canvas_workspace.progress.contains_key(id))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,656 @@
|
||||
use super::super::{Document, LayerContent, json, Instant, PhotocraftApp, Request, Tokens, Ui, Value, Workspace};
|
||||
use super::super::stitch_ui as kit;
|
||||
use super::candidate_menu_ui::{constrain_candidate_menu_width, CandidateDrawInput, SlotDrawInput};
|
||||
use super::document::{
|
||||
adopted, document_mapping, document_mapping_arc, document_scope_matches, manual_image,
|
||||
native_layers_from_mapping, FrameDocIndex,
|
||||
};
|
||||
use super::projection::{
|
||||
blank_selection_gesture, candidate_group, candidate_group_label, candidate_is_running,
|
||||
candidates, card, card_size, fit_tag_selection, frame, includes_target, location,
|
||||
native_content_at, native_selection_subject, rows, same_generation_target, scope,
|
||||
short_slot_label, slot_hit_is_obscured, status, target_summary, world_rect, Row,
|
||||
};
|
||||
use super::{bound_project, CameraRequest, CARD_GAP, CARD_WIDTH, GAP};
|
||||
use crate::canvas::ViewXform;
|
||||
use egui::{Color32, FontId, Rect, Sense, Stroke, pos2, vec2};
|
||||
use photocraft_engine::jobs::JobId;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct DirectImageDrag {
|
||||
pub(crate) layer: u64,
|
||||
pub(crate) revision: u64,
|
||||
pub(crate) start: [f64; 2],
|
||||
pub(crate) bounds: [f32; 4],
|
||||
}
|
||||
|
||||
pub(crate) struct CanvasImageTransform {
|
||||
pub(crate) job: JobId,
|
||||
pub(crate) doc: photocraft_doc::DocId,
|
||||
pub(crate) revision: u64,
|
||||
pub(crate) layer: u64,
|
||||
pub(crate) queued: Option<[f64; 6]>,
|
||||
}
|
||||
|
||||
pub(crate) fn image_affine(scale: f64, pivot: [f64; 2], delta: [f64; 2]) -> [f64; 6] {
|
||||
[scale, 0.0, 0.0, scale, pivot[0] * (1.0 - scale) + delta[0], pivot[1] * (1.0 - scale) + delta[1]]
|
||||
}
|
||||
|
||||
fn image_wheel_modifier(modifiers: egui::Modifiers) -> bool {
|
||||
modifiers.alt || modifiers.ctrl
|
||||
}
|
||||
|
||||
pub(crate) fn take_image_wheel(ui: &Ui) -> f32 {
|
||||
ui.input_mut(|input| {
|
||||
let mut scroll = 0.0;
|
||||
input.events.retain(|event| {
|
||||
if let egui::Event::MouseWheel { unit, delta, modifiers, .. } = event
|
||||
&& image_wheel_modifier(*modifiers)
|
||||
&& delta.y != 0.0 && delta.y.abs() >= delta.x.abs()
|
||||
{
|
||||
scroll += delta.y * if *unit == egui::MouseWheelUnit::Line { 40.0 } else { 1.0 };
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
// The input state can continue emitting the tail of a notch on frames
|
||||
// with no new event. It belongs to the image while the pointer is over it.
|
||||
if image_wheel_modifier(input.modifiers) && input.smooth_scroll_delta.y.abs() >= input.smooth_scroll_delta.x.abs() {
|
||||
input.smooth_scroll_delta.y = 0.0;
|
||||
}
|
||||
scroll
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn reference_scale(card: &mut [f32; 4], anchor: [f64; 2], factor: f32) {
|
||||
let side = card[2].max(card[3]);
|
||||
let scale = (side * factor).clamp(120.0, 3200.0) / side;
|
||||
for i in 0..2 {
|
||||
card[i] = anchor[i] as f32 + (card[i] - anchor[i] as f32) * scale;
|
||||
card[i + 2] *= scale;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reference_preview_edge(rect: Rect, pixels_per_point: f32) -> Option<u32> {
|
||||
let edge = rect.width().max(rect.height()) * pixels_per_point;
|
||||
if edge <= 320.0 {
|
||||
return None;
|
||||
}
|
||||
Some(if edge <= 1024.0 { 1024 } else if edge <= 2048.0 { 2048 } else { 4096 })
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn edit_canvas_image(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, xf: ViewXform, rows: &[Row<'_>], layers: &BTreeMap<String, u64>, enabled: bool) -> bool {
|
||||
if !enabled || app.ui.tool != crate::state::Tool::Move || app.ui.text_edit.is_some() || app.ui.transform.is_some()
|
||||
|| ui.input(|input| input.pointer.middle_down() || input.key_down(egui::Key::Space) || input.key_pressed(egui::Key::Escape)) {
|
||||
if self.canvas_workspace.direct_image_drag.take().is_some() { app.drag = None; }
|
||||
return false;
|
||||
}
|
||||
let Some(state) = app.session.active() else { return false };
|
||||
let revision = state.revision;
|
||||
let pointer = ui.input(|input| input.pointer.interact_pos()).filter(|point| self.canvas_workspace.on_canvas(xf.rect, *point));
|
||||
let target = pointer.and_then(|point| {
|
||||
let doc_point = xf.to_doc(point);
|
||||
let frame_hit = |row: &Row<'_>| frame(row).is_some_and(|[x, y, w, h]| {
|
||||
doc_point[0] >= f64::from(x) && doc_point[0] < f64::from(x+w)
|
||||
&& doc_point[1] >= f64::from(y) && doc_point[1] < f64::from(y+h)
|
||||
});
|
||||
let authored = rows.iter().rev().find(|row| frame_hit(row));
|
||||
rows.iter().rev().filter_map(|row| {
|
||||
if authored.is_some_and(|authored| authored.slot["id"] != row.slot["id"]) { return None; }
|
||||
let id = row.slot["nativeLayerId"].as_u64().or_else(|| layers.get(row.slot["id"].as_str()?).copied())?;
|
||||
let layer = state.doc.layer(photocraft_doc::LayerId(id))?;
|
||||
if slot_hit_is_obscured(&state.doc, doc_point, Some(layer.id)) { return None; }
|
||||
let locks = state.doc.effective_locks(layer.id);
|
||||
if !layer.visible || locks.position || locks.all || !matches!(layer.content, LayerContent::Smart(_)) { return None; }
|
||||
let bounds = photocraft_engine::transform_cmds::transform_frame(&state.doc, layer);
|
||||
if authored.is_none()
|
||||
&& let Some((left, top, right, bottom)) = layer.vector_mask.as_ref().filter(|mask| mask.enabled)
|
||||
.and_then(|mask| mask.path.control_bounds())
|
||||
&& (doc_point[0] < left || doc_point[0] >= right || doc_point[1] < top || doc_point[1] >= bottom)
|
||||
{ return None; }
|
||||
if bounds.is_empty() || doc_point[0] < f64::from(bounds.x0) || doc_point[0] >= f64::from(bounds.x1)
|
||||
|| doc_point[1] < f64::from(bounds.y0) || doc_point[1] >= f64::from(bounds.y1) { return None; }
|
||||
Some((id, [bounds.x0 as f32, bounds.y0 as f32, bounds.width() as f32, bounds.height() as f32]))
|
||||
}).next()
|
||||
});
|
||||
if self.canvas_workspace.direct_image_drag.is_some_and(|drag| drag.revision != revision) {
|
||||
self.canvas_workspace.direct_image_drag = None;
|
||||
app.drag = None;
|
||||
return true;
|
||||
}
|
||||
if let Some(drag) = self.canvas_workspace.direct_image_drag {
|
||||
let (down, released, position) = ui.input(|input| (input.pointer.primary_down(), input.pointer.primary_released(), input.pointer.interact_pos()));
|
||||
if let Some(position) = position {
|
||||
let current = xf.to_doc(position);
|
||||
let delta = [current[0] - drag.start[0], current[1] - drag.start[1]];
|
||||
if released && xf.map_vec(vec2(delta[0] as f32, delta[1] as f32)).length() >= 3.0 {
|
||||
self.commit_canvas_image_transform(app, drag.layer, image_affine(1.0, drag.start, delta));
|
||||
} else if down {
|
||||
if let Some(preview) = app.drag.as_mut() {
|
||||
preview.points.truncate(1);
|
||||
preview.points.push([current[0], current[1], 1.0]);
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
let mut bounds = drag.bounds;
|
||||
bounds[0] += delta[0] as f32;
|
||||
bounds[1] += delta[1] as f32;
|
||||
ui.painter_at(xf.rect).rect_stroke(world_rect(xf, bounds), 4.0, Stroke::new(1.5, Tokens::get(ui.ctx()).agent().accent), egui::StrokeKind::Inside);
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
}
|
||||
if !down { self.canvas_workspace.direct_image_drag = None; app.drag = None; }
|
||||
return true;
|
||||
}
|
||||
let (Some(position), Some((layer, bounds))) = (pointer, target) else { return false };
|
||||
let modifiers = ui.input(|input| input.modifiers);
|
||||
// Preserve ordinary canvas navigation and let a plain click select the image.
|
||||
if modifiers == egui::Modifiers::NONE && ui.input(|input| input.pointer.primary_pressed()) {
|
||||
if app.session.active_job().is_some() { return true; }
|
||||
if state.active_layer != Some(photocraft_doc::LayerId(layer)) || state.selected_layers().len() != 1 {
|
||||
if let Err(error) = app.session.select_layer(photocraft_doc::LayerId(layer)) { self.error = error.to_string(); return true; }
|
||||
app.sync_mask_targets();
|
||||
}
|
||||
let revision = app.session.active().map_or(revision, |state| state.revision);
|
||||
let start = xf.to_doc(position);
|
||||
self.canvas_workspace.direct_image_drag = Some(DirectImageDrag { layer, revision, start, bounds });
|
||||
if !app.layer_mask_targeted() {
|
||||
app.drag = Some(crate::canvas::Drag::new(crate::state::Tool::Move, start, vec![[start[0], start[1], 1.0]], egui::Modifiers::NONE, false));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if image_wheel_modifier(modifiers) && state.active_layer == Some(photocraft_doc::LayerId(layer)) {
|
||||
let scroll = take_image_wheel(ui);
|
||||
if scroll.abs() > 0.01 {
|
||||
let factor = f64::from((scroll * 0.003).exp().clamp(0.75, 1.33));
|
||||
self.commit_canvas_image_transform(app, layer, image_affine(factor, xf.to_doc(position), [0.0; 2]));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn commit_canvas_image_transform(&mut self, app: &mut PhotocraftApp, layer: u64, matrix: [f64; 6]) {
|
||||
let Some((doc, revision)) = app.session.active().map(|state| (state.doc.id, state.revision)) else { return };
|
||||
if let Some(job) = app.session.job_on(doc) {
|
||||
if let Some(pending) = self.canvas_workspace.image_transform.as_mut()
|
||||
&& pending.job == job.id && pending.layer == layer
|
||||
{
|
||||
pending.queued = Some(match pending.queued {
|
||||
// Each direct image gesture has uniform scale and translation. Compose wheel
|
||||
// ticks about their own pointer positions in the order the user made them.
|
||||
Some(first) => [
|
||||
matrix[0] * first[0], 0.0, 0.0, matrix[3] * first[3],
|
||||
matrix[0] * first[4] + matrix[4], matrix[3] * first[5] + matrix[5],
|
||||
],
|
||||
None => matrix,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
match app.run("edit.transform", json!({"layer":layer,"matrix":matrix})) {
|
||||
Ok(result) => {
|
||||
if let Some(job) = result["job"].as_u64() {
|
||||
self.canvas_workspace.image_transform = Some(CanvasImageTransform { job: JobId(job), doc, revision, layer, queued: None });
|
||||
} else {
|
||||
self.draft_changed = true;
|
||||
self.sync_dirty = true;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// The native command reports the desktop operation in the status bar.
|
||||
app.ui.status = "图片调整未完成,请查看画布状态后再试。".into();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_canvas_image_transform(&mut self, app: &mut PhotocraftApp, doc: u64) {
|
||||
let Some(pending) = self.canvas_workspace.image_transform.as_mut() else { return };
|
||||
if pending.doc.0 != doc {
|
||||
pending.queued = None;
|
||||
return;
|
||||
}
|
||||
if app.session.job(pending.job).is_some() { return; }
|
||||
let pending = self.canvas_workspace.image_transform.take().unwrap();
|
||||
let Some(job) = app.session.jobs_with_recent().into_iter().find(|job| job.id == pending.job && job.state == "done") else { return };
|
||||
self.draft_changed = true;
|
||||
self.sync_dirty = true;
|
||||
if let Some(matrix) = pending.queued
|
||||
&& app.session.active().is_some_and(|state| {
|
||||
state.doc.id == pending.doc && state.revision == job.after_revision.unwrap_or(pending.revision + 1)
|
||||
&& state.active_layer == Some(photocraft_doc::LayerId(pending.layer))
|
||||
})
|
||||
{
|
||||
self.commit_canvas_image_transform(app, pending.layer, matrix);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn workspace_canvas(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc_id: u64, width: f32) -> (bool, Option<CameraRequest>) {
|
||||
self.finish_canvas_image_transform(app, doc_id);
|
||||
self.expire_workspace_adoption(app, ui, doc_id);
|
||||
if !self.workspace_canvas_allowed(app, ui, doc_id) {
|
||||
if self.canvas_workspace.direct_image_drag.take().is_some() { app.drag = None; }
|
||||
return (false, None);
|
||||
}
|
||||
let blocked_by_overlay = ui.ctx().memory(|memory| memory.top_modal_layer().is_some())
|
||||
|| egui::Popup::is_any_open(ui.ctx()) || !app.ui.dialogs.is_empty()
|
||||
|| self.canvas_workspace.regen.is_some() || !ui.input(|input| input.raw.focused);
|
||||
if self.template_workflow["canvasFirst"] != true {
|
||||
self.canvas_workspace.geometry.remove("agentFeedback");
|
||||
let locating = self.canvas_workspace.locate_request.is_some() || self.canvas_workspace.locate_motion.is_some();
|
||||
let camera = self.plain_workspace_camera(app, ui, xf, doc_id, width);
|
||||
let feedback = self.canvas_feedback(app, ui, xf, doc_id, &[], width, blocked_by_overlay || locating);
|
||||
return (false, camera.or(feedback));
|
||||
}
|
||||
super::glow_pill::bind(ui, app.gpu_render_state.as_ref());
|
||||
let workflow = std::mem::take(&mut self.template_workflow);
|
||||
let mut clear_references = false;
|
||||
let output = self.canvas_workspace.output.clone();
|
||||
let variant = self.canvas_workspace.variant.clone();
|
||||
let rows = rows(&workflow, &output, &variant);
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let painter = ui.painter_at(xf.rect);
|
||||
let variant_label = self.creation_brief["variants"]
|
||||
.as_array()
|
||||
.and_then(|vs| vs.iter().find(|v| v["id"] == variant))
|
||||
.and_then(|v| v["name"].as_str())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let pointer = ui.input(|i| i.pointer.hover_pos()).filter(|p| self.canvas_workspace.on_canvas(xf.rect, *p));
|
||||
let world_pointer = pointer.map(|p| xf.to_doc(p));
|
||||
let references_enabled = self.canvas_workspace.regen.is_none() && app.ui.dialogs.is_empty()
|
||||
&& app.ui.transform.is_none() && !ui.memory(|memory| memory.top_modal_layer().is_some())
|
||||
&& !egui::Popup::is_any_open(ui.ctx());
|
||||
let editing_enabled = !blocked_by_overlay && references_enabled;
|
||||
let reference_pointer = ui.input(|input| input.pointer.interact_pos()).filter(|point| xf.rect.contains(*point));
|
||||
let reference_owns_pointer = references_enabled && self.creation_doc == Some(doc_id) && reference_pointer.is_some_and(|point| {
|
||||
self.canvas_workspace.reference_drag.is_some()
|
||||
|| self.canvas_workspace.reference_cards.iter().any(|(source, bounds)| {
|
||||
world_rect(xf, *bounds).contains(point) && self.canvas_workspace.on_canvas(xf.rect, point)
|
||||
&& super::creation::image_rows(&self.creation["brief"]).iter()
|
||||
.any(|(row, _)| row["purpose"] != "scene" && row["source"].as_str() == Some(source.as_str()))
|
||||
})
|
||||
});
|
||||
let mut blocked = self.canvas_workspace.regen.is_some();
|
||||
let mut camera = None;
|
||||
self.canvas_workspace.clear_canvas_geometry();
|
||||
let active_doc = app.session.active().map(|s| s.doc.clone());
|
||||
let doc_mapping = active_doc.as_deref().and_then(document_mapping_arc);
|
||||
let frame_index = active_doc.as_deref().map(|doc| FrameDocIndex::build(doc, &variant, doc_mapping.as_deref()));
|
||||
if let (Some(doc), Some(index)) = (active_doc.as_deref(), frame_index.as_ref()) {
|
||||
self.paint_processing_status(doc, doc_mapping.as_deref(), index, ui, &rows, xf, &t);
|
||||
}
|
||||
let mut action: Option<(&str, Value)> = None;
|
||||
let mut professional_request: Option<Option<u64>> = None;
|
||||
let now = ui.input(|i| i.time);
|
||||
self.canvas_workspace.appeared.retain(|_, started| now - *started < 0.3);
|
||||
let selected_layers = app.session.active().map(|s| s.selected_layers()).unwrap_or_default();
|
||||
let layer_map = doc_mapping.as_deref().map(native_layers_from_mapping).unwrap_or_default();
|
||||
let selection: Vec<_> = selected_layers.iter().map(|id| id.0).collect();
|
||||
let selection_changed = self.canvas_workspace.selection != selection;
|
||||
let canvas_navigation = pointer.is_some() && ui.input(|input| {
|
||||
input.pointer.middle_down()
|
||||
|| input.raw.events.iter().any(|event| matches!(event, egui::Event::MouseWheel { .. }))
|
||||
});
|
||||
if selection_changed || canvas_navigation || self.canvas_workspace.locate_request.is_some() {
|
||||
self.canvas_workspace.candidate_tab_page = None;
|
||||
}
|
||||
if selection_changed || self.canvas_workspace.context.is_none() {
|
||||
self.canvas_workspace.context =
|
||||
app.session.active().and_then(|state| native_selection_subject(&state.doc, &workflow, &variant, &variant_label, &selection));
|
||||
self.canvas_workspace.selection = selection;
|
||||
}
|
||||
if self.canvas_workspace.candidate_menu.as_ref().is_some_and(|menu| !menu.current(self, &workflow, doc_id))
|
||||
&& let Some(menu) = self.canvas_workspace.candidate_menu.take()
|
||||
{
|
||||
egui::Popup::close_id(ui.ctx(), menu.popup);
|
||||
}
|
||||
|
||||
let mut menu_shown = false;
|
||||
let mut pointer_on_image = false;
|
||||
let mut trace_target = None;
|
||||
for row in &rows {
|
||||
let slot_id = row.slot["id"].as_str().unwrap_or("");
|
||||
let mapping_layer = row.slot["nativeLayerId"].as_u64().or_else(|| layer_map.get(slot_id).copied());
|
||||
let slot = self.draw_workspace_slot(app, ui, SlotDrawInput {
|
||||
row, mapping_layer, xf, doc_id,
|
||||
variant: &variant, variant_label: &variant_label, world_pointer, now, painter: &painter,
|
||||
frame_index: frame_index.as_ref(),
|
||||
}, &mut action);
|
||||
blocked |= slot.0;
|
||||
pointer_on_image |= slot.1;
|
||||
}
|
||||
let near_y = xf.to_doc(xf.rect.center())[1] as f32;
|
||||
let selected = self.canvas_workspace.context.as_ref().and_then(|target| target["slotId"].as_str());
|
||||
let nearest = rows.iter().min_by(|a,b| {
|
||||
let distance = |r: &Row<'_>| {
|
||||
let [_, y, _, h] = frame(r).unwrap_or([0.0, r.page_top, width, r.page_height]);
|
||||
(near_y - near_y.clamp(y, y+h)).abs()
|
||||
};
|
||||
distance(a).total_cmp(&distance(b))
|
||||
});
|
||||
let selected_fit = rows.iter().find(|row| selected.is_some_and(|id| row.slot["id"] == id))
|
||||
.or_else(|| rows.iter().min_by(|a, b| {
|
||||
let distance = |row: &Row<'_>| (near_y - near_y.clamp(row.page_top, row.page_top + row.page_height)).abs();
|
||||
distance(a).total_cmp(&distance(b))
|
||||
}));
|
||||
let current = rows.iter().find(|row| selected.is_some_and(|id| row.slot["id"] == id)
|
||||
&& {
|
||||
let page = world_rect(xf, frame(row).unwrap_or([0.0, row.page_top, width, row.page_height]));
|
||||
page.bottom() > xf.rect.top() && page.top() < xf.rect.bottom()
|
||||
|| self.canvas_workspace.candidate_tab_page.as_ref()
|
||||
== Some(&row.slot["documentId"])
|
||||
}).or(nearest);
|
||||
if let Some(row) = current {
|
||||
let slot_id = row.slot["id"].as_str().unwrap_or("");
|
||||
let mapping_layer = row.slot["nativeLayerId"].as_u64().or_else(|| layer_map.get(slot_id).copied());
|
||||
let count = candidates(row.slot).len() + 1;
|
||||
let group = world_rect(xf, candidate_group(row, width, count));
|
||||
let keep_tabs = self.canvas_workspace.candidate_tab_page.as_ref() == Some(&row.slot["documentId"]);
|
||||
if group.intersects(xf.rect) || keep_tabs {
|
||||
self.canvas_workspace.geometry.insert(
|
||||
format!("candidate-group:{slot_id}"),
|
||||
[group.min.x, group.min.y, group.width(), group.height()],
|
||||
);
|
||||
let tabs: Vec<_> = rows.iter().filter(|item| item.slot["documentId"] == row.slot["documentId"]).collect();
|
||||
let left = group.left().clamp(xf.rect.left(), (xf.rect.right() - 160.0).max(xf.rect.left()));
|
||||
let top = (group.top() - 46.0).clamp(xf.rect.top() + 4.0, (xf.rect.bottom() - 42.0).max(xf.rect.top() + 4.0));
|
||||
let start = pos2(left, top);
|
||||
let tabs_rect = Rect::from_min_max(start, pos2(xf.rect.right(), start.y + 40.0));
|
||||
if tabs_rect.width() > 56.0 {
|
||||
let tabs_id = ui.scope_id().with(("candidate-slot-tabs", doc_id, row.slot["documentId"].as_str()));
|
||||
let mut tabs_ui = ui.new_child(egui::UiBuilder::new().id_salt(tabs_id)
|
||||
.max_rect(tabs_rect).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
tabs_ui.set_clip_rect(tabs_rect);
|
||||
if let Some(item) = self.draw_candidate_tabs(&mut tabs_ui, &tabs, slot_id, tabs_id, doc_id, blocked_by_overlay || reference_owns_pointer) {
|
||||
let item_id = item.slot["id"].as_str().unwrap_or("");
|
||||
let mut target = scope(item.slot, None, &variant, &variant_label);
|
||||
target["nativeLayerId"] = item.slot.get("nativeLayerId").cloned()
|
||||
.filter(|value| !value.is_null()).unwrap_or_else(|| json!(layer_map.get(item_id)));
|
||||
target["locateImageSlot"] = json!(true);
|
||||
self.canvas_workspace.context = Some(target.clone());
|
||||
self.canvas_workspace.candidate_tab_page = Some(item.slot["documentId"].clone());
|
||||
self.canvas_workspace.initial_focus = false;
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
self.canvas_workspace.locate_highlight = Some((target, now));
|
||||
self.canvas_workspace.locate_scope = Some(self.locate_scope_for(app, doc_id, &output, &variant));
|
||||
if let Some(bounds) = frame(item) {
|
||||
camera = fit_tag_selection(xf, bounds, card(item, width, 0), ui.ctx().pixels_per_point());
|
||||
}
|
||||
}
|
||||
blocked |= pointer.is_some_and(|p| tabs_rect.contains(p));
|
||||
}
|
||||
}
|
||||
let corners = [xf.rect.min, xf.rect.max, xf.rect.left_bottom(), xf.rect.right_top()];
|
||||
let (left, right) = corners.into_iter().map(|p| xf.to_doc(p)[0]).fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), x| (a.min(x), b.max(x)));
|
||||
let step = f64::from(card_size(row)[0] + CARD_GAP);
|
||||
let start = (((left - f64::from(width + GAP)) / step).floor().max(0.0) as usize).min(count);
|
||||
let end = ((((right - f64::from(width + GAP)) / step).ceil().max(0.0) as usize).saturating_add(1)).min(count);
|
||||
for index in start..end {
|
||||
let result = self.draw_workspace_candidate(app, ui, CandidateDrawInput {
|
||||
row, width, index, xf, pointer, doc_id, variant: &variant, variant_label: &variant_label,
|
||||
mapping_layer, painter: &painter, t, workflow: &workflow, output: &output, now, reference_owns_pointer,
|
||||
});
|
||||
blocked |= result.blocked;
|
||||
pointer_on_image |= result.pointer_on_image;
|
||||
menu_shown |= result.menu_shown;
|
||||
if result.trace_target.is_some() { trace_target = result.trace_target; }
|
||||
if result.action.is_some() { action = result.action; }
|
||||
if result.professional_request.is_some() { professional_request = result.professional_request; }
|
||||
}
|
||||
}
|
||||
let over_reference = self.paint_product_references(app, ui, xf, doc_id, width, references_enabled);
|
||||
blocked |= over_reference;
|
||||
if over_reference && action.as_ref().is_some_and(|(method, _)| *method == "slot-adopt-prep") {
|
||||
action = None;
|
||||
}
|
||||
if (!over_reference && !blocked) || self.canvas_workspace.direct_image_drag.is_some() {
|
||||
blocked |= self.edit_canvas_image(app, ui, xf, &rows, &layer_map, editing_enabled);
|
||||
}
|
||||
if pointer.is_some() && !pointer_on_image && !blocked && !egui::Popup::is_any_open(ui.ctx())
|
||||
&& ui.input(|input| input.pointer.primary_clicked()) {
|
||||
let modifiers = ui.input(|input| input.events.iter().rev().find_map(|event| match event {
|
||||
egui::Event::PointerButton { button:egui::PointerButton::Primary, modifiers, .. } => Some(*modifiers),
|
||||
_ => None,
|
||||
}).unwrap_or(input.modifiers));
|
||||
let native_content = world_pointer.is_some_and(|point| {
|
||||
app.session.active().is_some_and(|state| native_content_at(&state.doc, point))
|
||||
});
|
||||
if native_content || !blank_selection_gesture(app, modifiers) {
|
||||
// canvas.rs routes this same click to the selected native
|
||||
// tool after the overlay. Do not deselect or consume it. A
|
||||
// stale candidate target must yield to the whole native
|
||||
// selection, including a range a plain click will retain.
|
||||
// Blank Type/paint/create clicks also belong to that tool,
|
||||
// with their existing active layer and native history intact.
|
||||
self.canvas_workspace.context = app.session.active().and_then(|state| {
|
||||
native_selection_subject(&state.doc, &workflow, &variant, &variant_label, &self.canvas_workspace.selection)
|
||||
});
|
||||
} else {
|
||||
let deselected = if selected_layers.is_empty() {
|
||||
true
|
||||
} else if let Err(error) = app.run("select.deselectLayers", json!({})) {
|
||||
self.error = error;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
};
|
||||
if deselected { clear_references = true; }
|
||||
self.canvas_workspace.context = None;
|
||||
blocked = true;
|
||||
}
|
||||
self.canvas_workspace.remember_native_selection(app);
|
||||
self.canvas_workspace.candidate_tab_page = None;
|
||||
self.canvas_workspace.locate_request = None;
|
||||
self.canvas_workspace.locate_highlight = None;
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
}
|
||||
self.finish_candidate_menu(ui, &workflow, doc_id, menu_shown);
|
||||
let locating = self.canvas_workspace.locate_request.is_some() || self.canvas_workspace.locate_motion.is_some();
|
||||
if let Some(request) = self.canvas_workspace.locate_request.take() {
|
||||
let target_variant = request["productVariantId"].as_str().unwrap_or(&variant);
|
||||
let target_output = request["outputId"]
|
||||
.as_str()
|
||||
.or_else(|| workflow["slots"].as_array()?.iter().find(|slot| slot["id"] == request["slotId"])?["outputId"].as_str())
|
||||
.unwrap_or(&output);
|
||||
if target_variant != variant || target_output != output {
|
||||
if !self.canvas_workspace.scope_switch_in_flight
|
||||
&& self.saving.is_none()
|
||||
&& self.pending_slot_apply.is_none()
|
||||
&& self.busy.as_deref() != Some("slot-skeleton")
|
||||
{
|
||||
action = Some(("slot-skeleton", json!({"outputId":target_output,"variantId":target_variant})));
|
||||
}
|
||||
self.canvas_workspace.locate_request = Some(request);
|
||||
} else if let Some(target) = app.session.active().and_then(|state| location(&state.doc, &rows, &request, width, &self.agent_images)) {
|
||||
camera = self.begin_locate(app, xf, doc_id, &output, &variant, request, target, now);
|
||||
|
||||
}
|
||||
}
|
||||
camera = self.advance_locate(app, ui, xf, doc_id, &output, &variant, &rows, width, camera, now);
|
||||
let fit = std::mem::take(&mut self.canvas_workspace.fit_current_screen);
|
||||
let fit_row = if fit {
|
||||
selected_fit
|
||||
} else if self.canvas_workspace.initial_focus { rows.first() } else { None };
|
||||
if let Some(row) = fit_row {
|
||||
let zoom = (xf.rect.width() / (width + GAP + CARD_WIDTH)).min(xf.rect.height() / row.page_height).clamp(0.02, 1.0);
|
||||
camera = Some(CameraRequest { center: [(width + GAP + CARD_WIDTH) / 2.0, row.page_top + row.page_height / 2.0], zoom: Some(zoom * ui.ctx().pixels_per_point()) });
|
||||
self.canvas_workspace.initial_focus = false;
|
||||
}
|
||||
let feedback = self.canvas_feedback(app, ui, xf, doc_id, &rows, width,
|
||||
blocked_by_overlay || locating || camera.is_some());
|
||||
camera = camera.or(feedback);
|
||||
drop(rows);
|
||||
self.template_workflow = workflow;
|
||||
if let Some(target) = trace_target {
|
||||
self.trace_canvas_candidate(app, target);
|
||||
if self.pending_candidate_trace.is_some() {
|
||||
if let Err(error) = super::reveal_agent_tab(app) { self.error = error; }
|
||||
else { self.agent_dock_initialized = true; }
|
||||
}
|
||||
}
|
||||
if clear_references { self.composer_reference_clear(app); }
|
||||
if let Some(layer) = professional_request
|
||||
&& let Err(error) = self.enter_professional(app, layer)
|
||||
{
|
||||
self.error = error;
|
||||
}
|
||||
self.regeneration_window(app, ui);
|
||||
if let Some((method, input)) = action
|
||||
&& let Err(e) = self.slot_action(app, method, input)
|
||||
{
|
||||
self.error = e;
|
||||
}
|
||||
(blocked, camera)
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn draw_candidate_tabs<'a>(&mut self, ui: &mut Ui, tabs: &[&'a Row<'a>], slot_id: &str, id: egui::Id, doc_id: u64, blocked: bool) -> Option<&'a Row<'a>> {
|
||||
let labels: Vec<_> = tabs.iter().map(|item| short_slot_label(item.slot)).collect();
|
||||
let widths: Vec<_> = labels.iter().map(|label| kit::segment_width(ui, label)).collect();
|
||||
let current = tabs.iter().position(|item| item.slot["id"] == slot_id)?;
|
||||
let limit = ui.available_width() - kit::SEGMENT_RAIL_PADDING;
|
||||
let all_fit = widths.iter().sum::<f32>() + kit::SEGMENT_GAP * widths.len().saturating_sub(1) as f32 <= limit;
|
||||
let mut remaining = limit - widths[current] - kit::SEGMENT_MORE_WIDTH - kit::SEGMENT_GAP;
|
||||
let mut visible = Vec::new();
|
||||
let mut hidden = Vec::new();
|
||||
for (index, width) in widths.into_iter().enumerate() {
|
||||
if all_fit || index == current {
|
||||
visible.push(index);
|
||||
} else if width + kit::SEGMENT_GAP <= remaining {
|
||||
remaining -= width + kit::SEGMENT_GAP;
|
||||
visible.push(index);
|
||||
} else {
|
||||
hidden.push(index);
|
||||
}
|
||||
}
|
||||
|
||||
let popup_id = id.with("more");
|
||||
let popup_open = egui::Popup::is_id_open(ui.ctx(), popup_id);
|
||||
let enabled = !blocked || popup_open;
|
||||
let options: Vec<_> = visible.iter().map(|index| (labels[*index], enabled)).collect();
|
||||
let active = visible.iter().position(|index| *index == current)?;
|
||||
let strip = kit::candidate_segments(ui, id, &options, active, self.reduce_motion, (!hidden.is_empty()).then_some(enabled));
|
||||
let refocus = id.with("refocus");
|
||||
if ui.data_mut(|data| data.remove_temp::<bool>(refocus)) == Some(true) {
|
||||
strip.responses[active].request_focus();
|
||||
}
|
||||
for (index, button) in visible.iter().zip(&strip.responses) {
|
||||
let item = tabs[*index];
|
||||
let item_id = item.slot["id"].as_str().unwrap_or("");
|
||||
button.clone().on_hover_text(candidate_group_label(item.slot, |candidate| candidate_is_running(self, doc_id, item_id, candidate)));
|
||||
let rect = button.rect;
|
||||
let bounds = [rect.min.x, rect.min.y, rect.width(), rect.height()];
|
||||
self.canvas_workspace.geometry.insert(format!("candidate-tab:{item_id}"), bounds);
|
||||
if button.has_focus() {
|
||||
self.canvas_workspace.geometry.insert("candidate-tab-focus".into(), bounds);
|
||||
}
|
||||
}
|
||||
let mut chosen = strip.selected.map(|index| visible[index]);
|
||||
if let Some(more) = strip.more {
|
||||
let rect = more.rect;
|
||||
self.canvas_workspace.geometry.insert("candidate-tab-more".into(), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
let popup = egui::Popup::menu(&more).id(popup_id).frame(kit::surface_frame(ui.ctx(), kit::SurfaceRole::Menu));
|
||||
popup.show(|ui| {
|
||||
constrain_candidate_menu_width(ui);
|
||||
for index in hidden {
|
||||
let button = kit::menu_item(ui, labels[index], true);
|
||||
let item_id = tabs[index].slot["id"].as_str().unwrap_or("");
|
||||
let rect = button.rect;
|
||||
self.canvas_workspace.geometry.insert(format!("candidate-tab-menu:{item_id}"), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
if button.clicked() {
|
||||
chosen = Some(index);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if popup_open {
|
||||
egui::Popup::close_id(ui.ctx(), popup_id);
|
||||
}
|
||||
chosen.map(|index| {
|
||||
ui.data_mut(|data| data.insert_temp(refocus, true));
|
||||
tabs[index]
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn paint_processing_status(&mut self, _doc: &Document, mapping: Option<&Value>, frame_index: &FrameDocIndex<'_>, ui: &Ui, rows: &[Row<'_>], xf: ViewXform, t: &Tokens) {
|
||||
let Some(mapping) = mapping else { return };
|
||||
let painter = ui.painter_at(xf.rect);
|
||||
let fields=mapping["fields"].as_array().into_iter().flatten().chain(mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page|page["mapping"]["fields"].as_array().into_iter().flatten()));
|
||||
let slots: HashMap<_, _> = rows.iter().filter_map(|row| row.slot["id"].as_str().map(|id| (id, row))).collect();
|
||||
let applied_copywriting: HashSet<(u64, &str, &str)> = self.messages.iter()
|
||||
.filter(|message| message["kind"] == "copywriting-fields")
|
||||
.flat_map(|message| message["items"].as_array().into_iter().flatten())
|
||||
.filter_map(|item| {
|
||||
let layer = item["layer"].as_u64()?;
|
||||
let slot_id = item["field"]["slotId"].as_str()?;
|
||||
let applied = item["applied"].as_bool()?;
|
||||
let text = item["text"].as_str()?;
|
||||
let original = item["original"].as_str()?;
|
||||
(applied && text != original).then_some((layer, slot_id, text))
|
||||
})
|
||||
.collect();
|
||||
let omit_sample_copy = mapping["omitSampleCopy"] == true;
|
||||
let mut original=0;let mut processed=0;let mut changed=0;
|
||||
for field in fields {
|
||||
let layer_id = field["nativeLayerId"].as_u64().unwrap_or(0);
|
||||
let node = frame_index.layers.get(&layer_id).copied();
|
||||
if omit_sample_copy && field["kind"] == "text"
|
||||
&& node.is_some_and(|layer| matches!(&layer.content, LayerContent::Text(text) if text.text.trim().is_empty()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let slot_id = field["slotId"].as_str().unwrap_or("");
|
||||
let status = if frame_index.processed_layers.contains(&layer_id)
|
||||
|| (!slot_id.is_empty() && frame_index.adopted_slots.contains(slot_id))
|
||||
{
|
||||
"小壹已处理"
|
||||
} else if let Some(node) = node && let LayerContent::Text(text) = &node.content {
|
||||
if !slot_id.is_empty() && applied_copywriting.contains(&(layer_id, slot_id, text.text.as_str())) {
|
||||
"小壹已处理"
|
||||
} else if field["originalText"].as_str().is_some_and(|original| text.text != original) {
|
||||
"已修改"
|
||||
} else {
|
||||
"原稿 · 未处理"
|
||||
}
|
||||
} else {
|
||||
"原稿 · 未处理"
|
||||
};
|
||||
match status {"小壹已处理"=>processed+=1,"已修改"=>changed+=1,_=>original+=1};
|
||||
let frame_value=&field["frame"];
|
||||
let Some(values)=frame_value["x"].as_f64().zip(frame_value["y"].as_f64())
|
||||
.zip(frame_value["width"].as_f64().zip(frame_value["height"].as_f64())) else { continue };
|
||||
let ((x,y),(w,h))=values;
|
||||
let slot = field["slotId"].as_str().and_then(|id| slots.get(id)).copied();
|
||||
let rect = world_rect(xf, slot.and_then(frame).unwrap_or([x as f32,y as f32,w as f32,h as f32]));
|
||||
if !rect.intersects(xf.rect) {continue;}
|
||||
let id=field["fieldId"].as_str().unwrap_or("");
|
||||
self.canvas_workspace.geometry.insert(format!("field-state:{status}:{id}"),[rect.min.x,rect.min.y,rect.width(),rect.height()]);
|
||||
}
|
||||
let mut labels = vec![format!("原稿 · 未处理 {original}"), format!("小壹已处理 {processed}")];
|
||||
if changed > 0 { labels.push(format!("已修改 {changed}")); }
|
||||
let one_line_text = labels.join(" ");
|
||||
let visible = xf.rect.intersect(ui.clip_rect());
|
||||
let width = (visible.width() - 44.0).max(1.0);
|
||||
let width_bits = width.to_bits();
|
||||
let galley = if let Some((cached_text, cached_w, cached_color, cached_galley)) = self.canvas_workspace.processing_badge.as_ref()
|
||||
&& cached_text == &one_line_text && *cached_w == width_bits && *cached_color == t.text
|
||||
{
|
||||
cached_galley.clone()
|
||||
} else {
|
||||
let font = crate::theme::agent_scale::Type::Meta.font_id();
|
||||
let one_line = painter.layout_no_wrap(one_line_text.clone(), font.clone(), t.text);
|
||||
let galley = if one_line.size().x <= width { one_line } else {
|
||||
painter.layout(labels.join("\n"), font, t.text, width)
|
||||
};
|
||||
self.canvas_workspace.processing_badge = Some((one_line_text, width_bits, t.text, galley.clone()));
|
||||
galley
|
||||
};
|
||||
let badge=Rect::from_min_size(visible.min+vec2(12.0,12.0),galley.size()+vec2(20.0,12.0));
|
||||
painter.rect_filled(badge,5.0,t.card);
|
||||
painter.galley(badge.min+vec2(10.0,6.0),galley,t.text);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,403 @@
|
||||
use super::super::{json, Document, PhotocraftApp, Value, Workspace};
|
||||
use super::document::native_layers;
|
||||
use super::{
|
||||
CameraRequest, CARD_GAP, CARD_WIDTH, GAP, GROUP_PAD, HEADER,
|
||||
};
|
||||
use crate::canvas::ViewXform;
|
||||
use egui::{Rect, Vec2, vec2};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(crate) struct SubmittedRegen {
|
||||
pub(crate) session: u64,
|
||||
pub(crate) edit_version: u64,
|
||||
pub(crate) target: Value,
|
||||
pub(crate) text: String,
|
||||
pub(crate) identity: GenerationIdentity,
|
||||
}
|
||||
|
||||
pub(crate) struct SubmittedComposer {
|
||||
pub(crate) edit_version: u64,
|
||||
pub(crate) target: Value,
|
||||
pub(crate) text: String,
|
||||
pub(crate) identity: GenerationIdentity,
|
||||
}
|
||||
|
||||
pub(crate) struct GenerationIdentity {
|
||||
pub(crate) existing: HashSet<String>,
|
||||
pub(crate) candidate_id: Option<String>,
|
||||
pub(crate) ambiguous: bool,
|
||||
}
|
||||
|
||||
impl GenerationIdentity {
|
||||
pub(crate) fn new(workflow: &Value, target: &Value) -> Self {
|
||||
Self { existing: scoped_candidate_ids(workflow, target, false), candidate_id: None, ambiguous: false }
|
||||
}
|
||||
|
||||
pub(crate) fn bind_prepared(&mut self, workflow: &Value, target: &Value) {
|
||||
if self.candidate_id.is_some() || self.ambiguous {
|
||||
return;
|
||||
}
|
||||
let ids = scoped_candidate_ids(workflow, target, true);
|
||||
let mut new = ids.difference(&self.existing);
|
||||
if let Some(first) = new.next() {
|
||||
if new.next().is_some() {
|
||||
self.ambiguous = true;
|
||||
} else {
|
||||
self.candidate_id = Some(first.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn matches(&self, candidate: &Value, target: &Value) -> bool {
|
||||
self.candidate_id.as_deref().is_some_and(|id| candidate["id"].as_str() == Some(id)) && receipt_matches_target(candidate, target)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scoped_candidate_ids(workflow: &Value, target: &Value, pending_only: bool) -> HashSet<String> {
|
||||
workflow["slots"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|slot| slot["id"] == target["slotId"] && (slot["variantId"].is_null() || slot["variantId"] == target["productVariantId"]))
|
||||
.flat_map(candidates)
|
||||
.filter(|candidate| !pending_only || matches!(candidate["status"].as_str(), Some("prepared" | "dispatched" | "running")))
|
||||
.filter_map(|candidate| candidate["id"].as_str().filter(|id| !id.is_empty()).map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Row<'a> {
|
||||
pub(crate) slot: &'a Value,
|
||||
pub(crate) page_top: f32,
|
||||
pub(crate) page_height: f32,
|
||||
}
|
||||
|
||||
pub(crate) fn rows<'a>(workflow: &'a Value, output: &str, variant: &str) -> Vec<Row<'a>> {
|
||||
let mut out = Vec::new();
|
||||
let mut top = 0.0f32;
|
||||
for page in workflow["outputs"].as_array().into_iter().flatten().filter(|p| p["outputId"] == output) {
|
||||
let height = page["height"].as_f64().unwrap_or(1440.0).clamp(1.0, 30000.0) as f32;
|
||||
let slots: Vec<_> = workflow["slots"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|s| s["documentId"] == page["documentId"] && s["outputId"] == output && (s["variantId"].is_null() || s["variantId"] == variant))
|
||||
.collect();
|
||||
out.extend(slots.into_iter().map(|slot| Row { slot, page_top: top, page_height: height }));
|
||||
top += height;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn short_slot_label(slot: &Value) -> &str {
|
||||
let label = slot["label"].as_str().unwrap_or("图片");
|
||||
label.rsplit(['-', '–']).next().unwrap_or(label).rsplit(" - ").next().unwrap_or(label).trim()
|
||||
}
|
||||
|
||||
pub(crate) fn candidates(slot: &Value) -> &[Value] {
|
||||
slot["candidates"].as_array().map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_adoption_input(candidate: &Value, slot: &str, variant: &str, layer: Option<u64>) -> Value {
|
||||
let mut input = json!({"slotId":slot,"candidateId":candidate["id"],"variantId":variant,"nativeLayerId":layer});
|
||||
if candidate["historical"] == true {
|
||||
input["historicalCandidate"] = json!(true);
|
||||
}
|
||||
input
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_can_adopt(candidate: &Value, layer: Option<u64>) -> bool {
|
||||
candidate["status"] == "complete" && candidate["adoptionError"].is_null() && layer.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn first_generated_preview(slot: &Value) -> Option<&Value> {
|
||||
candidates(slot).iter()
|
||||
.find(|candidate| candidate["status"] == "complete" && candidate["historical"] != true
|
||||
&& candidate["archivePreview"] != true && !candidate["sourceType"].is_string())
|
||||
}
|
||||
|
||||
pub(crate) fn preview_rejected(candidate: &Value, slot_id: &str, progress: &Value) -> bool {
|
||||
let Some(id) = candidate["id"].as_str() else { return false };
|
||||
let live = &progress["candidateReviews"][id];
|
||||
if live["slotId"] == slot_id && let Some(status) = live["status"].as_str() {
|
||||
return status == "rejected";
|
||||
}
|
||||
matches!(candidate["reviewDecision"].as_str(), Some("revise" | "missing"))
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_task_id(candidate: &Value) -> &str {
|
||||
candidate.get("taskId").unwrap_or(&candidate["id"]).as_str().unwrap_or("")
|
||||
}
|
||||
|
||||
/// Count finished images separately from task records. Empty/running/failed
|
||||
/// entries still occupy their original layout positions and remain recoverable.
|
||||
pub(crate) fn candidate_group_label(slot: &Value, active: impl Fn(&Value) -> bool) -> String {
|
||||
let mut complete = 0;
|
||||
let mut processing = 0;
|
||||
let mut unresolved = 0;
|
||||
let mut failed = 0;
|
||||
for candidate in candidates(slot) {
|
||||
match candidate["status"].as_str() {
|
||||
Some("complete" | "applied") => complete += 1,
|
||||
Some("failed" | "rejected") => failed += 1,
|
||||
Some("prepared" | "dispatched" | "running") if active(candidate) => processing += 1,
|
||||
_ => unresolved += 1,
|
||||
}
|
||||
}
|
||||
let mut label = format!("{}的候选 · 已完成 {} 张", slot["label"].as_str().unwrap_or("图片"), complete);
|
||||
if processing > 0 { label.push_str(&format!(" · {processing} 项处理中")); }
|
||||
if unresolved > 0 { label.push_str(&format!(" · {unresolved} 项待核查")); }
|
||||
if failed > 0 { label.push_str(&format!(" · {failed} 项失败")); }
|
||||
label
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_is_running(w: &Workspace, doc: u64, slot: &str, candidate: &Value) -> bool {
|
||||
if !matches!(w.busy.as_deref(), Some("slot-generate" | "slot-append"))
|
||||
|| w.agent_effects_paused || w.canvas_workspace.handed_over
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(op) = w.running_workflow_generation(doc) {
|
||||
return op["slotId"] == slot && op["productVariantId"] == w.canvas_workspace.variant
|
||||
&& op["outputId"] == w.canvas_workspace.output
|
||||
&& op["candidateId"].is_string() && op["candidateId"] == candidate["id"];
|
||||
}
|
||||
if w.canvas_workspace.submitted_generation_target(&w.account["id"], &w.origin, Some(doc)).is_none() {
|
||||
return false;
|
||||
}
|
||||
let submission = w.canvas_workspace.submitted_composer.as_ref().map(|s| (&s.identity, &s.target))
|
||||
.or_else(|| w.canvas_workspace.submitted_regen.as_ref().map(|s| (&s.identity, &s.target)));
|
||||
submission.is_some_and(|(identity, target)| {
|
||||
identity.candidate_id.as_deref().is_some_and(|id| candidate["id"].as_str() == Some(id))
|
||||
&& target["slotId"] == slot && target["productVariantId"] == w.canvas_workspace.variant
|
||||
&& target["outputId"] == w.canvas_workspace.output
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn frame(row: &Row) -> Option<[f32; 4]> {
|
||||
let f = &row.slot["frame"];
|
||||
let result = [f["x"].as_f64()? as f32, row.page_top + f["y"].as_f64()? as f32, f["width"].as_f64()? as f32, f["height"].as_f64()? as f32];
|
||||
(result.iter().all(|n| n.is_finite()) && result[2] > 0.0 && result[3] > 0.0).then_some(result)
|
||||
}
|
||||
|
||||
pub(crate) fn world_rect(xf: ViewXform, r: [f32; 4]) -> Rect {
|
||||
let points = [(r[0], r[1]), (r[0] + r[2], r[1]), (r[0], r[1] + r[3]), (r[0] + r[2], r[1] + r[3])];
|
||||
points.into_iter().fold(Rect::NOTHING, |b, (x, y)| {
|
||||
let p = xf.to_screen(x, y);
|
||||
b.union(Rect::from_min_max(p, p))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn card_size(row: &Row) -> [f32; 2] {
|
||||
let max_height = (row.page_height - HEADER - 70.0).max(80.0);
|
||||
let ratio = frame(row).map_or(1.0, |f| f[2] / f[3]).clamp(0.05, 20.0);
|
||||
let height = (CARD_WIDTH / ratio).min(max_height);
|
||||
[height * ratio, height]
|
||||
}
|
||||
|
||||
pub(crate) fn card(row: &Row, width: f32, index: usize) -> [f32; 4] {
|
||||
let [card_width, card_height] = card_size(row);
|
||||
let top = frame(row).map_or(row.page_top, |frame| frame[1]);
|
||||
[width + GAP + index as f32 * (card_width + CARD_GAP), top + HEADER, card_width, card_height]
|
||||
}
|
||||
|
||||
pub(crate) fn candidate_group(row: &Row, width: f32, count: usize) -> [f32; 4] {
|
||||
let first = card(row, width, 0);
|
||||
let last = card(row, width, count.saturating_sub(1));
|
||||
[first[0] - GROUP_PAD, first[1] - GROUP_PAD, last[0] + last[2] - first[0] + 2.0 * GROUP_PAD, first[3] + 2.0 * GROUP_PAD]
|
||||
}
|
||||
|
||||
pub(crate) fn fit_tag_selection(xf: ViewXform, field: [f32; 4], candidate: [f32; 4], ppp: f32) -> Option<CameraRequest> {
|
||||
let visible = xf.rect.shrink(32.0);
|
||||
if visible.contains_rect(world_rect(xf, field)) && xf.rect.intersects(world_rect(xf, candidate)) {
|
||||
return None;
|
||||
}
|
||||
let unit_view = ViewXform { zoom: 1.0, ..xf };
|
||||
let bounds = world_rect(unit_view, field).union(world_rect(unit_view, candidate));
|
||||
let center = unit_view.to_doc(bounds.center());
|
||||
let zoom = (visible.width() / bounds.width()).min(visible.height() / bounds.height()).min(xf.zoom).max(0.02);
|
||||
Some(CameraRequest {
|
||||
center: [center[0] as f32, center[1] as f32],
|
||||
zoom: (zoom != xf.zoom).then_some(zoom * ppp),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn fit_candidate(image: [f32; 4], source: Vec2) -> [f32; 4] {
|
||||
if source.x <= 0.0 || source.y <= 0.0 || !source.x.is_finite() || !source.y.is_finite() {
|
||||
return image;
|
||||
}
|
||||
let scale = (image[2] / source.x).min(image[3] / source.y);
|
||||
let size = source * scale;
|
||||
[image[0] + (image[2] - size.x) * 0.5, image[1] + (image[3] - size.y) * 0.5, size.x, size.y]
|
||||
}
|
||||
|
||||
/// Paint the whole candidate texture with the same rounded silhouette at every
|
||||
/// entrance frame. The transient blur changes samples and opacity only; it
|
||||
/// never moves the visible image away from its eventual clickable bounds.
|
||||
|
||||
pub(crate) fn scope(slot: &Value, candidate: Option<&Value>, variant: &str, variant_label: &str) -> Value {
|
||||
let label = slot["label"].as_str().unwrap_or("图片");
|
||||
let mut value = json!({"kind":if candidate.is_some(){"candidate"}else{"slot"},"label":label,
|
||||
"pageId":slot["documentId"],"slotId":slot["id"],"fieldId":slot["fieldId"],"outputId":slot["outputId"],
|
||||
"productVariantId":variant,"variantLabel":variant_label,"nativeLayerId":slot["nativeLayerId"]});
|
||||
if let Some(candidate) = candidate {
|
||||
value["candidateId"] = candidate["id"].clone();
|
||||
value["taskId"] = candidate.get("taskId").unwrap_or(&candidate["id"]).clone();
|
||||
value["previewId"] = value["taskId"].clone();
|
||||
value["status"] = candidate["status"].clone();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
pub(crate) fn native_selection_subject(doc: &Document, workflow: &Value, variant: &str, variant_label: &str, selected: &[u64]) -> Option<Value> {
|
||||
let mapping = native_layers(doc);
|
||||
let targets: Vec<_> = selected
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let layer = doc.layer(photocraft_doc::LayerId(*id))?;
|
||||
let slot = workflow["slots"].as_array().into_iter().flatten().find(|slot| {
|
||||
slot["nativeLayerId"].as_u64().or_else(|| slot["id"].as_str().and_then(|id| mapping.get(id).copied())) == Some(*id)
|
||||
&& (slot["variantId"].is_null() || slot["variantId"] == variant)
|
||||
});
|
||||
Some(if let Some(slot) = slot {
|
||||
let mut target = scope(slot, None, variant, variant_label);
|
||||
target["nativeLayerId"] = json!(id);
|
||||
target
|
||||
} else {
|
||||
json!({"kind":"layer","label":layer.name,"nativeLayerId":id})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
match targets.as_slice() {
|
||||
[] => None,
|
||||
[target] => Some(target.clone()),
|
||||
_ => Some(json!({"kind":"selection","label":format!("已选 {} 个对象",targets.len()),"targets":targets,"selectedLayerIds":selected})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Use the native Auto-Select hit test, including text bounds between glyphs,
|
||||
/// rather than treating everything outside the image slots as empty. The
|
||||
/// native Background is the blank page, not a separate collaboration target.
|
||||
pub(crate) fn slot_hit_is_obscured(doc: &Document, point: [f64; 2], slot: Option<photocraft_doc::LayerId>) -> bool {
|
||||
photocraft_engine::pick_cmds::auto_select_target(doc, point[0].floor() as i32, point[1].floor() as i32, false)
|
||||
.is_some_and(|hit| Some(hit) != slot && !doc.is_background(hit)
|
||||
&& slot.and_then(|id| doc.path_of(id)).zip(doc.path_of(hit)).is_some_and(|(slot, hit)| hit > slot))
|
||||
}
|
||||
|
||||
pub(crate) fn native_content_at(doc: &Document, point: [f64; 2]) -> bool {
|
||||
if point.iter().any(|coordinate| !coordinate.is_finite()) {
|
||||
return false;
|
||||
}
|
||||
photocraft_engine::pick_cmds::auto_select_target(doc, point[0].floor() as i32, point[1].floor() as i32, false)
|
||||
.is_some_and(|layer| !doc.is_background(layer))
|
||||
}
|
||||
|
||||
/// Only a plain native Auto-Select gesture owns blank-click deselection. The
|
||||
/// canvas resolves temporary Hand/Move tools before the overlay and uses the
|
||||
/// same event-tool and sticky-modifier rules for its actual pointer dispatch.
|
||||
pub(crate) fn blank_selection_gesture(app: &PhotocraftApp, modifiers: egui::Modifiers) -> bool {
|
||||
let modifiers = crate::workspace_ui::sticky_mods(app, modifiers);
|
||||
let tool = crate::canvas::event_tool(app, modifiers);
|
||||
tool == crate::state::Tool::Move && app.ui.tool_options.move_auto_select != modifiers.command
|
||||
&& !modifiers.shift && !modifiers.alt && app.drag.is_none() && app.guide_drag.is_none()
|
||||
&& app.ui.transform.is_none() && app.ui.text_edit.is_none() && app.ui.dialogs.is_empty()
|
||||
&& !crate::cam_transform::active(app) && !crate::move_ui::moves_selected_pixels_with(app, tool)
|
||||
}
|
||||
|
||||
/// The queue contains checked, concrete edits. A conversation, external image
|
||||
/// wait or current selection alone is not evidence of an active canvas edit.
|
||||
pub(crate) fn includes_target(subject: Option<&Value>, slot: &str, candidate: Option<&str>) -> bool {
|
||||
subject.is_some_and(|subject| {
|
||||
if subject["kind"] == "selection" {
|
||||
subject["targets"].as_array().into_iter().flatten().any(|target| includes_target(Some(target), slot, candidate))
|
||||
} else {
|
||||
subject["slotId"] == slot && candidate.is_none_or(|id| subject["candidateId"] == id || subject["taskId"] == id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn matches_candidate(candidate: &Value, target: &Value) -> bool {
|
||||
["id", "taskId"]
|
||||
.iter()
|
||||
.filter_map(|key| candidate[*key].as_str())
|
||||
.any(|id| target["candidateId"].as_str() == Some(id) || target["taskId"].as_str() == Some(id))
|
||||
}
|
||||
|
||||
pub(crate) fn same_generation_target(a: &Value, b: &Value) -> bool {
|
||||
a["slotId"].as_str().is_some_and(|value| !value.is_empty())
|
||||
&& a["productVariantId"].as_str().is_some_and(|value| !value.is_empty())
|
||||
&& ["slotId", "productVariantId", "outputId", "candidateId"].iter().all(|key| a[*key] == b[*key])
|
||||
}
|
||||
|
||||
pub(crate) fn receipt_matches_target(candidate: &Value, target: &Value) -> bool {
|
||||
target["slotId"].as_str().is_some_and(|value| !value.is_empty())
|
||||
&& target["productVariantId"].as_str().is_some_and(|value| !value.is_empty())
|
||||
&& candidate["slotId"] == target["slotId"]
|
||||
&& candidate["variantId"] == target["productVariantId"]
|
||||
}
|
||||
|
||||
pub(crate) fn target_summary(target: &Value) -> Value {
|
||||
if !target.is_object() {
|
||||
return Value::Null;
|
||||
}
|
||||
let mut summary = serde_json::Map::new();
|
||||
for key in
|
||||
["kind", "label", "pageId", "slotId", "outputId", "productVariantId", "variantLabel", "candidateId", "taskId", "nativeLayerId", "selectedLayerIds", "documentId", "revision", "component", "layerKind", "fieldId", "status", "source"]
|
||||
{
|
||||
if let Some(value) = target.get(key) {
|
||||
summary.insert(key.into(), value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(targets) = target["targets"].as_array() {
|
||||
summary.insert("targets".into(), json!(targets.iter().take(64).map(target_summary).collect::<Vec<_>>()));
|
||||
}
|
||||
Value::Object(summary)
|
||||
}
|
||||
|
||||
pub(crate) fn location(doc: &Document, rows: &[Row<'_>], target: &Value, width: f32, images: &super::agent_image_cache::TextureCache<egui::TextureHandle>) -> Option<[f32; 4]> {
|
||||
if target["kind"] == "selection" {
|
||||
return target["targets"].as_array().into_iter().flatten().filter_map(|target| location(doc, rows, target, width, images)).reduce(|a, b| {
|
||||
let x = a[0].min(b[0]);
|
||||
let y = a[1].min(b[1]);
|
||||
[x, y, (a[0] + a[2]).max(b[0] + b[2]) - x, (a[1] + a[3]).max(b[1] + b[3]) - y]
|
||||
});
|
||||
}
|
||||
let row = rows.iter().find(|row| target["slotId"] == row.slot["id"] || candidates(row.slot).iter().any(|candidate| matches_candidate(candidate, target)));
|
||||
if target["locateImageSlot"] != true && let Some((row, index)) =
|
||||
row.and_then(|row| candidates(row.slot).iter().position(|candidate| matches_candidate(candidate, target)).map(|index| (row, index)))
|
||||
{
|
||||
let bounds = card(row, width, index);
|
||||
let candidate = &candidates(row.slot)[index];
|
||||
let task = candidate_task_id(candidate);
|
||||
// Match the actual image and clickable bounds, not the larger slot-
|
||||
// ratio cell. This also keeps the locate animation centred on the
|
||||
// picture when a candidate has a different aspect ratio.
|
||||
return Some(images.get(task).map_or(bounds, |texture| fit_candidate(bounds, texture.size_vec2())));
|
||||
}
|
||||
if target["locateImageSlot"] == true && let Some(bounds) = row.and_then(frame) {
|
||||
return Some(bounds);
|
||||
}
|
||||
// Native text, pixels and groups already have document-space bounds. Use
|
||||
// those current bounds after manual moves; candidate cards stay separate.
|
||||
if let Some(layer) = target["nativeLayerId"].as_u64().and_then(|id| doc.layer(photocraft_doc::LayerId(id))) {
|
||||
let bounds = photocraft_compose::layer_bounds(layer, doc.bounds());
|
||||
if !bounds.is_empty() {
|
||||
return Some([bounds.x0 as f32, bounds.y0 as f32, bounds.width() as f32, bounds.height() as f32]);
|
||||
}
|
||||
}
|
||||
let row = row?;
|
||||
frame(row).or(Some([0.0, row.page_top, width, row.page_height]))
|
||||
}
|
||||
|
||||
pub(crate) fn status(value: &Value, busy: bool) -> &'static str {
|
||||
match value["status"].as_str() {
|
||||
Some("complete" | "applied") => "已生成",
|
||||
Some("failed" | "rejected") => "生成失败",
|
||||
Some("unknown") => "结果待核查",
|
||||
Some("prepared") if busy => "准备生成",
|
||||
Some("dispatched" | "running") if busy => "生成中",
|
||||
Some("prepared" | "dispatched" | "running") => "结果待核查",
|
||||
_ => "待生成",
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,420 @@
|
||||
use super::super::{json, PhotocraftApp, Request, Tokens, Ui, Value, Workspace};
|
||||
use super::super::stitch_ui as kit;
|
||||
use super::projection::{native_selection_subject, world_rect};
|
||||
use super::candidate_menu_ui::candidate_image_shape;
|
||||
use super::overlay_ui::{reference_preview_edge, reference_scale, take_image_wheel};
|
||||
use super::{bound_project, CARD_GAP, CARD_WIDTH, GAP};
|
||||
use crate::canvas::ViewXform;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Vec2, pos2, vec2};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Default, PartialEq, serde::Deserialize, serde::Serialize)]
|
||||
pub(crate) struct ReferenceDockLayout {
|
||||
pub(crate) placements: BTreeMap<String, Option<[f32; 4]>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) enum ReferenceDockTab {
|
||||
#[default]
|
||||
Products,
|
||||
Resources,
|
||||
}
|
||||
|
||||
/// 收纳坞浮层:`open` 是打开它的文档,`tab` 是正在或刚才显示的那组图片(退场时仍显示它)。
|
||||
/// 只在本次运行内有效,默认收起。
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(crate) struct ReferencePopover {
|
||||
pub(crate) open: Option<u64>,
|
||||
pub(crate) tab: ReferenceDockTab,
|
||||
}
|
||||
|
||||
/// 按钮组与浮层各自是画布上方的一个浮动层。
|
||||
fn reference_dock_layer(part: &'static str) -> egui::Id {
|
||||
egui::Id::unique(("xiaoyi-reference-dock", part))
|
||||
}
|
||||
|
||||
/// 收纳坞浮层打开时 Esc 先交给它收起,不再同时取消选区、后台任务或全屏;
|
||||
/// 按住鼠标拖动时仍留给拖动取消。
|
||||
pub(crate) fn reference_dock_owns_escape(ctx: &egui::Context) -> bool {
|
||||
let popover = egui::LayerId::new(egui::Order::Middle, reference_dock_layer("popover"));
|
||||
!ctx.input(|input| input.pointer.any_down())
|
||||
&& ctx.memory(|memory| memory.areas().visible_last_frame(&popover))
|
||||
&& egui::AreaState::load(ctx, popover.id).is_some_and(|state| state.interactable)
|
||||
}
|
||||
|
||||
/// 底板上的计数按钮:静止时透明,悬停、按下与打开分别用 `hover` / `pressed` 底色,
|
||||
/// 不再叠一层描边;圆角与底板同心。
|
||||
fn reference_dock_button_style(ui: &mut Ui, t: Tokens, corner: f32, gap: f32) {
|
||||
use crate::theme::agent_scale::control;
|
||||
let style = ui.style_mut();
|
||||
let widgets = &mut style.visuals.widgets;
|
||||
for (visual, fill) in [
|
||||
(&mut widgets.noninteractive, Color32::TRANSPARENT),
|
||||
(&mut widgets.inactive, Color32::TRANSPARENT),
|
||||
(&mut widgets.hovered, t.hover),
|
||||
(&mut widgets.active, t.pressed),
|
||||
] {
|
||||
visual.bg_fill = fill;
|
||||
visual.weak_bg_fill = fill;
|
||||
visual.bg_stroke = Stroke::NONE;
|
||||
visual.corner_radius = egui::CornerRadius::same(corner as u8);
|
||||
}
|
||||
style.visuals.selection.bg_fill = t.pressed;
|
||||
style.spacing.button_padding = vec2(6.0, 4.0);
|
||||
style.spacing.interact_size.y = control::STANDARD;
|
||||
style.spacing.item_spacing.x = gap;
|
||||
}
|
||||
|
||||
fn rect_geometry(rect: Rect) -> [f32; 4] {
|
||||
[rect.left(), rect.top(), rect.width(), rect.height()]
|
||||
}
|
||||
|
||||
impl ReferenceDockTab {
|
||||
pub(crate) fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Products => "产品图",
|
||||
Self::Resources => "图片资源",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ReferenceDockLayout {
|
||||
pub(crate) fn key(project: &str) -> egui::Id {
|
||||
egui::Id::unique(("xiaoyi-product-reference-dock", project))
|
||||
}
|
||||
|
||||
pub(crate) fn visible(&self, source: &str, introducing: bool) -> bool {
|
||||
self.placements.get(source).map_or(introducing, Option::is_some)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn product_reference_images(&self, doc: u64) -> Vec<(String, String)> {
|
||||
if self.creation_doc != Some(doc) { return Vec::new(); }
|
||||
super::creation::image_rows(&self.creation["brief"]).into_iter()
|
||||
.filter_map(|(image, _)| {
|
||||
if image["purpose"] == "scene" { return None; }
|
||||
Some((image["source"].as_str()?.to_owned(), image["name"].as_str().unwrap_or("产品参考图").to_owned()))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn paint_product_references(&mut self, app: &PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc_id: u64, width: f32, enabled: bool) -> bool {
|
||||
if self.creation_doc != Some(doc_id) { return false; }
|
||||
let Some(project) = self.open_projects.get(&doc_id) else { return false };
|
||||
let images = self.product_reference_images(doc_id);
|
||||
if !images.is_empty() && self.reference_intro_doc == Some(doc_id) {
|
||||
self.reference_intro_doc = None;
|
||||
self.canvas_workspace.reference_intro = true;
|
||||
}
|
||||
let layout_id = ReferenceDockLayout::key(project);
|
||||
let saved = ui.ctx().data_mut(|data| data.get_persisted::<ReferenceDockLayout>(layout_id)).unwrap_or_default();
|
||||
let mut layout = saved.clone();
|
||||
let introducing = self.canvas_workspace.reference_intro;
|
||||
self.canvas_workspace.reference_cards.retain(|source, _| layout.visible(source, introducing));
|
||||
let mut owns_primary = self.place_docked_reference(ui, xf, doc_id, enabled, &mut layout);
|
||||
// Paint after the template and candidates, using the same document transform.
|
||||
let painter = ui.painter_at(xf.rect);
|
||||
let mut cards = Vec::new();
|
||||
for (index, (source, name)) in images.into_iter().enumerate() {
|
||||
if !layout.visible(&source, introducing) { continue; }
|
||||
let key = super::creation_reads::reference_key(&source);
|
||||
self.queue_creation_reference(app, &source);
|
||||
let Some(texture) = self.creation_thumbs.get(&key).cloned() else { continue };
|
||||
let reference_id = ui.scope_id().with(("canvas-product-reference", doc_id, index));
|
||||
if let Some(Some(bounds)) = layout.placements.get(&source) {
|
||||
self.canvas_workspace.reference_cards.insert(source.clone(), *bounds);
|
||||
}
|
||||
let card = self.canvas_workspace.reference_cards.entry(source.clone()).or_insert_with(|| {
|
||||
let size = texture.size_vec2();
|
||||
let size = size * (720.0 / size.x.max(size.y));
|
||||
let right = xf.to_doc(pos2(xf.rect.right() - 24.0, xf.rect.top() + 54.0));
|
||||
let x = (width + GAP + CARD_WIDTH + CARD_GAP).min(right[0] as f32 - size.x);
|
||||
[x, right[1] as f32 + index as f32 * 758.0, size.x, size.y]
|
||||
});
|
||||
let screen = world_rect(xf, *card);
|
||||
cards.push((index, reference_id, source, name, texture, *card, screen, key));
|
||||
}
|
||||
let middle = ui.input(|input| input.pointer.middle_down());
|
||||
let pointer = ui.input(|input| input.pointer.interact_pos());
|
||||
let hovered = pointer.filter(|point| self.canvas_workspace.on_canvas(xf.rect, *point))
|
||||
.and_then(|point| cards.iter().rev().find(|card| card.6.intersect(xf.rect).contains(point)).map(|card| card.0));
|
||||
owns_primary |= enabled && middle && hovered.is_some();
|
||||
let (pressed, down, released) = ui.input(|input| (input.pointer.primary_pressed(), input.pointer.primary_down(), input.pointer.primary_released()));
|
||||
let double_clicked = ui.input(|input| input.pointer.button_double_clicked(egui::PointerButton::Primary));
|
||||
if !enabled || middle {
|
||||
self.canvas_workspace.reference_drag = None;
|
||||
}
|
||||
let mut visible_previews = std::collections::HashSet::new();
|
||||
for (index, reference_id, source, name, thumbnail, mut world, screen, key) in cards {
|
||||
let visible = screen.intersect(xf.rect).intersect(ui.clip_rect());
|
||||
let can_interact = enabled && !middle && !owns_primary && hovered == Some(index);
|
||||
if enabled && !middle && visible.is_positive() {
|
||||
let response = ui.interact(visible, reference_id, Sense::click_and_drag());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("收回{name}")));
|
||||
let recall = (can_interact && double_clicked)
|
||||
|| (response.has_focus()
|
||||
&& ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)));
|
||||
if recall {
|
||||
self.canvas_workspace.reference_cards.remove(&source);
|
||||
layout.placements.insert(source, None);
|
||||
self.canvas_workspace.reference_drag = None;
|
||||
self.canvas_workspace.reference_popover = ReferencePopover { open: Some(doc_id), tab: ReferenceDockTab::Products };
|
||||
owns_primary = true;
|
||||
ui.ctx().request_repaint();
|
||||
continue;
|
||||
}
|
||||
if can_interact && !down {
|
||||
response.on_hover_text(format!("{name} · 双击收回,拖动摆放,Alt 或 Ctrl 加滚轮缩放"));
|
||||
}
|
||||
}
|
||||
if can_interact && pressed && let Some(point) = pointer {
|
||||
let [x, y] = xf.to_doc(point);
|
||||
self.canvas_workspace.reference_drag = Some((reference_id, [x - f64::from(world[0]), y - f64::from(world[1])]));
|
||||
}
|
||||
let drag = self.canvas_workspace.reference_drag.filter(|(id, _)| *id == reference_id);
|
||||
let before = world;
|
||||
if let Some((_, offset)) = drag && (down || released) && let Some(point) = pointer {
|
||||
let [x, y] = xf.to_doc(point);
|
||||
world[0] = (x - offset[0]) as f32;
|
||||
world[1] = (y - offset[1]) as f32;
|
||||
}
|
||||
if can_interact && !down {
|
||||
let scroll = take_image_wheel(ui);
|
||||
if scroll != 0.0 {
|
||||
reference_scale(&mut world, xf.to_doc(pointer.unwrap_or(screen.center())), (scroll * 0.006).exp());
|
||||
}
|
||||
}
|
||||
let moving_from_dock = self.canvas_workspace.reference_dock_drag.as_ref()
|
||||
.is_some_and(|(doc, i, key)| *doc == doc_id && *i == index && *key == source);
|
||||
if world != before {
|
||||
self.canvas_workspace.reference_cards.insert(source.clone(), world);
|
||||
layout.placements.insert(source, Some(world));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if can_interact || drag.is_some() {
|
||||
owns_primary = true;
|
||||
ui.ctx().set_cursor_icon(if down && drag.is_some() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
|
||||
}
|
||||
let rect = world_rect(xf, world);
|
||||
if moving_from_dock || !rect.intersect(xf.rect).intersect(ui.clip_rect()).is_positive() { continue; }
|
||||
let texture = if (visible_previews.len() < 3 || hovered == Some(index))
|
||||
&& let Some(edge) = reference_preview_edge(rect, ui.ctx().pixels_per_point())
|
||||
{
|
||||
visible_previews.insert(key.clone());
|
||||
self.queue_creation_reference_preview(app, &key, edge);
|
||||
self.creation_reads.reference_previews.get(&key).map_or(thumbnail.id(), |(_, image)| image.id())
|
||||
} else {
|
||||
thumbnail.id()
|
||||
};
|
||||
painter.add(candidate_image_shape(ui.ctx(), texture, world, xf, 1.0));
|
||||
self.canvas_workspace.geometry.insert(format!("product-reference:{index}"), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
}
|
||||
self.creation_reads.reference_previews.retain(|key, _| visible_previews.contains(key));
|
||||
if !down { self.canvas_workspace.reference_drag = None; }
|
||||
if layout != saved {
|
||||
ui.ctx().data_mut(|data| data.insert_persisted(layout_id, layout));
|
||||
}
|
||||
owns_primary
|
||||
}
|
||||
|
||||
/// 产品图收纳坞:画布内容区左下角的一组小按钮,点开后在按钮组正上方弹出浮层。
|
||||
/// 两者都浮在画布上,不改变画布视口;浮层的开合只在本次运行内有效,默认收起。
|
||||
pub(crate) fn reference_dock(&mut self, app: &PhotocraftApp, ui: &mut Ui, doc: u64, viewport: Rect) {
|
||||
use crate::theme::agent_scale::{control, motion, radius, space};
|
||||
/// 按钮组离画布内容区左边、横向滚动条各 10。
|
||||
const EDGE: f32 = 10.0;
|
||||
/// 底板外沿到按钮 3:内边距 2 加 1px 描边,按钮组高 `STANDARD + 6`。
|
||||
const PLATE_MARGIN: i8 = 2;
|
||||
const INSET: f32 = 3.0;
|
||||
/// 浮层在按钮组上方 8,开合时带 6 的位移;最宽占画布 60%,最高占 40%。
|
||||
const GAP: f32 = 8.0;
|
||||
const RISE: f32 = 6.0;
|
||||
const POPOVER_RADIUS: u8 = 10;
|
||||
|
||||
self.canvas_workspace.reference_dock_cover.clear();
|
||||
let popover_layer = reference_dock_layer("popover");
|
||||
let reveal_id = popover_layer.with("reveal");
|
||||
let shown = !(self.professional_mode || self.library || self.material || (self.creation_open && self.creation_step != 3)
|
||||
|| self.professional_child_active(app) || !self.canvas_scope_valid(app))
|
||||
&& bound_project(self, doc).is_some();
|
||||
let images = if shown && self.template_workflow["canvasFirst"] == true { self.product_reference_images(doc) } else { Vec::new() };
|
||||
let resources = if shown { self.production_assets().count() } else { 0 };
|
||||
let show_resources = shown && (self.template_workflow["canvasFirst"] == true || resources > 0);
|
||||
if images.is_empty() && !show_resources {
|
||||
// 收纳坞不显示时浮层直接收起,回到画布时不补播退场。
|
||||
self.canvas_workspace.reference_popover.open = None;
|
||||
ui.ctx().animate_bool_with_time(reveal_id, false, 0.0);
|
||||
return;
|
||||
}
|
||||
|
||||
let enabled = app.ui.dialogs.is_empty() && app.ui.transform.is_none() && self.canvas_workspace.regen.is_none()
|
||||
&& !ui.memory(|memory| memory.top_modal_layer().is_some()) && !egui::Popup::is_any_open(ui.ctx());
|
||||
let mut popover = self.canvas_workspace.reference_popover;
|
||||
// 换了文档立即收起;对话框、变换、重生成或其他弹层出现时淡出收起。
|
||||
let switched = popover.open.is_some_and(|open| open != doc);
|
||||
if switched || !enabled { popover.open = None; }
|
||||
if images.is_empty() { popover.tab = ReferenceDockTab::Resources; }
|
||||
else if !show_resources { popover.tab = ReferenceDockTab::Products; }
|
||||
|
||||
let ctx = ui.ctx().clone();
|
||||
let t = Tokens::get(&ctx).agent();
|
||||
let reduced = self.reduce_motion;
|
||||
let canvas = crate::rulers::content_rect(app, viewport);
|
||||
let scrollbar = if app.ui.view.shows_scrollbars() { crate::scrollbars::THICKNESS } else { 0.0 };
|
||||
let plate_height = control::STANDARD + 2.0 * INSET;
|
||||
let buttons = reference_dock_layer("buttons");
|
||||
let mut clicked = None;
|
||||
let group = egui::Area::new(buttons).order(egui::Order::Middle).fade_in(false)
|
||||
.fixed_pos(pos2(canvas.left() + EDGE, canvas.bottom() - scrollbar - EDGE - plate_height))
|
||||
.show(&ctx, |ui| {
|
||||
egui::Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.field_border))
|
||||
.corner_radius(radius::MENU as u8).inner_margin(PLATE_MARGIN)
|
||||
.show(ui, |ui| super::stitch_ui::scope_with_motion(ui, reduced, |ui| {
|
||||
if !enabled { ui.disable(); }
|
||||
reference_dock_button_style(ui, t, radius::MENU - INSET, INSET);
|
||||
ui.horizontal(|ui| {
|
||||
for (item, glyph, count, geometry) in [
|
||||
(ReferenceDockTab::Products, "image", images.len(), "productDockToggle"),
|
||||
(ReferenceDockTab::Resources, "folder-open", resources, "imageResourcesToggle"),
|
||||
] {
|
||||
if count == 0 && !(item == ReferenceDockTab::Resources && show_resources) { continue; }
|
||||
let label = if count == 0 { item.label().to_owned() } else { format!("{} · {count} 张", item.label()) };
|
||||
let response = kit::counted_icon_button(ui, glyph, count, &label, popover.open.is_some() && popover.tab == item);
|
||||
self.canvas_workspace.geometry.insert(geometry.into(), rect_geometry(response.rect));
|
||||
if item == ReferenceDockTab::Resources {
|
||||
self.record_production_images_tag_geometry(response.rect);
|
||||
}
|
||||
// 不常驻文字:悬停或键盘焦点落在按钮上时用提示说明。
|
||||
let response = if response.has_focus() {
|
||||
response.show_tooltip_text(label.as_str());
|
||||
response
|
||||
} else {
|
||||
response.on_hover_text(label.as_str())
|
||||
};
|
||||
if response.clicked() { clicked = Some(item); }
|
||||
}
|
||||
});
|
||||
}));
|
||||
}).response.rect;
|
||||
self.canvas_workspace.geometry.insert("referenceDock".into(), rect_geometry(group));
|
||||
self.canvas_workspace.reference_dock_cover.push(group);
|
||||
|
||||
// 再点同一个按钮收起、点另一个切换内容;点浮层外面或按 Esc 收起。
|
||||
// 按住鼠标拖动时 Esc 先留给拖动取消。
|
||||
let (click, dragging) = ctx.input(|input| (
|
||||
input.pointer.any_click().then(|| input.pointer.interact_pos()).flatten(), input.pointer.any_down()));
|
||||
let clicked_outside = click.is_some_and(|point| {
|
||||
ctx.layer_id_at(point).is_none_or(|layer| layer.id != buttons && layer.id != popover_layer)
|
||||
});
|
||||
if let Some(item) = clicked {
|
||||
let open = !(popover.open.is_some() && popover.tab == item);
|
||||
popover = ReferencePopover { open: open.then_some(doc), tab: item };
|
||||
} else if popover.open.is_some() && (clicked_outside
|
||||
|| (!dragging && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape))))
|
||||
{
|
||||
popover.open = None;
|
||||
}
|
||||
self.canvas_workspace.reference_popover = popover;
|
||||
|
||||
let instant = reduced || switched || super::agent_motion::hidden(ui, canvas);
|
||||
let reveal = ctx.animate_bool_with_time_and_easing(reveal_id, popover.open.is_some(),
|
||||
if instant { 0.0 } else { motion::NATIVE }, egui::emath::easing::cubic_out);
|
||||
if reveal <= 0.0 { return; }
|
||||
let interactive = popover.open.is_some();
|
||||
let frame = egui::Frame::NONE.fill(t.card).stroke(Stroke::new(1.0, t.field_border))
|
||||
.corner_radius(POPOVER_RADIUS).inner_margin(space::SM as i8)
|
||||
.shadow(egui::Shadow { color: t.shadow, ..ctx.global_style().visuals.popup_shadow });
|
||||
let content = vec2(canvas.width() * 0.6, canvas.height() * 0.4) - frame.total_margin().sum();
|
||||
// 浮层底边钉在按钮组上方,尺寸变了(换内容、图片到达)就重排这一帧,不让它闪到按钮组上。
|
||||
let measured = egui::AreaState::load(&ctx, popover_layer).and_then(|state| state.size);
|
||||
let sheet = egui::Area::new(popover_layer).order(egui::Order::Middle).fade_in(false)
|
||||
.pivot(Align2::LEFT_BOTTOM).fixed_pos(pos2(group.left(), group.top() - GAP + RISE * (1.0 - reveal)))
|
||||
.interactable(interactive)
|
||||
.show(&ctx, |ui| {
|
||||
let visual = super::stitch_ui::OverlayVisual { render: true, interactive, opacity: reveal };
|
||||
super::stitch_ui::overlay_contents(ui, visual, |ui| frame.show(ui, |ui| {
|
||||
super::stitch_ui::scope_with_motion(ui, reduced, |ui| {
|
||||
ui.set_max_size(content.max(Vec2::ZERO));
|
||||
match popover.tab {
|
||||
ReferenceDockTab::Products => self.product_dock_thumbnails(app, ui, doc, &images),
|
||||
ReferenceDockTab::Resources => {
|
||||
self.production_assets_ui(ui, doc);
|
||||
if interactive {
|
||||
self.record_image_resources_clip_geometry(ui.min_rect());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}));
|
||||
}).response.rect;
|
||||
if measured.is_some_and(|size| size != sheet.size()) {
|
||||
ctx.request_discard("产品图收纳坞浮层换了尺寸");
|
||||
}
|
||||
self.canvas_workspace.geometry.insert("referenceDockPopover".into(), rect_geometry(sheet));
|
||||
if interactive { self.canvas_workspace.reference_dock_cover.push(sheet); }
|
||||
}
|
||||
|
||||
pub(crate) fn product_dock_thumbnails(&mut self, app: &PhotocraftApp, ui: &mut Ui, doc: u64, images: &[(String, String)]) {
|
||||
const THUMBNAIL: f32 = 64.0;
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
egui::ScrollArea::horizontal().id_salt("product-reference-thumbnails").show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = crate::theme::agent_scale::space::SM;
|
||||
ui.horizontal(|ui| {
|
||||
for (index, (source, name)) in images.iter().enumerate() {
|
||||
let (cell, response) = ui.allocate_exact_size(Vec2::splat(THUMBNAIL), Sense::drag());
|
||||
if !ui.is_rect_visible(cell) { continue; }
|
||||
self.canvas_workspace.geometry.insert(format!("product-dock:{index}"), rect_geometry(cell));
|
||||
self.queue_creation_reference(app, source);
|
||||
let key = super::creation_reads::reference_key(source);
|
||||
let Some(texture) = self.creation_thumbs.get(&key) else {
|
||||
ui.painter().rect_filled(cell, t.radius_sm, t.field);
|
||||
continue;
|
||||
};
|
||||
let size = texture.size_vec2();
|
||||
let image = Rect::from_center_size(cell.center(), size * (THUMBNAIL / size.x.max(size.y)));
|
||||
egui::Image::new(texture).corner_radius(t.radius_sm).paint_at(ui, image);
|
||||
if response.drag_started_by(egui::PointerButton::Primary) {
|
||||
self.canvas_workspace.reference_dock_drag = Some((doc, index, source.clone()));
|
||||
}
|
||||
response.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(format!("{name} · 拖到画布"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn place_docked_reference(&mut self, ui: &Ui, xf: ViewXform, doc: u64, enabled: bool, layout: &mut ReferenceDockLayout) -> bool {
|
||||
let (pointer, down, released, cancelled) = ui.input(|input| (
|
||||
input.pointer.interact_pos(), input.pointer.primary_down(), input.pointer.primary_released(),
|
||||
input.pointer.middle_down() || input.key_pressed(egui::Key::Escape)));
|
||||
let dragging = self.canvas_workspace.reference_dock_drag.clone();
|
||||
if let Some((active_doc, _, source)) = dragging.as_ref() {
|
||||
if enabled && !cancelled && *active_doc == doc
|
||||
&& let Some(point) = pointer.filter(|point| self.canvas_workspace.on_canvas(xf.rect, *point))
|
||||
&& let Some(texture) = self.creation_thumbs.get(&super::creation_reads::reference_key(source))
|
||||
{
|
||||
let size = texture.size_vec2();
|
||||
let default = size * (720.0 / size.x.max(size.y));
|
||||
let world = self.canvas_workspace.reference_cards.get(source).copied()
|
||||
.unwrap_or([0.0,0.0,default.x,default.y]);
|
||||
let [x, y] = xf.to_doc(point);
|
||||
let dropped = [x as f32 - world[2]/2.0, y as f32 - world[3]/2.0, world[2], world[3]];
|
||||
if released {
|
||||
self.canvas_workspace.reference_cards.insert(source.clone(), dropped);
|
||||
layout.placements.insert(source.clone(), Some(dropped));
|
||||
} else if down {
|
||||
let mut painter = ui.painter_at(xf.rect);
|
||||
painter.set_clip_rect(xf.rect);
|
||||
painter.add(candidate_image_shape(ui.ctx(),texture.id(),dropped,xf,0.8));
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
}
|
||||
if !down || cancelled || !enabled || *active_doc != doc {
|
||||
self.canvas_workspace.reference_dock_drag = None;
|
||||
}
|
||||
}
|
||||
enabled && dragging.is_some()
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,313 @@
|
||||
use super::super::{json, Document, PhotocraftApp, Request, Tokens, Ui, Value, Workspace};
|
||||
use super::super::stitch_ui as kit;
|
||||
use super::document::{adopted, manual_image};
|
||||
use super::projection::{candidates, first_generated_preview, rows, target_summary};
|
||||
use egui::{Color32, FontId, Rect, Sense, Stroke, vec2};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RegenerationSnapshot {
|
||||
pub(crate) target: Value,
|
||||
pub(crate) prompt: String,
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn regeneration_template_prompt<'a>(workflow: &'a Value, target: &Value) -> Option<&'a str> {
|
||||
let slot_id = target["slotId"].as_str()?;
|
||||
let slot = workflow["slots"].as_array()?.iter()
|
||||
.find(|slot| slot["id"] == slot_id && slot["outputId"] == target["outputId"] && slot["variantId"] == target["productVariantId"])?;
|
||||
slot["templatePrompt"].as_str().filter(|prompt| !prompt.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(crate) fn plain_native_reference_valid(doc: &Document, target: &Value) -> bool {
|
||||
if target["kind"] == "selection" {
|
||||
return target["targets"].as_array().is_some_and(|targets| !targets.is_empty() && targets.iter().all(|target| plain_native_reference_valid(doc, target)));
|
||||
}
|
||||
if target["slotId"].is_string() || target["candidateId"].is_string() { return false; }
|
||||
let Some(layer) = target["nativeLayerId"].as_u64().and_then(|id| doc.layer(photocraft_doc::LayerId(id))) else { return false };
|
||||
match target["component"].as_str().unwrap_or("layer") {
|
||||
"layer" => true,
|
||||
"pixelMask" => layer.mask.is_some(),
|
||||
"vectorMask" => layer.vector_mask.is_some(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn modal_product_references(&self, doc: Option<u64>) -> Vec<(usize, String, String)> {
|
||||
if let Some(items) = self.template_workflow["productReferences"].as_array() {
|
||||
return items.iter().enumerate().filter_map(|(fallback_idx, item)| {
|
||||
if item["purpose"] != "product" { return None; }
|
||||
let idx = item["index"].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(fallback_idx);
|
||||
let source = item["source"].as_str()?.to_owned();
|
||||
let name = item["name"].as_str().unwrap_or("产品实拍图").to_owned();
|
||||
Some((idx, source, name))
|
||||
}).collect();
|
||||
}
|
||||
doc.map(|doc| self.product_reference_images(doc).into_iter().enumerate()
|
||||
.map(|(idx, (source, name))| (idx, source, name)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn regeneration_window(&mut self, app: &PhotocraftApp, ui: &mut Ui) {
|
||||
let id = egui::Id::unique(("canvas-regenerate", &self.origin, self.account["id"].as_str(), self.owner_doc, &self.canvas_workspace.binding));
|
||||
let snapshot_id = id.with("exit-snapshot");
|
||||
let open = self.canvas_workspace.regen.is_some();
|
||||
if let Some(target) = self.canvas_workspace.regen.as_ref() {
|
||||
ui.data_mut(|data| data.insert_temp(snapshot_id, RegenerationSnapshot { target:target.clone(), prompt:self.canvas_workspace.prompt.clone() }));
|
||||
}
|
||||
let visual = super::stitch_ui::overlay_transition(ui.ctx(), id.with("lifetime"), open, self.reduce_motion);
|
||||
if !visual.render {
|
||||
ui.data_mut(|data| data.remove::<RegenerationSnapshot>(snapshot_id));
|
||||
return;
|
||||
}
|
||||
let Some(snapshot) = ui.data(|data| data.get_temp::<RegenerationSnapshot>(snapshot_id)) else { return };
|
||||
let target = snapshot.target;
|
||||
let mut prompt = snapshot.prompt;
|
||||
let editing_candidate = target["candidateId"].as_str().is_some_and(|id| !id.is_empty());
|
||||
let title = if editing_candidate { "重新生成" } else { "生成图片" };
|
||||
let mut submit = false;
|
||||
let mut selected_product_original: Option<usize> = None;
|
||||
let mut cancel = false;
|
||||
let mut closed = false;
|
||||
use super::stitch_ui::{self as kit, ButtonRole};
|
||||
let session = self.canvas_workspace.regen_session;
|
||||
let prompt_id = id.with(("prompt", session));
|
||||
let reduce_motion = self.reduce_motion;
|
||||
let response = kit::modal(ui.ctx(), id.with("surface"), visual, reduce_motion, |ui| {
|
||||
let width = 490.0_f32.min((ui.ctx().content_rect().width() - 80.0).max(180.0));
|
||||
ui.set_width(width);
|
||||
let tokens = Tokens::get(ui.ctx()).agent();
|
||||
let label = target["label"].as_str().unwrap_or("当前图片").replace('-', " · ");
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(title).size(18.0).strong());
|
||||
ui.add_space(8.0);
|
||||
ui.add(crate::icons::image("scan", 14.0, tokens.text_dim));
|
||||
let width = (ui.available_width() - 36.0).max(20.0);
|
||||
ui.allocate_ui_with_layout(vec2(width, 26.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(&label).color(tokens.text_dim)).truncate()).on_hover_text(label);
|
||||
});
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
closed = kit::icon_button(ui, "x", 28.0, false, "关闭").clicked();
|
||||
});
|
||||
});
|
||||
if !self.canvas_workspace.regen_error.is_empty() {
|
||||
kit::status_chip(ui, &self.canvas_workspace.regen_error, kit::StatusTone::Error);
|
||||
}
|
||||
ui.add_space(5.0);
|
||||
ui.label(egui::RichText::new("图片提示词").strong());
|
||||
|
||||
let editor_height = (ui.ctx().content_rect().height() * 0.35).clamp(104.0, 264.0);
|
||||
let mut editor_bounds = Rect::NOTHING;
|
||||
let field = kit::surface_frame(ui.ctx(), kit::SurfaceRole::Input).show(ui, |ui| {
|
||||
let editor = egui::ScrollArea::vertical()
|
||||
.id_salt(prompt_id)
|
||||
.min_scrolled_height(editor_height)
|
||||
.max_height(editor_height)
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.add(kit::text_input(&mut prompt, "说说你想怎么调整画面,例如:保留我们实拍椅子的弧形靠背和胡桃木扶手,换成暖白阳光客厅背景…", true)
|
||||
.id(prompt_id)
|
||||
.font(FontId::proportional(14.0))
|
||||
.min_size(vec2(0.0, editor_height))
|
||||
.desired_width(f32::INFINITY)
|
||||
.cursor_at_end(false)
|
||||
.frame(egui::Frame::NONE)
|
||||
.char_limit(2000))
|
||||
});
|
||||
editor_bounds = editor.inner_rect;
|
||||
editor.inner
|
||||
});
|
||||
let response = field.inner;
|
||||
super::agent_motion::role_light(ui,
|
||||
super::agent_motion::Surface::new(prompt_id.with("field"), field.response.rect.shrink(0.5), 9.0),
|
||||
reduce_motion,
|
||||
super::agent_motion::LightRole::Field { focused: visual.interactive && response.has_focus(), hovered: false },
|
||||
);
|
||||
if visual.interactive && ui.data_mut(|data| {
|
||||
if data.get_temp::<u64>(id.with("focused-session")) == Some(session) { return false; }
|
||||
data.insert_temp(id.with("focused-session"), session);
|
||||
true
|
||||
}) {
|
||||
response.request_focus();
|
||||
}
|
||||
if open && response.changed() {
|
||||
self.canvas_workspace.prompt = prompt.clone();
|
||||
self.canvas_workspace.regen_edited();
|
||||
ui.data_mut(|data| data.insert_temp(snapshot_id, RegenerationSnapshot { target: target.clone(), prompt }));
|
||||
}
|
||||
let rect = response.rect.intersect(editor_bounds);
|
||||
self.canvas_workspace.geometry.insert("regenerate-prompt".into(), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
|
||||
ui.add_space(7.0);
|
||||
let active_doc = app.session.active().map(|s| s.doc.id.0);
|
||||
let product_refs = self.modal_product_references(active_doc);
|
||||
if open && !product_refs.is_empty() && self.canvas_workspace.regen_selected_refs.is_empty()
|
||||
&& !self.template_workflow["productReferences"].is_array()
|
||||
{
|
||||
for (idx, _, _) in &product_refs {
|
||||
self.canvas_workspace.regen_selected_refs.insert(*idx);
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new("参考图").strong());
|
||||
if product_refs.is_empty() {
|
||||
ui.weak("当前商品尚未上传产品实拍图");
|
||||
} else {
|
||||
ui.weak(format!("已选 {}/{} 张产品实拍图(作为外观/结构依据)",
|
||||
self.canvas_workspace.regen_selected_refs.len(), product_refs.len()));
|
||||
}
|
||||
});
|
||||
if !product_refs.is_empty() {
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::horizontal().id_salt(id.with(("refs", session))).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (idx, source, name) in &product_refs {
|
||||
let selected = self.canvas_workspace.regen_selected_refs.contains(idx);
|
||||
self.queue_creation_reference(app, source);
|
||||
let key = super::creation_reads::reference_key(source);
|
||||
let (cell, resp) = ui.allocate_exact_size(vec2(52.0, 52.0), Sense::click());
|
||||
let stroke = if selected { Stroke::new(2.0, tokens.accent) } else { Stroke::new(1.0, tokens.field_border) };
|
||||
ui.painter().rect_filled(cell, tokens.radius_sm, tokens.field);
|
||||
if let Some(texture) = self.creation_thumbs.get(&key) {
|
||||
let size = texture.size_vec2();
|
||||
let image_rect = Rect::from_center_size(cell.center(), size * (48.0 / size.x.max(size.y)));
|
||||
egui::Image::new(texture).corner_radius(tokens.radius_sm).paint_at(ui, image_rect);
|
||||
}
|
||||
ui.painter().rect_stroke(cell, tokens.radius_sm, stroke, egui::StrokeKind::Inside);
|
||||
let badge_rect = Rect::from_min_size(cell.left_top() + vec2(3.0, 3.0), vec2(26.0, 16.0));
|
||||
ui.painter().rect_filled(badge_rect, 3.0, if selected { tokens.accent } else { Color32::from_black_alpha(170) });
|
||||
ui.painter().text(badge_rect.center(), egui::Align2::CENTER_CENTER, format!("图{}", idx + 1), FontId::proportional(10.0), Color32::WHITE);
|
||||
if resp.on_hover_text(format!("图{} · {}(点击{})", idx + 1, name, if selected { "取消参考" } else { "加入参考" })).clicked() && open {
|
||||
if selected {
|
||||
self.canvas_workspace.regen_selected_refs.remove(idx);
|
||||
} else {
|
||||
self.canvas_workspace.regen_selected_refs.insert(*idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut self.canvas_workspace.regen_use_template_base, "参考当前模板构图");
|
||||
ui.weak("仅参考构图与留白,不沿用旧产品");
|
||||
});
|
||||
ui.add_space(5.0);
|
||||
let slot_busy = self.slot_generation_busy(&target);
|
||||
let missing_refs = !product_refs.is_empty() && self.canvas_workspace.regen_selected_refs.is_empty();
|
||||
let can_generate = open && !slot_busy && self.image_ready && !missing_refs;
|
||||
let disable_reason = if !open || can_generate {
|
||||
None
|
||||
} else if slot_busy {
|
||||
Some("当前图位正在生成中…")
|
||||
} else if !self.image_ready {
|
||||
Some("未检测到可用生图服务,请先检查连接")
|
||||
} else {
|
||||
Some("请至少勾选一张产品实拍图")
|
||||
};
|
||||
let footer_note = disable_reason.unwrap_or("新增候选,保留已有图片");
|
||||
if !editing_candidate {
|
||||
let original = kit::action_button(ui, "使用产品原图", ButtonRole::Secondary, open);
|
||||
self.canvas_workspace.geometry.insert("regenerate-product-original".into(),
|
||||
[original.rect.min.x, original.rect.min.y, original.rect.width(), original.rect.height()]);
|
||||
if original.clicked() {
|
||||
self.canvas_workspace.regen_picking_original = !self.canvas_workspace.regen_picking_original;
|
||||
}
|
||||
if self.canvas_workspace.regen_picking_original {
|
||||
ui.add_space(4.0);
|
||||
kit::surface_frame(ui.ctx(), kit::SurfaceRole::Task).show(ui, |ui| {
|
||||
if product_refs.is_empty() {
|
||||
ui.weak("当前商品尚未上传产品实拍图");
|
||||
} else {
|
||||
ui.weak("点击下方实拍图,直接放到当前画布图位:");
|
||||
ui.add_space(4.0);
|
||||
egui::ScrollArea::horizontal().id_salt(id.with(("pick-original", session))).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for (idx, source, name) in &product_refs {
|
||||
self.queue_creation_reference(app, source);
|
||||
let key = super::creation_reads::reference_key(source);
|
||||
let (cell, resp) = ui.allocate_exact_size(vec2(58.0, 58.0), Sense::click());
|
||||
ui.painter().rect_filled(cell, tokens.radius_sm, tokens.field);
|
||||
if let Some(texture) = self.creation_thumbs.get(&key) {
|
||||
let size = texture.size_vec2();
|
||||
let image_rect = Rect::from_center_size(cell.center(), size * (54.0 / size.x.max(size.y)));
|
||||
egui::Image::new(texture).corner_radius(tokens.radius_sm).paint_at(ui, image_rect);
|
||||
}
|
||||
ui.painter().rect_stroke(cell, tokens.radius_sm, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside);
|
||||
let badge_rect = Rect::from_min_size(cell.left_top() + vec2(3.0, 3.0), vec2(26.0, 16.0));
|
||||
ui.painter().rect_filled(badge_rect, 3.0, Color32::from_black_alpha(180));
|
||||
ui.painter().text(badge_rect.center(), egui::Align2::CENTER_CENTER, format!("图{}", idx + 1), FontId::proportional(10.0), Color32::WHITE);
|
||||
if resp.on_hover_text(format!("点击直接将 图{} · {} 放到画布", idx + 1, name)).clicked() && open {
|
||||
selected_product_original = Some(*idx);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if width < 300.0 {
|
||||
if disable_reason.is_some() {
|
||||
ui.colored_label(tokens.warning, footer_note);
|
||||
} else {
|
||||
ui.weak(footer_note);
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let button = kit::action_button(ui, "生成候选", ButtonRole::Primary, can_generate);
|
||||
self.canvas_workspace.geometry.insert("regenerate-submit".into(),
|
||||
[button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
|
||||
submit = button.clicked();
|
||||
cancel = kit::action_button(ui, "取消", ButtonRole::Quiet, open).clicked();
|
||||
if width >= 300.0 {
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
if disable_reason.is_some() {
|
||||
ui.colored_label(tokens.warning, footer_note);
|
||||
} else {
|
||||
ui.weak(footer_note);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
if open && (closed || cancel || response.is_some_and(|r| r.should_close()) || ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape))) {
|
||||
self.canvas_workspace.invalidate_regen();
|
||||
}
|
||||
if let Some(ref_index) = selected_product_original {
|
||||
let doc_id = app.session.active().map(|s| s.doc.id.0);
|
||||
let result = self.canvas_workspace.regeneration_input(&self.template_workflow).and_then(|mut input| {
|
||||
input["useProductReference"] = json!(true);
|
||||
input["referenceIndex"] = json!(ref_index);
|
||||
input["adoptImmediately"] = json!(true);
|
||||
input["manualImage"] = json!(false);
|
||||
if let Some(doc) = doc_id {
|
||||
self.canvas_workspace.pending_product_original_adopt = Some(json!({
|
||||
"doc": doc,
|
||||
"slotId": input["slotId"],
|
||||
"variantId": input["variantId"],
|
||||
"nativeLayerId": input["nativeLayerId"],
|
||||
}));
|
||||
}
|
||||
self.slot_action(app, "slot-append", input)
|
||||
});
|
||||
match result {
|
||||
Ok(_) => {
|
||||
self.canvas_workspace.invalidate_regen();
|
||||
self.note("正在将产品原图放到画布…");
|
||||
}
|
||||
Err(error) => {
|
||||
self.canvas_workspace.pending_product_original_adopt = None;
|
||||
self.canvas_workspace.regen_error = error;
|
||||
}
|
||||
}
|
||||
} else if submit {
|
||||
self.canvas_workspace.regen_error.clear();
|
||||
if let Err(error) = self.submit_regeneration(app) {
|
||||
self.canvas_workspace.regen_error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,500 @@
|
||||
use super::super::{LayerContent, json, Instant, PhotocraftApp, Request, Tokens, Ui, Value, Workspace};
|
||||
use super::super::stitch_ui as kit;
|
||||
use super::document::{adopted, document_mapping, hidden_unfilled_sample, manual_image, native_layer};
|
||||
use super::projection::{
|
||||
candidate_group, candidates, fit_tag_selection, location, matches_candidate,
|
||||
native_selection_subject, rows, scope, short_slot_label, target_summary, world_rect, Row,
|
||||
};
|
||||
use super::regeneration_ui::plain_native_reference_valid;
|
||||
use super::{bound_project, CameraRequest};
|
||||
use crate::canvas::ViewXform;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Vec2, pos2, vec2};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct LocateMotion {
|
||||
pub(crate) from: [f32; 2],
|
||||
pub(crate) to: [f32; 2],
|
||||
pub(crate) started: f64,
|
||||
pub(crate) duration: f64,
|
||||
pub(crate) smooth: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct CanvasFeedback {
|
||||
pub(crate) doc: u64,
|
||||
pub(crate) target: Value,
|
||||
pub(crate) label: String,
|
||||
pub(crate) edit: bool,
|
||||
pub(crate) image_replacement: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct FeedbackDisplay {
|
||||
pub(crate) feedback: CanvasFeedback,
|
||||
pub(crate) motion: Option<LocateMotion>,
|
||||
pub(crate) arrived: f64,
|
||||
}
|
||||
|
||||
impl LocateMotion {
|
||||
pub(crate) fn progress(self, now: f64) -> f32 {
|
||||
((now - self.started) / self.duration).clamp(0.0, 1.0) as f32
|
||||
}
|
||||
|
||||
pub(crate) fn camera(self, progress: f32) -> CameraRequest {
|
||||
let ease = if self.smooth {
|
||||
progress.powi(3) * (10.0 + progress * (-15.0 + 6.0 * progress))
|
||||
} else {
|
||||
1.0 - (1.0 - progress).powi(3)
|
||||
};
|
||||
CameraRequest {
|
||||
center: [
|
||||
self.from[0] + (self.to[0] - self.from[0]) * ease,
|
||||
self.from[1] + (self.to[1] - self.from[1]) * ease,
|
||||
],
|
||||
zoom: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const FEEDBACK_IDLE: f64 = 10.0;
|
||||
const FEEDBACK_DISPLAY: f64 = 1.30;
|
||||
|
||||
|
||||
impl Workspace {
|
||||
pub(crate) fn canvas_subject(&self, app: &PhotocraftApp) -> Value {
|
||||
let native = || {
|
||||
let state = app.session.active()?;
|
||||
let selected: Vec<_> = state.selected_layers().iter().map(|id| id.0).collect();
|
||||
native_selection_subject(&state.doc, &self.template_workflow, &self.canvas_workspace.variant, "", &selected)
|
||||
};
|
||||
// Formal and retained legacy template requests keep their explicit
|
||||
// slot/candidate target. Plain native layer selections must follow the
|
||||
// real selection rather than an old overlay layer snapshot.
|
||||
let template_target = self.template_workflow["canvasFirst"] == true
|
||||
|| (self.template_workflow["templateId"].as_str().is_some_and(|id| !id.is_empty())
|
||||
&& self.canvas_workspace.context.as_ref().is_some_and(|target| matches!(target["kind"].as_str(), Some("slot" | "candidate"))));
|
||||
let subject = if template_target { self.canvas_workspace.context.clone().or_else(native) } else { native() };
|
||||
subject
|
||||
.unwrap_or_else(|| json!({"kind":"project","label":"当前项目"}))
|
||||
}
|
||||
|
||||
pub(crate) fn professional_entry_layer(&self, app: &PhotocraftApp) -> Option<u64> {
|
||||
let state = app.session.active()?;
|
||||
if self.pending() || self.saving.is_some() || self.pending_slot_apply.is_some()
|
||||
|| self.canvas_workspace.pending_adoption.is_some() || self.canvas_workspace.scope_switch_in_flight {
|
||||
return None;
|
||||
}
|
||||
let mapped = document_mapping(&state.doc).is_some_and(|mapping| mapping["canvasFirst"] == true);
|
||||
let formal = self.template_workflow["canvasFirst"] == true;
|
||||
// A formal template without its matching workflow is never downgraded
|
||||
// to the ordinary-image entry when a catalogue/read is unavailable.
|
||||
if (mapped && !formal) || !self.canvas_scope_valid(app) { return None; }
|
||||
let target = self.canvas_subject(app);
|
||||
let id = target["nativeLayerId"].as_u64()?;
|
||||
let layer = state.doc.layer(photocraft_doc::LayerId(id))?;
|
||||
let LayerContent::Smart(smart) = &layer.content else { return None };
|
||||
if formal {
|
||||
if !matches!(target["kind"].as_str(), Some("slot" | "candidate"))
|
||||
|| target["productVariantId"] != self.canvas_workspace.variant || target["outputId"] != self.canvas_workspace.output {
|
||||
return None;
|
||||
}
|
||||
let slot_id = target["slotId"].as_str()?;
|
||||
if native_layer(&state.doc, slot_id) != Some(id) { return None; }
|
||||
if target["kind"] == "slot" && hidden_unfilled_sample(&state.doc, layer, slot_id, &self.canvas_workspace.variant) {
|
||||
return None;
|
||||
}
|
||||
if target["kind"] == "candidate" {
|
||||
let candidate = self.template_workflow["slots"].as_array()?.iter().find(|slot| slot["id"] == slot_id)?;
|
||||
return candidates(candidate).iter().any(|candidate| candidate["id"] == target["candidateId"] && candidate["status"] == "complete").then_some(id);
|
||||
}
|
||||
} else if target["kind"] != "layer" || state.selected_layers() != [photocraft_doc::LayerId(id)] {
|
||||
return None;
|
||||
}
|
||||
(!matches!(&smart.source, photocraft_doc::SmartSource::Embedded { file_name, .. } if file_name == "template-empty.png")).then_some(id)
|
||||
}
|
||||
|
||||
pub(crate) fn record_professional_control(&mut self, name: &str, response: &egui::Response) {
|
||||
if !matches!(name, "professionalEnter" | "professionalApply" | "professionalReturn") { return; }
|
||||
let rect = response.rect;
|
||||
if rect.is_finite() && rect.is_positive() && response.ctx.content_rect().intersects(rect) {
|
||||
self.canvas_workspace.geometry.insert(name.into(), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
self.canvas_workspace.professional_controls.insert(name.into(), response.enabled());
|
||||
}
|
||||
}
|
||||
|
||||
/// Result/task clicks only locate their own target. They do not submit,
|
||||
/// adopt, replace the chat transcript, or change the current zoom.
|
||||
pub(crate) fn canvas_locate(&mut self, target: Value) {
|
||||
let mut normalized = target.clone();
|
||||
if target["kind"] != "selection"
|
||||
&& let Some(slot) = self.template_workflow["slots"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|slot| target["slotId"] == slot["id"] || candidates(slot).iter().any(|candidate| matches_candidate(candidate, &target)))
|
||||
{
|
||||
let candidate = candidates(slot).iter().find(|candidate| matches_candidate(candidate, &target));
|
||||
let variant = target["productVariantId"]
|
||||
.as_str()
|
||||
.or(target["variantId"].as_str())
|
||||
.or_else(|| candidate.and_then(|candidate| candidate["variantId"].as_str()))
|
||||
.or(slot["variantId"].as_str())
|
||||
.unwrap_or(&self.canvas_workspace.variant);
|
||||
let label = self.creation_brief["variants"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|item| item["id"] == variant)
|
||||
.and_then(|item| item["name"].as_str())
|
||||
.unwrap_or("");
|
||||
normalized = scope(slot, candidate, variant, label);
|
||||
if target["nativeLayerId"].is_u64() {
|
||||
normalized["nativeLayerId"] = target["nativeLayerId"].clone();
|
||||
}
|
||||
}
|
||||
self.canvas_workspace.locate_queued_scope = target["documentId"].as_u64().map(|doc| json!({
|
||||
"account":self.account["id"], "origin":self.origin, "project":bound_project(self, doc), "doc":doc, "revision":target["revision"]
|
||||
}));
|
||||
self.canvas_workspace.locate_request = Some(normalized);
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
}
|
||||
|
||||
pub(crate) fn queue_canvas_feedback(&mut self, doc: u64, target: Value, label: impl Into<String>) {
|
||||
if self.agent_effects_paused { return; }
|
||||
let state = &mut self.canvas_workspace;
|
||||
state.feedback_queue.retain(|item| item.doc != doc
|
||||
|| item.target["slotId"] != target["slotId"] || item.target["nativeLayerId"] != target["nativeLayerId"]);
|
||||
let edit = target["nativeLayerId"].is_u64();
|
||||
let label = label.into();
|
||||
let image_replacement = matches!(label.as_str(), "图片已回填" | "图片已替换" | "图片已置入");
|
||||
state.feedback_queue.push_back(CanvasFeedback { doc, target, label, edit, image_replacement });
|
||||
}
|
||||
|
||||
pub(crate) fn canvas_feedback(
|
||||
&mut self, app: &PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc: u64, rows: &[Row<'_>],
|
||||
width: f32, blocked: bool,
|
||||
) -> Option<CameraRequest> {
|
||||
let now = ui.input(|input| input.time);
|
||||
let idle = ui.data(|data| data.get_temp::<f64>(egui::Id::unique("jiansun-canvas-last-input")))
|
||||
.map_or(FEEDBACK_IDLE, |last| now - last);
|
||||
let state = &mut self.canvas_workspace;
|
||||
if self.agent_effects_paused {
|
||||
state.feedback_queue.clear();
|
||||
state.feedback_display = None;
|
||||
return None;
|
||||
}
|
||||
state.feedback_queue.retain(|item| item.doc == doc);
|
||||
let can_show = !blocked && idle >= FEEDBACK_IDLE;
|
||||
if !can_show {
|
||||
if let Some(display) = state.feedback_display.take()
|
||||
&& display.motion.is_some()
|
||||
&& !state.feedback_queue.iter().any(|item| item.target == display.feedback.target)
|
||||
{
|
||||
state.feedback_queue.push_front(display.feedback);
|
||||
}
|
||||
if idle < FEEDBACK_IDLE && let Some(latest) = state.feedback_queue.pop_back() {
|
||||
state.feedback_queue.clear();
|
||||
state.feedback_queue.push_back(latest);
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(FEEDBACK_IDLE - idle));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let locate = |item: &CanvasFeedback| {
|
||||
let current = app.session.active()?;
|
||||
if current.doc.id.0 != item.doc { return None; }
|
||||
let [x, y, w, h] = location(¤t.doc, rows, &item.target, width, &self.agent_images)?;
|
||||
// Automatic feedback follows the part of the target that can actually be drawn.
|
||||
let on_canvas = Rect::from_min_size(pos2(x, y), vec2(w, h)).intersect(
|
||||
Rect::from_min_size(pos2(0.0, 0.0), vec2(current.doc.size.width as f32, current.doc.size.height as f32)),
|
||||
);
|
||||
on_canvas.is_positive().then(|| [on_canvas.min.x, on_canvas.min.y, on_canvas.width(), on_canvas.height()])
|
||||
};
|
||||
if state.feedback_display.as_ref().is_some_and(|display|
|
||||
display.feedback.doc != doc || display.motion.is_none() && now - display.arrived >= FEEDBACK_DISPLAY)
|
||||
{
|
||||
state.feedback_display = None;
|
||||
}
|
||||
if state.feedback_display.is_none() {
|
||||
while let Some(feedback) = state.feedback_queue.pop_front() {
|
||||
let Some(bounds) = locate(&feedback) else { continue; };
|
||||
let target = world_rect(xf, bounds);
|
||||
let mut motion = None;
|
||||
if !xf.rect.shrink(48.0).contains_rect(target) {
|
||||
let current = xf.to_doc(xf.rect.center());
|
||||
let distance = (target.center() - xf.rect.center()).length();
|
||||
motion = Some(LocateMotion {
|
||||
from: [current[0] as f32, current[1] as f32],
|
||||
to: [bounds[0] + bounds[2] / 2.0, bounds[1] + bounds[3] / 2.0],
|
||||
started: now,
|
||||
duration: (0.58 + f64::from(distance) / 2100.0).min(1.35),
|
||||
smooth: true,
|
||||
});
|
||||
}
|
||||
state.feedback_display = Some(FeedbackDisplay { feedback, motion, arrived: now });
|
||||
break;
|
||||
}
|
||||
}
|
||||
let display = state.feedback_display.as_mut()?;
|
||||
if let Some(motion) = display.motion {
|
||||
let progress = if self.reduce_motion { 1.0 } else { motion.progress(now) };
|
||||
if progress >= 1.0 {
|
||||
display.motion = None;
|
||||
display.arrived = now;
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
return Some(motion.camera(progress));
|
||||
}
|
||||
let Some(bounds) = locate(&display.feedback) else {
|
||||
state.feedback_display = None;
|
||||
return None;
|
||||
};
|
||||
let target = world_rect(xf, bounds);
|
||||
let available = xf.rect.shrink(8.0);
|
||||
let visible = target.intersect(available);
|
||||
if visible.is_positive() && available.height() >= 26.0 {
|
||||
let width = (ui.painter().layout_no_wrap(display.feedback.label.clone(), FontId::proportional(12.0), Color32::WHITE)
|
||||
.size().x + 36.0).min(available.width());
|
||||
let above = visible.top() - 32.0;
|
||||
let label_top = if above >= available.top() { above } else {
|
||||
(visible.top() + 8.0).min(available.bottom() - 26.0)
|
||||
};
|
||||
let rect = Rect::from_min_size(
|
||||
pos2((visible.left() + 8.0).min(available.right() - width), label_top),
|
||||
vec2(width, 26.0),
|
||||
);
|
||||
ui.scope(|ui| {
|
||||
ui.set_clip_rect(ui.clip_rect().intersect(xf.rect));
|
||||
let id = ui.scope_id().with(("agent-canvas-feedback", doc));
|
||||
if display.feedback.image_replacement {
|
||||
super::agent_motion::replacement_sweep(ui, target, display.arrived, self.reduce_motion);
|
||||
} else {
|
||||
super::agent_motion::target_beacon(ui, id, target, display.arrived, self.reduce_motion);
|
||||
if display.feedback.edit {
|
||||
super::agent_motion::paint_real_target(ui, target, xf.rect, self.reduce_motion, false);
|
||||
}
|
||||
}
|
||||
kit::paint_badge(ui, id.with("label"), rect, kit::BadgeKind::Adopted, &display.feedback.label, self.reduce_motion);
|
||||
});
|
||||
state.geometry.insert("agentFeedback".into(), [rect.min.x, rect.min.y, rect.width(), rect.height()]);
|
||||
}
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64((FEEDBACK_DISPLAY - (now - display.arrived)).max(0.0)));
|
||||
None
|
||||
}
|
||||
|
||||
|
||||
pub(crate) fn workspace_toolbar(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
self.enforce_canvas_scope(app);
|
||||
for name in ["professionalEnter", "professionalApply", "professionalReturn"] {
|
||||
self.canvas_workspace.geometry.remove(name);
|
||||
}
|
||||
self.canvas_workspace.professional_controls.clear();
|
||||
super::stitch_ui::scope(ui, |ui| {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min).with_main_wrap(true), |ui| {
|
||||
let canvas_first = self.template_workflow["canvasFirst"] == true;
|
||||
// Allocate the complete right-hand action before the left
|
||||
// controls can consume its space at larger application scales.
|
||||
if app.session.active().is_some() {
|
||||
let editing = self.professional_child_active(app);
|
||||
let layer = self.professional_entry_layer(app);
|
||||
let label = if editing { "回填详情页" } else { "专业编辑" };
|
||||
let hint = if editing { "将独立画布的编辑回填到原图位,可撤销" } else { "在独立原生画布中编辑所选图片" };
|
||||
let professional = super::stitch_ui::action_button(ui, label, super::stitch_ui::ButtonRole::Secondary, editing || layer.is_some()).on_hover_text(hint);
|
||||
self.record_professional_control(if editing { "professionalApply" } else { "professionalEnter" }, &professional);
|
||||
if professional.clicked() {
|
||||
let result = if editing {
|
||||
self.leave_professional(app)
|
||||
} else {
|
||||
self.enter_professional(app, layer)
|
||||
};
|
||||
if let Err(error) = result {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
if editing {
|
||||
let back = super::stitch_ui::action_button(ui, "返回详情页", super::stitch_ui::ButtonRole::Secondary, true).on_hover_text("保留独立编辑稿,暂不回填");
|
||||
self.record_professional_control("professionalReturn", &back);
|
||||
if back.clicked()
|
||||
&& let Err(error) = self.professional_back(app) { self.error = error; }
|
||||
return;
|
||||
}
|
||||
}
|
||||
if canvas_first
|
||||
&& !self.professional_mode
|
||||
&& super::stitch_ui::action_button(ui, "适配", super::stitch_ui::ButtonRole::Secondary, true)
|
||||
.on_hover_text("适配当前页")
|
||||
.clicked()
|
||||
{
|
||||
self.canvas_workspace.fit_current_screen = true;
|
||||
}
|
||||
let room = ui.available_size_before_wrap().x;
|
||||
let left_width = if room < 290.0 { ui.max_rect().width() } else { room };
|
||||
ui.allocate_ui_with_layout(vec2(left_width, 40.0), egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), |ui| {
|
||||
if super::stitch_ui::action_button(ui, "产品资料", super::stitch_ui::ButtonRole::Secondary, true).clicked() {
|
||||
self.creation_open = true;
|
||||
self.creation_step = 0;
|
||||
}
|
||||
self.copywriting_menu(app, ui);
|
||||
if !canvas_first {
|
||||
return;
|
||||
}
|
||||
let (active_output, active_variant) = self.toolbar_output_and_variant(app);
|
||||
let installed_colors = self.template_workflow["variants"].as_array().or_else(|| self.creation_brief["variants"].as_array());
|
||||
let variants: Vec<_> = installed_colors.into_iter().flatten()
|
||||
.filter(|row| self.template_workflow["outputVariantIds"][&active_output].as_array()
|
||||
.filter(|ids| !ids.is_empty())
|
||||
.is_none_or(|ids| ids.contains(&row["id"]))).cloned().collect();
|
||||
let current_color_visible = variants.iter().any(|row| row["id"] == active_variant);
|
||||
// Wrap the output group and colour group as meaningful
|
||||
// units, retaining the single row on wide workspaces.
|
||||
let outputs = [("detail", "详情"), ("main_images", "主图"), ("sku_images", "SKU")];
|
||||
let selected = outputs.iter().position(|(id, _)| *id == active_output).unwrap_or(0);
|
||||
let map_template = self.template_workflow["templateVersion"].as_str().is_some_and(|version| version.starts_with("map-"));
|
||||
let [detail, main, sku] = outputs.map(|(id, label)| (label, !map_template
|
||||
|| self.template_workflow["outputs"].as_array().into_iter().flatten().any(|output| output["outputId"] == id)
|
||||
|| self.template_workflow["productTemplateOutputs"].as_array().into_iter().flatten().any(|output| output == id)));
|
||||
let choices = [detail, main, sku, ("主图视频", false), ("买家秀", false)];
|
||||
let output_width = choices.iter().map(|(label, _)| super::stitch_ui::segment_width(ui, label)).sum::<f32>()
|
||||
+ super::stitch_ui::SEGMENT_GAP * (choices.len() - 1) as f32 + 6.0 + ui.spacing().item_spacing.x + 1.0;
|
||||
ui.allocate_ui_with_layout(vec2(output_width.min(left_width.max(1.0)), 40.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
super::stitch_ui::vertical_divider(ui);
|
||||
let segmented = super::stitch_ui::segmented_control(ui, egui::Id::unique("canvas-output"), &choices, selected, self.reduce_motion);
|
||||
segmented.responses[3].clone().on_disabled_hover_text("主图视频 · 开发中,即将支持");
|
||||
segmented.responses[4].clone().on_disabled_hover_text("买家秀(种草视频)· 开发中,即将支持");
|
||||
if let Some((id, _)) = segmented.selected.and_then(|index| outputs.get(index)).copied() {
|
||||
if self.canvas_workspace.output != id || self.canvas_workspace.scope_blocked
|
||||
|| !current_color_visible || self.product_view_pending() {
|
||||
let request = json!({"outputId":id});
|
||||
if let Err(error) = self.slot_action(app, "slot-skeleton", request) {
|
||||
self.product_views.view_error = Some(error.clone());
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if variants.len() > 1 || (!variants.is_empty() && !current_color_visible) {
|
||||
let colour_width = 140.0_f32.min((left_width - ui.spacing().item_spacing.x - 1.0).max(0.0));
|
||||
ui.allocate_ui_with_layout(
|
||||
vec2(colour_width + ui.spacing().item_spacing.x + 1.0, 40.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
super::stitch_ui::vertical_divider(ui);
|
||||
let selected =
|
||||
variants.iter().find(|v| v["id"] == active_variant).and_then(|v| v["name"].as_str()).unwrap_or("花色");
|
||||
super::stitch_ui::halo_select(ui, "canvas-product-variant", colour_width, selected, self.reduce_motion, |ui| {
|
||||
for v in &variants {
|
||||
if super::stitch_ui::menu_item(ui, v["name"].as_str().unwrap_or("花色"), true).clicked()
|
||||
&& let Err(e) = self.slot_action(
|
||||
app,
|
||||
"slot-skeleton",
|
||||
json!({"outputId":active_output.as_str(),"variantId":v["id"]}),
|
||||
)
|
||||
{
|
||||
self.error = e;
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn locate_scope_for(&self, app: &PhotocraftApp, doc_id: u64, output: &str, variant: &str) -> Value {
|
||||
json!({"account":self.account["id"], "origin":self.origin, "project":bound_project(self, doc_id), "doc":doc_id,
|
||||
"revision":app.session.active().map(|state|state.revision), "output":output, "variant":variant})
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn begin_locate(&mut self, app: &PhotocraftApp, xf: ViewXform, doc_id: u64, output: &str, variant: &str,
|
||||
request: Value, target: [f32; 4], now: f64) -> Option<CameraRequest> {
|
||||
self.canvas_workspace.context = Some(request.clone());
|
||||
self.canvas_workspace.locate_scope = Some(self.locate_scope_for(app, doc_id, output, variant));
|
||||
self.canvas_workspace.initial_focus = false;
|
||||
if !xf.rect.shrink(48.0).contains_rect(world_rect(xf, target)) {
|
||||
let current = xf.to_doc(xf.rect.center());
|
||||
let to = [target[0] + target[2] / 2.0, target[1] + target[3] / 2.0];
|
||||
let from = [current[0] as f32, current[1] as f32];
|
||||
let distance = ((to[0] - from[0]).powi(2) + (to[1] - from[1]).powi(2)).sqrt();
|
||||
let duration = (distance / 3000.0).clamp(0.20, 0.45) as f64;
|
||||
if distance < 0.01 { self.canvas_workspace.locate_highlight = Some((request, now)); }
|
||||
else if self.reduce_motion {
|
||||
self.canvas_workspace.locate_highlight = Some((request, now));
|
||||
return Some(CameraRequest { center:to, zoom:None });
|
||||
} else {
|
||||
self.canvas_workspace.locate_highlight = Some((request, now + duration));
|
||||
self.canvas_workspace.locate_motion = Some(LocateMotion { from, to, started:now, duration, smooth:false });
|
||||
}
|
||||
} else { self.canvas_workspace.locate_highlight = Some((request, now)); }
|
||||
None
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn advance_locate(&mut self, app: &PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc_id: u64, output: &str, variant: &str,
|
||||
rows: &[Row<'_>], width: f32, mut camera: Option<CameraRequest>, now: f64) -> Option<CameraRequest> {
|
||||
let current_scope = self.locate_scope_for(app, doc_id, output, variant);
|
||||
if self.canvas_workspace.locate_scope.as_ref().is_some_and(|scope| *scope != current_scope) {
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
self.canvas_workspace.locate_highlight = None;
|
||||
self.canvas_workspace.locate_scope = None;
|
||||
camera = None;
|
||||
}
|
||||
if ui.input(|input| {
|
||||
input.raw.events.iter().any(|event| matches!(event, egui::Event::MouseWheel { .. }))
|
||||
|| (input.pointer.any_down() && input.pointer.delta() != Vec2::ZERO)
|
||||
}) {
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
self.canvas_workspace.locate_highlight = None;
|
||||
self.canvas_workspace.locate_scope = None;
|
||||
camera = None;
|
||||
}
|
||||
if let Some(motion) = self.canvas_workspace.locate_motion {
|
||||
let progress = if self.reduce_motion { 1.0 } else { motion.progress(now) };
|
||||
camera = Some(motion.camera(progress));
|
||||
if progress >= 1.0 {
|
||||
self.canvas_workspace.locate_motion = None;
|
||||
} else {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
if let Some((target, started)) = self.canvas_workspace.locate_highlight.as_ref() {
|
||||
if now >= *started && now - started < 0.9 {
|
||||
if let Some(bounds) = app.session.active().and_then(|state| location(&state.doc, rows, target, width, &self.agent_images)) {
|
||||
ui.scope(|ui| {
|
||||
ui.set_clip_rect(ui.clip_rect().intersect(xf.rect));
|
||||
let beacon_id = ui.scope_id().with("locate-beacon");
|
||||
super::agent_motion::target_beacon(ui, beacon_id, world_rect(xf, bounds), *started, self.reduce_motion);
|
||||
});
|
||||
}
|
||||
} else if now - started >= 0.9 {
|
||||
self.canvas_workspace.locate_highlight = None;
|
||||
}
|
||||
}
|
||||
camera
|
||||
}
|
||||
|
||||
pub(crate) fn plain_workspace_camera(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, xf: ViewXform, doc_id: u64, width: f32) -> Option<CameraRequest> {
|
||||
let output = self.canvas_workspace.output.clone();
|
||||
let variant = self.canvas_workspace.variant.clone();
|
||||
let now = ui.input(|input| input.time);
|
||||
let mut camera = None;
|
||||
if let Some(request) = self.canvas_workspace.locate_request.take() {
|
||||
let queued = self.canvas_workspace.locate_queued_scope.take();
|
||||
let scope = self.locate_scope_for(app, doc_id, &output, &variant);
|
||||
let valid_scope = queued.as_ref().is_some_and(|q| {
|
||||
q["account"].as_str().is_some_and(|id| !id.is_empty()) && q["origin"].as_str().is_some_and(|origin| !origin.is_empty())
|
||||
&& q["project"].is_string() && q["account"] == scope["account"] && q["origin"] == scope["origin"]
|
||||
&& q["project"] == scope["project"] && q["doc"] == scope["doc"] && q["revision"] == scope["revision"]
|
||||
});
|
||||
if valid_scope && let Some(bounds) = app.session.active().and_then(|state| {
|
||||
plain_native_reference_valid(&state.doc, &request).then(|| location(&state.doc, &[], &request, width, &self.agent_images)).flatten()
|
||||
}) {
|
||||
camera = self.begin_locate(app, xf, doc_id, &output, &variant, request, bounds, now);
|
||||
}
|
||||
}
|
||||
camera = self.advance_locate(app, ui, xf, doc_id, &output, &variant, &[], width, camera, now);
|
||||
camera
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user