From 5a8ebae4644bd26244b3872623c8d10aa76d6f4e Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Tue, 1 Dec 2026 15:26:08 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=95=B4=E5=B0=8F=E5=A3=B9=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E6=9D=A1=E7=A0=81=E8=A1=A8=E5=8D=95=E4=B8=8E=E5=8F=82?= =?UTF-8?q?=E8=80=83=E5=9B=BE=E9=A2=84=E8=A7=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../crates/ui-egui/src/jiansun.rs | 30 +- .../crates/ui-egui/src/jiansun/agent_panel.rs | 8 +- .../crates/ui-egui/src/jiansun/creation.rs | 866 +++++++++++++----- .../ui-egui/src/jiansun/creation_reads.rs | 161 +++- .../crates/ui-egui/src/jiansun/stitch_ui.rs | 3 +- 5 files changed, 826 insertions(+), 242 deletions(-) diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 4ae5c1b6..be0bf7bf 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1004,14 +1004,10 @@ pub struct Workspace { image_catalog_error: String, account_error: String, api_key: String, - knowledge_key: String, xiaoyi_key: String, xiaoyi_key_saved: bool, xiaoyi_knowledge_mode: String, xiaoyi_key_check: Option>, - knowledge_origin: String, - knowledge_key_saved: bool, - knowledge_key_check: Option>, config: bool, composer: String, composer_attachments: composer_attachments::State, @@ -1554,14 +1550,10 @@ impl Workspace { image_catalog_error: String::new(), account_error: String::new(), api_key: String::new(), - knowledge_key: String::new(), xiaoyi_key: String::new(), xiaoyi_key_saved: false, xiaoyi_knowledge_mode: "unavailable".into(), xiaoyi_key_check: None, - knowledge_origin: String::new(), - knowledge_key_saved: false, - knowledge_key_check: None, config: false, composer: String::new(), composer_attachments: composer_attachments::State::default(), @@ -2752,14 +2744,6 @@ impl Workspace { self.projects = v["projects"].as_array().cloned().unwrap_or_default(); self.project_refresh = Instant::now(); self.project_refresh_requested = false; - if let Some(origin) = v["knowledgeOrigin"].as_str() - && self.knowledge_origin != origin - { - self.knowledge_origin = origin.to_owned(); - self.knowledge_key_check = None; - self.xiaoyi_key_check = None; - } - self.knowledge_key_saved = v["knowledgeKeySaved"] == true; self.xiaoyi_key_saved = v["xiaoyiKeySaved"] == true; if let Some(mode @ ("automatic" | "manual" | "unavailable")) = v["xiaoyiKnowledgeMode"].as_str() { self.xiaoyi_knowledge_mode = mode.to_owned(); @@ -3219,8 +3203,9 @@ impl Workspace { if method == "creation-read" { self.creation_read_failed = true; } - if method == "configure-knowledge" { - self.knowledge_key_check = Some(Err(e)); + if matches!(method, "creation-import" | "creation-import-data") { + self.creation_reads.reference_import_error = e; + self.creation_reads.reference_import_paths = None; } else if method == "configure-xiaoyi-knowledge" { self.xiaoyi_key_check = Some(Err(e)); } else if method == "project-delete" { @@ -3326,15 +3311,6 @@ impl Workspace { self.xiaoyi_key_saved |= v["saved"] == true; self.xiaoyi_key_check = Some(v["error"].as_str().map_or(Ok(()), |error| Err(error.to_owned()))); } - "configure-knowledge" => { - let origin = v["origin"].as_str().unwrap_or_default(); - if v["originChanged"] == true { - self.xiaoyi_key_check = None; - } - self.knowledge_origin = origin.to_owned(); - self.knowledge_key_saved = true; - self.knowledge_key_check = Some(Ok(())); - } "configure" => { self.connection_received(&v); self.api_key.clear(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs index bf0693e6..db89cc9c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_panel.rs @@ -3630,7 +3630,8 @@ impl Workspace { (true, _, _) => ("正在连接", StatusTone::Neutral), (false, Some(Err(_)), _) => ("连接失败", StatusTone::Error), (false, _, "automatic") => ("素材库自动连接", StatusTone::Neutral), - _ => ("等待连接", StatusTone::Neutral), + _ if self.account.is_null() => ("登录后自动连接", StatusTone::Neutral), + _ => ("未连接", StatusTone::Neutral), }; status_label(ui, status, tone); if let Some(Err(error)) = self.xiaoyi_key_check.as_ref().filter(|_| !checking) { @@ -3664,7 +3665,6 @@ impl Workspace { // mounted through the exit. Secrets never stay in the retained shell. if !open { self.api_key.clear(); - self.knowledge_key.clear(); self.xiaoyi_key.clear(); } if !visual.render { @@ -3721,8 +3721,6 @@ impl Workspace { } }); } - ui.add_space(2.0); - ui.label(RichText::new("连接信息保存在本机,可随时更换。").size(12.0).color(t.text_dim)); ui.add_space(4.0); ui.horizontal(|ui| { icon(ui, "lock", t.text_dim); @@ -7187,7 +7185,7 @@ mod tests { let mut text = Vec::new(); for shape in &output.unwrap().shapes { labels(&shape.shape, &mut text); } assert!(text.iter().any(|text| text == "小壹设置")); - assert!(text.iter().any(|text| text == "连接信息保存在本机,可随时更换。")); + assert!(!text.iter().any(|text| text == "连接信息保存在本机,可随时更换。")); assert!(text.iter().any(|text| text == "输入个人 Key")); assert!(!text.iter().any(|text| text == CONTEXT_UNAVAILABLE), "missing usage does not add a permanent warning to settings"); assert!(text.iter().all(|text| !text.to_lowercase().contains("98k"))); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index 915d4598..e6ef39b5 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -132,7 +132,7 @@ impl PhotocraftApp { if drop_contains(&w.creation_view_geometry["product-form-viewport"], at) && files.iter().any(|file| reference_image_path(file.path())) { - if let Some(w) = self.jiansun.as_mut() { w.error = "请将图片拖到「产品参考图」区域".into(); } + if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = "请将图片拖到「产品参考图」区域".into(); } return true; } return false; @@ -147,7 +147,7 @@ impl PhotocraftApp { None }; if let Some(error) = reject { - if let Some(w) = self.jiansun.as_mut() { w.error = error.into(); } + if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = error.into(); } return true; } let paths = files.iter().map(|file| { @@ -156,16 +156,28 @@ impl PhotocraftApp { valid.then(|| path.to_str().map(str::to_owned)).flatten() }).collect::>>(); let Some(paths) = paths else { - if let Some(w) = self.jiansun.as_mut() { w.error = "请选择 PNG、JPG 或 WebP 格式的本机图片".into(); } + if let Some(w) = self.jiansun.as_mut() { w.creation_reads.reference_import_error = "请选择 PNG、JPG 或 WebP 格式的本机图片".into(); } return true; }; - if let Err(error) = super::action(self, "creation-import", json!({"doc":doc,"paths":paths})) + if let Err(error) = self.import_reference_paths(paths) && let Some(w) = self.jiansun.as_mut() { - w.error = error; + w.creation_reads.reference_import_error = error; } true } + fn import_reference_paths(&mut self, paths: Vec) -> Result { + let native = self.session.authorize.is_none(); + let result = super::action(self, "creation-import", json!({"paths": paths}))?; + if let Some(w) = self.jiansun.as_mut() { + w.creation_reads.reference_import_error.clear(); + if native && result["submitted"] == true { + w.creation_reads.reference_import_paths = Some(paths); + } + } + Ok(result) + } + } pub(crate) fn creation_escape_active(app: &PhotocraftApp) -> bool { @@ -399,6 +411,9 @@ fn canvas_entry_missing(brief: &Value, template: &Value) -> Vec<&'static str> { (template_identity(template), "模板"), (filled("name"), "产品名称"), (image_rows(brief).iter().any(|(image, _)| image["purpose"] == "product"), "产品图"), + (project_barcodes(brief).next().is_none() || filled(spu_field(brief)), "SPU 型号"), + (project_barcodes(brief).nth(1).is_none() || + brief["detailBarcode"].as_str().is_some_and(|selected| project_barcodes(brief).any(|code| code == selected)), "详情页出图条码"), ] .into_iter() .filter_map(|(present, label)| (!present).then_some(label)) @@ -430,23 +445,35 @@ fn edit_hint(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mu } fn edit_named(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut Value, width: f32, multiline: bool, hint: &str, name: &str) -> bool { - let mut text = value.as_str().unwrap_or("").to_owned(); - // Halo Field consumes 10pt inner margin plus its 1pt stroke on each side. - let content_width = (width - 22.0).max(0.0); - let id = egui::Id::unique("creation-field").with(id); - ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(id.with("editor"))); - let mut field = stitch_ui::text_input(&mut text, hint, multiline).desired_width(content_width).id(id.with("editor")); + let mut text = match value { + Value::String(text) => text.clone(), + Value::Number(number) => number.to_string(), + _ => String::new(), + }; + let mut field = stitch_ui::text_input(&mut text, hint, multiline); if multiline { field = field.desired_rows(3); } - let reduced = ui.style().animation_time == 0.0; - let changed = stitch_ui::halo_field(ui, id, None, reduced, |ui| ui.add(field.frame(egui::Frame::NONE)).accessible_name(name)).changed(); - if changed { - *value = json!(text); - } + let changed = form_editor(ui, id, field, width, name).changed(); + if changed { *value = json!(text); } changed } +fn form_editor(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, field: egui::TextEdit<'_>, width: f32, name: &str) -> egui::Response { + // Halo Field consumes 10pt inner margin plus its 1pt stroke on each side. + let content_width = (width - 22.0).max(0.0); + let editor = creation_editor_id(ui, id); + let field = field.desired_width(content_width).id(editor).frame(egui::Frame::NONE); + let reduced = ui.style().animation_time == 0.0; + stitch_ui::halo_field(ui, editor.with("halo"), None, reduced, |ui| ui.add(field).accessible_name(name)) +} + +fn creation_editor_id(ui: &Ui, id: impl std::hash::Hash + std::fmt::Debug) -> egui::Id { + let editor = egui::Id::unique("creation-field").with(id).with("editor"); + ui.data_mut(|data| data.get_temp_mut_or_default::>(egui::Id::unique("creation-active-editors")).push(editor)); + editor +} + fn field_group(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { ui.vertical(|ui| { ui.set_width(width); @@ -456,50 +483,187 @@ fn field_group(ui: &mut Ui, width: f32, label: &str, contents: impl FnOnce(&m }) } +fn intake_columns(width: f32) -> usize { + if width >= 420.0 { 3 } else if width >= 152.0 { 2 } else { 1 } +} + fn intake_fields(ui: &mut Ui, scope: egui::Id, width: f32, schema: &Value, values: &mut Value, reduced: bool) -> bool { + let Some(fields) = schema.as_array() else { return false }; + let columns = intake_columns(width); + let column_width = (width - 8.0 * (columns - 1) as f32) / columns as f32; + let compact = |field: &Value| matches!(field["type"].as_str(), Some("number" | "select" | "boolean")); let mut changed = false; - for field in schema.as_array().into_iter().flatten() { - let Some(id) = field["id"].as_str() else { continue }; - let Some(name) = field["label"].as_str() else { continue }; - let label = format!("{}{}{}", name, - field["unit"].as_str().map(|unit| format!("({unit})")).unwrap_or_default(), - if field["required"] == true { " *" } else { "" }); - field_group(ui, width, &label, |ui| { - match field["type"].as_str() { - Some("text" | "number") => { - let hint = if field["type"] == "number" { "输入数字" } else { "输入内容" }; - changed |= edit_named(ui, scope.with(id), &mut values[id], width, false, hint, &label); + let mut remaining = fields.as_slice(); + while let Some((first, rest)) = remaining.split_first() { + if !compact(first) { + changed |= intake_field(ui, scope, width, 0.0, first, values, reduced); + remaining = rest; + } else { + let count = remaining.iter().take(columns).take_while(|field| compact(field)).count(); + let (row, rest) = remaining.split_at(count); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + let label_height = row.iter().map(|field| ui.painter().layout( + intake_label(field), crate::theme::agent_scale::Type::Title.font_id(), egui::Color32::WHITE, column_width, + ).size().y).fold(0.0_f32, f32::max); + for field in row { + changed |= intake_field(ui, scope, column_width, label_height, field, values, reduced); } - Some("select") => { - let selected = values[id].as_str().unwrap_or("请选择").to_owned(); - let response = stitch_ui::halo_select(ui, scope.with(id), width, &selected, reduced, |ui| { - for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { - if stitch_ui::select_option(ui, option, values[id] == option, true).clicked() { - values[id] = json!(option); - changed = true; - ui.close(); - } - } - }); - response.response.on_hover_text(&label); - } - Some("boolean") => { - let mut value = values[id].as_bool().unwrap_or(false); - if ui.checkbox(&mut value, name).changed() { - values[id] = json!(value); - changed = true; - } - } - _ => {} - } - if let Some(help) = field["help"].as_str().filter(|help| !help.is_empty()) { - ui.weak(help); - } - }); + }); + remaining = rest; + } } changed } +fn intake_label(field: &Value) -> String { + let name = field["label"].as_str().or(field["id"].as_str()).unwrap_or("未命名字段"); + format!("{}{}{}", name, + field["unit"].as_str().map(|unit| format!(" ({unit})")).unwrap_or_default(), + if field["required"] == true { " *" } else { "" }) +} + +fn intake_field(ui: &mut Ui, scope: egui::Id, width: f32, label_height: f32, field: &Value, values: &mut Value, reduced: bool) -> bool { + let label = intake_label(field); + let Some(id) = field["id"].as_str().filter(|id| !id.trim().is_empty()) else { + stitch_ui::status_label(ui, &format!("{label}缺少字段编号"), stitch_ui::StatusTone::Warning); + return false; + }; + let mut changed = false; + ui.vertical(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing.y = 6.0; + let text_dim = Tokens::get(ui.ctx()).agent().text_dim; + ui.allocate_ui(vec2(width, label_height), |ui| { + ui.set_min_height(label_height); + ui.add(egui::Label::new(egui::RichText::new(&label).size(crate::theme::agent_scale::Type::Title.size()).color(text_dim)).wrap()); + }); + match field["type"].as_str() { + Some("text" | "number") => { + let hint = if field["type"] == "number" { "输入数字" } else { "输入内容" }; + changed |= edit_named(ui, scope.with(id), &mut values[id], width, false, hint, &label); + } + Some("select") => { + let selected = values[id].as_str().unwrap_or("请选择").to_owned(); + let response = stitch_ui::halo_select(ui, scope.with(id), width, &selected, reduced, |ui| { + for option in field["options"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if stitch_ui::select_option_sized(ui, option, values[id] == option, true, vec2(ui.available_width(), 28.0)).clicked() { + values[id] = json!(option); + changed = true; + ui.close(); + } + } + }); + response.response.on_hover_text(&label); + } + Some("boolean") => { + let value = values[id] == true; + if stitch_ui::toggle_option_sized(ui, "是", value, true, vec2(width, 28.0)).accessible_name(&label).clicked() { + values[id] = json!(!value); + changed = true; + } + } + _ => { + let kind = field["type"].as_str().unwrap_or("未指定"); + stitch_ui::status_label(ui, &format!("暂不支持此字段类型({kind})"), stitch_ui::StatusTone::Warning); + } + } + if let Some(help) = field["help"].as_str().filter(|help| !help.is_empty()) { + ui.weak(help); + } + }); + changed +} + +fn spu_field(brief: &Value) -> &'static str { + if brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" } +} + +fn set_intake(brief: &mut Value, template_id: &Value, schema: &Value) { + if schema["version"] != 1 { + if let Some(fields) = brief.as_object_mut() { + fields.remove("intake"); + } + } else if brief["intake"]["templateId"] != *template_id { + brief["intake"] = json!({"templateId":template_id,"schema":schema,"productValues":{},"barcodeValues":{}}); + } +} + +const BARCODE_HINT: &str = "如 DNZ030516N717V01"; +const BARCODE_SEPARATORS: [char; 7] = ['\r', '\n', ',', ',', '、', ';', ';']; + +fn barcode_editor(ui: &mut Ui, id: egui::Id, value: &mut String, width: f32, name: &str) -> egui::Response { + let id = creation_editor_id(ui, id); + use crate::theme::agent_scale::Type; + let font_size = if width >= 128.0 { Type::Meta } else { Type::Caption }.size(); + // A one-row multiline editor preserves embedded line breaks in pasted barcodes. + ui.add(stitch_ui::text_input(value, BARCODE_HINT, true) + .desired_rows(1).lock_focus(false).return_key(None) + .id(id).font(egui::FontId::monospace(font_size)).margin(egui::Margin::symmetric(2, 6)) + .desired_width((width - 4.0).max(1.0))).accessible_name(name) +} + +fn binding_barcodes(binding: &Value) -> impl Iterator { + let legacy = binding.as_str().into_iter().flat_map(|text| text.split(BARCODE_SEPARATORS)); + let current = binding.as_array().into_iter().flatten().filter_map(Value::as_str); + let mut seen = std::collections::HashSet::new(); + legacy.chain(current).map(str::trim) + .filter(move |barcode| !barcode.is_empty() && seen.insert(*barcode)) +} + +fn project_barcodes(brief: &Value) -> impl Iterator { + brief["barcodeBindings"].as_object().into_iter().flat_map(|groups| groups.values()).flat_map(binding_barcodes) +} + +fn barcode_issue(brief: &Value, text: &str) -> Option<&'static str> { + let text = text.trim(); + if text.is_empty() { + Some("请输入产品条码") + } else if project_barcodes(brief).any(|barcode| barcode == text) { + Some("此条码已录入当前项目") + } else { + None + } +} + +fn update_detail_barcode(brief: &mut Value) -> bool { + let selected = brief["detailBarcode"].as_str(); + let next = { + let mut codes = project_barcodes(brief); + let first = codes.next(); + let next = if codes.next().is_none() { + first + } else { + selected.filter(|selected| project_barcodes(brief).any(|code| code == *selected)) + }; + if selected == next { return false; } + next.map(str::to_owned) + }; + if let Some(next) = next { + brief["detailBarcode"] = json!(next); + } else if let Some(fields) = brief.as_object_mut() { + fields.remove("detailBarcode"); + } + true +} + +fn replace_barcode(brief: &mut Value, old: &str, replacement: Option<&str>) { + if brief["detailBarcode"] == old { + if let Some(code) = replacement { + brief["detailBarcode"] = json!(code); + } else if let Some(fields) = brief.as_object_mut() { + fields.remove("detailBarcode"); + } + } + if let Some(values) = brief.get_mut("intake").and_then(|intake| intake.get_mut("barcodeValues")) + .and_then(Value::as_object_mut) + && let Some(value) = values.remove(old) + && let Some(code) = replacement + { + values.insert(code.to_owned(), value); + } +} + fn help_icon(ui: &mut Ui, text: &str) -> egui::Response { let (rect, response) = ui.allocate_exact_size(vec2(20.0, 20.0), egui::Sense::click()); let color = Tokens::get(ui.ctx()).agent().text_dim; @@ -608,6 +772,9 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val return; } if let Some(images) = value["images"].as_array() { + if method == "creation-import" { + w.match_imported_reference_paths(app, images); + } let mut current = w.creation_brief["images"].as_array().cloned().unwrap_or_default(); let references = image_rows(&w.creation_brief); for image in images { @@ -1074,6 +1241,9 @@ impl Workspace { } input["doc"] = json!(st.doc.id.0); input["baseRevision"] = json!(st.revision); + if method == "creation-import" { + self.creation_read_scope(app); + } if method == "creation-import" && app.session.authorize.is_some() { use base64::Engine as _; let paths = input["paths"].as_array().filter(|a| !a.is_empty() && a.len() <= 8).ok_or("每次最多8张图片")?; @@ -1115,6 +1285,9 @@ impl Workspace { if method == "creation-save" && input.get("deliveryDir").is_none() { input["deliveryDir"] = json!(self.creation_delivery_dir); } + if matches!(method, "creation-save" | "creation-facts") { + update_detail_barcode(&mut input["brief"]); + } input["model"] = json!(self.model); input["imageModel"] = json!(self.image_model); if matches!(method, "creation-generate" | "creation-load") { @@ -1288,7 +1461,7 @@ impl Workspace { }); }); } - fn brief_fields_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + fn brief_fields_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { let t = Tokens::get(ui.ctx()).agent(); let panel_width = ui.available_width(); let frame = stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Task) @@ -1304,11 +1477,11 @@ impl Workspace { help_icon(ui, "选择品牌、品类和模板,再填写产品资料与参考图,进入画布。"); }); ui.add_space(16.0); - self.brief_content_ui(app, ui); - }); + self.brief_content_ui(app, ui) + }).inner } - fn brief_content_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { + fn brief_content_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) -> bool { let field_scope = self.creation_field_scope(app); let width = ui.available_width(); section_heading(ui, "品牌与模板", "选定匹配模板后沿用原稿与图位。没有匹配模板时,小壹按产品资料自主策划。"); @@ -1349,11 +1522,13 @@ impl Workspace { self.product_select_results(app, ui); } ui.add_space(10.0); + let dynamic = self.creation_brief["intake"]["schema"]["version"] == 1; let columns = brief_columns(width).min(2); let field_width = ((width - 14.0 * (columns - 1) as f32) / columns as f32).max(130.0); let labels = ["产品名称 *", "产品尺寸(长 × 宽 × 高)", "SPU 型号", "画幅导出规格"]; egui::Grid::new("creation-brief").num_columns(columns).spacing(vec2(14.0, 12.0)).show(ui, |ui| { - for (index, label) in labels.iter().enumerate() { + for (position, (index, label)) in labels.iter().enumerate() + .filter(|(index, _)| !dynamic || matches!(index, 0 | 2)).enumerate() { field_group(ui, field_width, label, |ui| match index { 0 => { let name = ui.scope(|ui| edit(ui, (field_scope, "name"), &mut self.creation_brief["name"], field_width, false, "产品名称")); @@ -1395,8 +1570,7 @@ impl Workspace { self.control_geometry("dimensions", dimensions.response.rect); } 2 => { - let is_spu = self.creation_brief["identifierType"] == "spu"; - let field = if is_spu { "identifier" } else { "deliverySpu" }; + let field = spu_field(&self.creation_brief); let mut spu = self.creation_brief[field].clone(); let identifier = ui.scope(|ui| { edit_named(ui, (field_scope, "identifier"), &mut spu, field_width, false, "输入 SPU 型号", "SPU 型号") @@ -1405,7 +1579,7 @@ impl Workspace { self.creation_brief[field] = spu; self.creation_dirty = true; } - if !is_spu { + if field == "deliverySpu" { if let Some(legacy) = self.creation_brief["identifier"].as_str().filter(|value| !value.is_empty()) { ui.weak(format!("原项目编号 {legacy}")); } @@ -1427,14 +1601,15 @@ impl Workspace { } _ => {} }); - if (index + 1) % columns == 0 { + if (position + 1) % columns == 0 { ui.end_row(); } } }); ui.add_space(8.0); let product_fields = self.creation_brief["intake"]["schema"]["productFields"].clone(); - if product_fields.is_array() { + if product_fields.as_array().is_some_and(|fields| !fields.is_empty()) { + section_heading(ui, "共用属性", ""); let mut values = self.creation_brief["intake"]["productValues"].clone(); if !values.is_object() { values = json!({}); } if intake_fields(ui, field_scope.with("intake-product"), width, &product_fields, &mut values, self.reduce_motion) { @@ -1443,105 +1618,29 @@ impl Workspace { } } brief_section_break(ui); - if width >= 600.0 { - ui.horizontal_top(|ui| { - // The trigger and popup share a width in `picker`: keep room - // for the material search field, thumbnails and long names. - let material_width = (width - 240.0).min(420.0); - let heading_width = (width - material_width - 20.0).max(100.0); - let heading = ui.vertical(|ui| { - ui.set_width(heading_width); - section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。"); - }); - self.control_geometry("material-heading", heading.response.rect); - self.material_select(app, ui, material_width); - }); - } else { - section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。"); - ui.add_space(6.0); - self.material_select(app, ui, width.min(420.0)); - } - ui.add_space(12.0); - self.sku_colors(ui, width, field_scope); - let mut variants = brief_variants(&self.creation_brief); - if variants.is_empty() { - variants.push(json!({"id":"default","name":"当前花色"})); - } - let barcode_fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); - for variant in variants { - let Some(id) = variant["id"].as_str() else { continue }; - let name = variant["name"].as_str().filter(|name| !name.is_empty()).unwrap_or("当前花色"); - let label = if id == "default" { "条码".to_owned() } else { format!("{name} · 条码") }; - let binding = self.creation_brief["barcodeBindings"][id].as_str().unwrap_or_default(); - let mut barcodes: Vec = binding.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、')) - .filter(|code| !code.is_empty()).map(str::to_owned).collect(); - let spu_field = if self.creation_brief["identifierType"] == "spu" { "identifier" } else { "deliverySpu" }; - let has_spu = self.creation_brief[spu_field].as_str().is_some_and(|value| !value.trim().is_empty()); - let draft_id = field_scope.with(("barcode-draft", id)); - let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or(Value::Null); - let mut changed = false; - field_group(ui, width, &label, |ui| { - ui.add_enabled_ui(has_spu, |ui| { - let mut remove = None; - for (index, barcode) in barcodes.iter().enumerate() { - ui.horizontal(|ui| { - let text_width = (width - 44.0).max(40.0); - ui.add_sized(vec2(text_width, 28.0), egui::Label::new(barcode).truncate()).on_hover_text(barcode); - let button = stitch_ui::icon_button(ui, "x", 24.0, false, &format!("删除条码 {barcode}")); - self.control_geometry(&format!("barcode-remove-{id}-{index}"), button.rect); - if button.clicked() { - remove = Some(index); - } - }); - if barcode_fields.is_array() { - let mut values = self.creation_brief["intake"]["barcodeValues"][barcode.as_str()].clone(); - if !values.is_object() { values = json!({}); } - if intake_fields(ui, field_scope.with(("intake-barcode", barcode)), width, &barcode_fields, &mut values, self.reduce_motion) { - self.creation_brief["intake"]["barcodeValues"][barcode.as_str()] = values; - self.creation_dirty = true; - } - } - } - if let Some(index) = remove { - let barcode = barcodes.remove(index); - if let Some(values) = self.creation_brief.get_mut("intake") - .and_then(|intake| intake.get_mut("barcodeValues")) - .and_then(Value::as_object_mut) - { - values.remove(&barcode); - } - changed = true; - } - ui.horizontal(|ui| { - let hint = if has_spu { "输入条码" } else { "填写 SPU 后可录入条码" }; - let entry = ui.scope(|ui| { - edit_named(ui, draft_id, &mut draft, (width - 86.0).max(40.0), false, hint, "新增条码") - }); - self.control_geometry(&format!("barcode-input-{id}"), entry.response.rect); - let text = draft.as_str().unwrap_or_default().trim(); - let valid = !text.is_empty() && text.len() <= 120 - && text.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')); - let duplicate = self.creation_brief["barcodeBindings"].as_object().into_iter().flatten() - .filter_map(|(_, binding)| binding.as_str()) - .flat_map(|binding| binding.split(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ',' | '、'))) - .any(|code| !code.is_empty() && code.eq_ignore_ascii_case(text)); - let button = stitch_ui::action_button(ui, "添加条码", stitch_ui::ButtonRole::Secondary, valid && !duplicate) - .on_disabled_hover_text(if duplicate { "此条码已录入当前项目" } else { "请输入条码" }); - self.control_geometry(&format!("barcode-add-{id}"), button.rect); - if button.clicked() { - barcodes.push(text.to_owned()); - draft = Value::Null; - changed = true; - } + if !dynamic { + if width >= 600.0 { + ui.horizontal_top(|ui| { + // The trigger and popup share a width in `picker`: keep room + // for the material search field, thumbnails and long names. + let material_width = (width - 240.0).min(420.0); + let heading_width = (width - material_width - 20.0).max(100.0); + let heading = ui.vertical(|ui| { + ui.set_width(heading_width); + section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。"); }); + self.control_geometry("material-heading", heading.response.rect); + self.material_select(app, ui, material_width); }); - }); - ui.data_mut(|data| data.insert_temp(draft_id, draft)); - if changed { - self.creation_brief["barcodeBindings"][id] = json!(barcodes.join("\n")); - self.creation_dirty = true; + } else { + section_heading(ui, "产品花色", "添加花色后,可为同一花色录入多个条码。"); + ui.add_space(6.0); + self.material_select(app, ui, width.min(420.0)); } + ui.add_space(12.0); + self.sku_colors(ui, width, field_scope); } + let barcode_pending = self.barcode_cards_ui(ui, width, field_scope); if self.creation_brief.get("barcodeBindings").is_none() { stitch_ui::disclosure(ui, field_scope.with("legacy-sku-bindings"), "旧项目商品编号", false, self.reduce_motion, |ui| { let mut variants = brief_variants(&self.creation_brief); @@ -1563,14 +1662,178 @@ impl Workspace { }); } ui.add_space(8.0); - let has_note = self.creation_brief["note"].as_str().is_some_and(|note| !note.trim().is_empty()); - stitch_ui::disclosure(ui, field_scope.with("creation-note"), "补充产品资料或出图要求(选填)", has_note, self.reduce_motion, |ui| { - self.creation_dirty |= edit_named(ui, (field_scope, "note"), &mut self.creation_brief["note"], ui.available_width(), true, - "例如:台面为白蜡木;首屏突出可折叠;避免使用未经验证的承重数据", "补充产品资料或出图要求"); - }); + self.special_requirements_ui(ui, field_scope); ui.add_space(8.0); self.references_ui(app, ui, width); brief_section_break(ui); + barcode_pending + } + + fn special_requirements_ui(&mut self, ui: &mut Ui, scope: egui::Id) { + let response = stitch_ui::disclosure(ui, scope.with("creation-note"), "+ 添加特殊制作要求(选填)", false, self.reduce_motion, |ui| { + let note = ui.scope(|ui| edit_named(ui, (scope, "note"), &mut self.creation_brief["note"], ui.available_width(), true, + "无特殊要求可留空。仅补充模板字段外的重点卖点、画面禁忌或场景偏好。", "特殊制作要求")); + self.creation_dirty |= note.inner; + self.control_geometry("special-requirements-input", note.response.rect); + }); + self.control_geometry("special-requirements", response.rect); + } + + fn barcode_cards_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id) -> bool { + let variants = brief_variants(&self.creation_brief); + let mut groups: Vec<(&str, &str)> = variants.iter().filter_map(|variant| { + Some((variant["id"].as_str()?, variant["name"].as_str().unwrap_or("条码"))) + }).collect(); + if groups.is_empty() || binding_barcodes(&self.creation_brief["barcodeBindings"]["default"]).next().is_some() { + groups.insert(0, ("default", "条码")); + } + let fields = self.creation_brief["intake"]["schema"]["barcodeFields"].clone(); + let mut ordinal = 0; + let mut pending = false; + for (id, label) in groups { + let scope = scope.with(("barcodes", id)); + let mut codes: Vec = binding_barcodes(&self.creation_brief["barcodeBindings"][id]).map(str::to_owned).collect(); + let single_before_add = project_barcodes(&self.creation_brief).take(2).count() == 1; + let (added, entry_pending) = self.barcode_entry_ui(ui, width, scope, id, label, &mut codes); + pending |= entry_pending; + let mut changed = added; + let mut remove = None; + for (index, code) in codes.iter_mut().enumerate() { + ordinal += 1; + let card = egui::Frame::NONE.stroke(egui::Stroke::new(1.0, Tokens::get(ui.ctx()).agent().card_border)) + .corner_radius(12).inner_margin(8).show(ui, |ui| { + let width = (width - 18.0).max(1.0); + ui.set_width(width); + let card_scope = scope.with(code.as_str()); + let draft_id = card_scope.with("edit"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)).unwrap_or_else(|| code.clone()); + let mut commit = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let number = ui.weak(format!("#{ordinal}")); + let edit_width = (ui.available_width() - 28.0).clamp(1.0, 260.0); + let editor = barcode_editor(ui, card_scope, &mut draft, edit_width, "编辑产品条码"); + self.control_geometry(&format!("barcode-edit-{id}-{index}"), editor.rect); + commit = editor.lost_focus() || (editor.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) && (editor.has_focus() || editor.lost_focus()) { + draft.clone_from(code); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let delete = stitch_ui::icon_button(ui, "trash", 24.0, false, "删除条码"); + self.control_geometry(&format!("barcode-remove-{id}-{index}"), delete.rect); + if delete.clicked() { remove = Some(index); } + }); + self.control_geometry(&format!("barcode-number-{id}-{index}"), number.rect); + }); + if draft.trim() != code.as_str() { + if let Some(issue) = barcode_issue(&self.creation_brief, &draft) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); + } else if commit { + let replacement = draft.trim(); + replace_barcode(&mut self.creation_brief, code, Some(replacement)); + *code = replacement.to_owned(); + changed = true; + } + } + pending |= draft.trim() != code.as_str() && remove != Some(index); + ui.data_mut(|data| { + if draft == *code || commit && draft.trim() == code.as_str() || remove == Some(index) { + data.remove::(draft_id); + } else { + data.insert_temp(draft_id, draft); + } + }); + let mut values = self.creation_brief["intake"]["barcodeValues"][code.as_str()].clone(); + if !values.is_object() { values = json!({}); } + if intake_fields(ui, card_scope, width, &fields, &mut values, self.reduce_motion) { + self.creation_brief["intake"]["barcodeValues"][code.as_str()] = values; + self.creation_dirty = true; + } + }); + self.control_geometry(&format!("barcode-card-{id}-{index}"), card.response.rect); + } + if let Some(index) = remove { + replace_barcode(&mut self.creation_brief, &codes.remove(index), None); + changed = true; + } + if changed { + self.creation_brief["barcodeBindings"][id] = json!(codes); + if added && single_before_add && let Some(fields) = self.creation_brief.as_object_mut() { + fields.remove("detailBarcode"); + } + self.creation_dirty = true; + } + } + // Older projects may only have the binding. The next save or canvas + // request carries the derived default, without autosaving on paint. + update_detail_barcode(&mut self.creation_brief); + let codes: Vec = project_barcodes(&self.creation_brief).map(str::to_owned).collect(); + if codes.len() > 1 { + let selected = self.creation_brief["detailBarcode"].as_str().unwrap_or("请选择条码").to_owned(); + field_group(ui, width, "详情页出图条码", |ui| { + let picker = stitch_ui::halo_select_with_behavior(ui, scope.with("detail-barcode"), width, &selected, self.reduce_motion, + egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { + for (index, code) in codes.iter().enumerate() { + let option = stitch_ui::select_option_sized(ui, code, code == &selected, true, vec2(ui.available_width(), 28.0)); + self.control_geometry(&format!("detail-barcode-option-{index}"), option.rect); + if option.clicked() { + self.creation_brief["detailBarcode"] = json!(code); + self.creation_dirty = true; + ui.close(); + } + } + }); + }); + self.control_geometry("detail-barcode", picker.response.rect); + }); + } + pending + } + + fn barcode_entry_ui(&mut self, ui: &mut Ui, width: f32, scope: egui::Id, id: &str, label: &str, codes: &mut Vec) -> (bool, bool) { + let draft_id = scope.with("new-barcode"); + let mut draft = ui.data(|data| data.get_temp::(draft_id)); + let mut opened = false; + ui.horizontal(|ui| { + ui.set_width(width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let add = stitch_ui::action_button(ui, "+ 添加条码", stitch_ui::ButtonRole::Quiet, true); + self.control_geometry(&format!("barcode-add-{id}"), add.rect); + if add.clicked() { + draft.get_or_insert_with(String::new); + opened = true; + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add(egui::Label::new(egui::RichText::new(label).strong()).truncate()); + }); + }); + }); + let Some(mut text) = draft else { return (false, false) }; + let editor = barcode_editor(ui, draft_id, &mut text, width, "新增产品条码"); + self.control_geometry(&format!("barcode-input-{id}"), editor.rect); + if opened { editor.request_focus(); } + let issue = barcode_issue(&self.creation_brief, &text); + if !text.trim().is_empty() && let Some(issue) = issue { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Warning); + } + let mut added = false; + let mut cancelled = false; + ui.horizontal(|ui| { + let confirm = stitch_ui::action_button(ui, "添加", stitch_ui::ButtonRole::Secondary, issue.is_none()); + self.control_geometry(&format!("barcode-confirm-{id}"), confirm.rect); + if issue.is_none() && (confirm.clicked() || ((editor.has_focus() || editor.lost_focus()) && ui.input(|input| input.key_pressed(egui::Key::Enter)))) { + codes.push(text.trim().to_owned()); + added = true; + } + cancelled = stitch_ui::action_button(ui, "取消", stitch_ui::ButtonRole::Quiet, true).clicked(); + }); + let pending = !added && !cancelled && !text.trim().is_empty(); + ui.data_mut(|data| { + if added || cancelled { data.remove::(draft_id); } + else { data.insert_temp(draft_id, text); } + }); + (added, pending) } pub(super) fn output_tags_ui(&mut self, ui: &mut Ui) { @@ -1587,7 +1850,7 @@ impl Workspace { fn brief_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) { let editable = form_editable(self.busy.as_deref(), self.unknown && !self.scoped_production_pending()); - ui.add_enabled_ui(editable, |ui| self.brief_fields_ui(app, ui)); + let barcode_pending = ui.add_enabled_ui(editable, |ui| self.brief_fields_ui(app, ui)).inner; let template = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); let missing = canvas_entry_missing(&self.creation_brief, &template); let new_project = self.template_workflow["canvasFirst"] != true; @@ -1599,6 +1862,8 @@ impl Workspace { else { "请先核查原请求,再进入模板画布。" }.into()) } else if self.busy.is_some() { Some("请等待当前操作完成。".into()) + } else if barcode_pending { + Some("请确认正在编辑的条码。".into()) } else if prerequisites == &["模板"] && chosen_pending { if self.creation_catalog_loading("resource-set") || self.creation_catalog_loading("resource-component") { Some("正在核对模板资料,请稍候。".into()) @@ -1638,13 +1903,13 @@ impl Workspace { ui.horizontal_wrapped(|ui| { let save = stitch_ui::action_button( ui, "保存资料", stitch_ui::ButtonRole::Secondary, - self.creation_dirty && self.can_save_creation(), + self.creation_dirty && self.can_save_creation() && !barcode_pending, ); self.control_geometry("save-brief", save.rect); if save.clicked() { self.creation_submit(app, "creation-save", json!({})); } - let actions_ready = self.busy.is_none() && !self.unknown; + let actions_ready = self.busy.is_none() && !self.unknown && !barcode_pending; self.brief_enter_button(app, ui, &template, blocked.is_none(), actions_ready && missing.is_empty(), refinement); if self.has_production_stages() || self.has_paused_production() { let resume = stitch_ui::action_button(ui, "继续整套制作", stitch_ui::ButtonRole::Primary, self.can_resume_product()); @@ -1837,7 +2102,7 @@ impl Workspace { }); } - fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) -> egui::Rect { let supported = ui.input(|input| { let files = &input.raw.hovered_files; !files.is_empty() && files.len() <= 8 && files.iter().all(|file| { @@ -1870,15 +2135,23 @@ impl Workspace { return Err("账号或项目已切换,未导入到其他项目".into()); } match answer { - crate::FileDialogAnswer::Paths(paths) => super::action(app, "creation-import", json!({"paths":paths})), + crate::FileDialogAnswer::Paths(paths) => { + if let Err(error) = app.import_reference_paths(paths) + && let Some(w) = app.jiansun.as_mut() + { + w.creation_reads.reference_import_error = error; + } + Ok(Value::Null) + }, _ => Err("请选择本机产品图片".into()), } }, ); if let Err(e) = result { - self.error = e; + self.creation_reads.reference_import_error = e; } } + add_reference.rect } fn brief_enter_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, template: &Value, production_ready: bool, canvas_ready: bool, refinement: Option) { @@ -1893,6 +2166,7 @@ impl Workspace { self.control_geometry("enter-canvas", enter.rect); if enter.clicked() || generate { let mut brief = self.creation_brief.clone(); + update_detail_barcode(&mut brief); let variants = brief_variants(&brief); set_brief_variants(&mut brief, variants); brief["templateSelection"] = template.clone(); @@ -1905,11 +2179,15 @@ impl Workspace { fn source_picker(&mut self, ui: &mut Ui) { let t = Tokens::get(ui.ctx()).agent(); let mut choices = Vec::new(); + let label = egui::RichText::new("资料来源").size(12.0).color(t.text_dim); + let narrow = ui.available_width() < 240.0; + if narrow { ui.label(label.clone()); } let source = ui.horizontal_wrapped(|ui| { - ui.label(egui::RichText::new("资料来源").size(12.0).color(t.text_dim)); + if !narrow { ui.label(label); } + let option_width = if narrow { (ui.available_width() - ui.spacing().item_spacing.x) / 2.0 } else { 92.0 }; for (value, label) in [("upload", "手工录入"), ("library", "素材库产品")] { let selected = self.creation_brief["source"] == value; - let response = stitch_ui::segmented_option_sized(ui, label, selected, true, vec2(92.0, 28.0)); + let response = stitch_ui::segmented_option_sized(ui, label, selected, true, vec2(option_width, 28.0)); self.control_geometry(&format!("source-{value}"), response.rect); choices.push(json!({"id":value,"label":label,"ready":true,"rect":rect_value(response.rect)})); if response.clicked() && !selected { @@ -1929,21 +2207,15 @@ impl Workspace { } fn references_ui(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { + self.poll_imported_reference_previews(app, ui.ctx()); let t = Tokens::get(ui.ctx()).agent(); let variants = brief_variants(&self.creation_brief); let mut rows = image_rows(&self.creation_brief); let mut changed = false; let mut remove = None; + let mut errors = Vec::new(); let title = ui.label(egui::RichText::new("产品参考图 *").size(13.0).color(t.text_dim)); - let mut target = title.rect; - if rows.is_empty() { - let empty = stitch_ui::material_frame(ui, stitch_ui::surface_frame(ui.ctx(), stitch_ui::SurfaceRole::Input).corner_radius(10).inner_margin(18), |ui| { - ui.set_width((width - 38.0).max(100.0)); - ui.label(egui::RichText::new("至少添加一张用途为「产品图」的参考图").size(14.0).color(t.text_dim)); - }); - self.control_geometry("reference-empty", empty.response.rect); - target = target.union(empty.response.rect); - } else if !rows.iter().any(|(image, _)| image["purpose"] == "product") { + if !rows.is_empty() && !rows.iter().any(|(image, _)| image["purpose"] == "product") { stitch_ui::status_label(ui, "请将至少一张参考图的用途设为「产品图」。", stitch_ui::StatusTone::Warning); } // Keep real purpose and ownership controls visible alongside each image. @@ -1965,7 +2237,7 @@ impl Workspace { ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = 12.0; let thumbnail_width = (inner_width * 0.32).clamp(56.0, 96.0); - let details_width = (inner_width - thumbnail_width - 12.0).max(80.0); + let details_width = (inner_width - thumbnail_width - 12.0).max(1.0); let (preview_rect, preview) = ui.allocate_exact_size(vec2(thumbnail_width, thumbnail_width), egui::Sense::hover()); if ui.is_rect_visible(preview_rect) { self.queue_creation_reference(app, &source); @@ -1996,12 +2268,14 @@ impl Workspace { "读取失败" } else if loading { "加载中…" - } else if saved { - "等待加载" } else { - "保存后预览" + "" }; - ui.painter().text(preview_rect.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), t.text_dim); + if label.is_empty() { + crate::icons::paint(ui, preview_rect, "image", 18.0, t.text_dim); + } else { + ui.painter().text(preview_rect.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(12.0), t.text_dim); + } if let Some(error) = error.as_deref() { preview.on_hover_text(error); } @@ -2012,15 +2286,19 @@ impl Workspace { ui.vertical(|ui| { ui.set_width(details_width); ui.spacing_mut().item_spacing.y = 6.0; - if error.is_some() && stitch_ui::action_button(ui, "重新读取", stitch_ui::ButtonRole::Secondary, true).clicked() { - self.retry_creation_reference(app, &source); + if let Some(error) = error.as_deref() { + let name = image["name"].as_str().unwrap_or("产品参考图"); + errors.push(format!("{name} · {error}")); + if saved && stitch_ui::action_button(ui, "重试", stitch_ui::ButtonRole::Quiet, true).clicked() { + self.retry_creation_reference(app, &source); + } } ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 4.0; ui.add(crate::icons::image("image", 17.0, t.text_dim)); let name = image["name"].as_str().unwrap_or("产品图片"); ui.add_sized( - vec2((details_width - 53.0).max(30.0), 28.0), + vec2((details_width - 53.0).max(1.0), 28.0), egui::Label::new(egui::RichText::new(name).size(13.0)).truncate(), ) .on_hover_text(name); @@ -2072,12 +2350,23 @@ impl Workspace { ui.end_row(); } } - self.add_reference_button(app, ui, card_width - 2.0); }); - let visible = target.union(grid.response.rect).intersect(ui.clip_rect()); + let drop_rect = self.add_reference_button(app, ui, width); + if rows.is_empty() { + self.control_geometry("reference-empty", drop_rect); + } + let target = title.rect.union(drop_rect); + let visible = if rows.is_empty() { target } else { target.union(grid.response.rect) }.intersect(ui.clip_rect()); self.creation_view_geometry["referenceDrop"] = json!({ "doc":app.session.active().map(|state| state.doc.id.0),"accountId":self.account["id"],"origin":self.origin,"rect":rect_value(visible) }); + for error in errors { + stitch_ui::status_label(ui, &error, stitch_ui::StatusTone::Error); + } + if !self.creation_reads.reference_import_error.is_empty() { + let status = stitch_ui::status_label(ui, &self.creation_reads.reference_import_error, stitch_ui::StatusTone::Error); + self.control_geometry("reference-import-error", status.rect); + } if let Some(label) = reference_import_activity(self.busy.as_deref()) { ui.add_space(8.0); let id = egui::Id::unique(("creation-reference-import", &self.origin, self.account["id"].as_str(), self.creation_doc)); @@ -2141,13 +2430,7 @@ impl Workspace { if active { continue; } - if self.creation_brief["intake"]["templateId"] != row["id"] { - self.creation_brief["intake"] = if row["intake"]["version"] == 1 { - json!({"templateId":row["id"],"schema":row["intake"],"productValues":{},"barcodeValues":{}}) - } else { - Value::Null - }; - } + set_intake(&mut self.creation_brief, &row["id"], &row["intake"]); self.creation_reads.resource_set = row.clone(); self.creation_reads.resource_component.clear(); self.creation_reads.resource_image = None; @@ -2248,13 +2531,8 @@ impl Workspace { } if let Some(fields) = choice.as_object_mut() { fields.remove("width"); - if let Some(schema) = fields.remove("intake") - && schema["version"] == 1 - && self.creation_brief["intake"]["templateId"] != fields["id"] - { - self.creation_brief["intake"] = json!({ - "templateId":fields["id"],"schema":schema,"productValues":{},"barcodeValues":{} - }); + if let Some(schema) = fields.remove("intake") { + set_intake(&mut self.creation_brief, &fields["id"], &schema); } } self.creation_brief["templateSelection"] = choice; @@ -2371,6 +2649,9 @@ impl Workspace { json!({"id":row["id"],"version":row["version"],"contentHash":row["contentHash"],"ready":enabled,"hasStructurePreview":preview.is_some(),"rect":rect_value(item.rect)}), ); if item.clicked() && !fixed { + if !is_selected { + set_intake(&mut self.creation_brief, &row["id"], &row["intake"]); + } self.creation_brief["templateSelection"] = choice; self.creation_dirty = true; ui.close(); @@ -3606,6 +3887,179 @@ mod tests { } + fn barcode_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { + let (mut w, app, requests) = brief_fixture(); + set_brief_variants(&mut w.creation_brief, vec![]); + w.creation_brief["images"] = json!([]); + w.creation_brief["barcodeBindings"] = json!({"default":["DNZ030516N717V01","CY001307N35V01"]}); + set_intake(&mut w.creation_brief, &json!("template"), &json!({"version":1, + "productFields":[ + {"id":"summary","label":"固定卖点","type":"text"}, + {"id":"new_kind","label":"扩展字段","type":"future-kind"} + ], + "barcodeFields":[ + {"id":"color","label":"颜色组合","type":"text"}, + {"id":"length","label":"长度","type":"number","unit":"mm"}, + {"id":"width","label":"宽度","type":"number","unit":"mm"}, + {"id":"height","label":"高度","type":"number","unit":"mm"} + ]})); + w.creation_brief["intake"]["barcodeValues"]["DNZ030516N717V01"] = json!({"length":1200,"width":580,"height":750}); + (w, app, requests) + } + + #[test] + fn barcode_bindings_read_legacy_lists_and_deduplicate_the_complete_trimmed_values() { + let legacy = json!(" DNZ030516N717V01,;CY001307N35V01、\r\nDNZ030516N717V01 "); + assert_eq!(binding_barcodes(&legacy).collect::>(), ["DNZ030516N717V01", "CY001307N35V01"]); + let exact = "0007 台面/甲+乙,A;B\n编码\t二🪑"; + let brief = json!({"barcodeBindings":{"default":["DNZ030516N717V01", "CY001307N35V01", exact]}}); + assert_eq!(project_barcodes(&brief).last(), Some(exact)); + assert_eq!(barcode_issue(&brief, &format!(" {exact} ")), Some("此条码已录入当前项目")); + assert_eq!(barcode_issue(&brief, "cy001307n35v01"), None); + assert_eq!(barcode_issue(&brief, "cy001301N35"), None); + assert_eq!(barcode_issue(&brief, "SJ021613N16V01"), None); + assert_eq!(barcode_issue(&brief, &"A".repeat(121)), None); + assert_eq!(barcode_issue(&brief, " \t\n"), Some("请输入产品条码")); + } + + #[test] + fn pasted_barcode_survives_the_form_and_save_payload_without_losing_characters() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_brief["barcodeBindings"] = json!({}); + w.reduce_motion = true; + let ctx = egui::Context::default(); + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } + let add = control_rect(&w, "barcode-add-default").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(add)); + let exact = "0007 台面/甲+乙,A;B\r\n编码\t二🪑"; + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![egui::Event::Paste(format!(" \t{exact}\n "))]); + let apply = control_rect(&w, "barcode-confirm-default").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(apply)); + assert_eq!(w.creation_brief["barcodeBindings"]["default"], json!([exact])); + assert_eq!(w.creation_brief["detailBarcode"], exact); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if method == "creation-save" + && input["brief"]["barcodeBindings"]["default"] == json!([exact]) + && input["brief"]["detailBarcode"] == exact)); + } + + #[test] + fn detail_barcode_defaults_for_one_and_follows_rename_or_removal() { + let (mut w, mut app, requests) = barcode_fixture(); + assert!(!update_detail_barcode(&mut w.creation_brief)); + assert!(canvas_entry_missing(&w.creation_brief, &Value::Null).contains(&"详情页出图条码")); + w.creation_brief["detailBarcode"] = json!("DNZ030516N717V01"); + replace_barcode(&mut w.creation_brief, "DNZ030516N717V01", Some("SG008839N1049V01")); + w.creation_brief["barcodeBindings"]["default"] = json!(["SG008839N1049V01","CY001307N35V01"]); + assert_eq!(w.creation_brief["detailBarcode"], "SG008839N1049V01"); + assert_eq!(w.creation_brief["intake"]["barcodeValues"]["SG008839N1049V01"]["length"], 1200); + w.creation_action(&mut app, "creation-save", json!({})).unwrap(); + assert!(matches!(requests.try_recv(), Ok(Request::Action(method, input)) if + method == "creation-save" && input["brief"]["detailBarcode"] == "SG008839N1049V01")); + replace_barcode(&mut w.creation_brief, "SG008839N1049V01", None); + w.creation_brief["barcodeBindings"]["default"] = json!(["CY001307N35V01"]); + assert!(update_detail_barcode(&mut w.creation_brief)); + assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); + } + + #[test] + fn dynamic_barcode_form_keeps_cards_and_controls_within_wide_and_narrow_bounds() { + assert_eq!(intake_columns(178.0), 2); + assert_eq!(intake_columns(460.0), 3); + for width in [248.0, 760.0, 900.0] { + let (mut w, mut app, _) = barcode_fixture(); + let ctx = egui::Context::default(); + w.reduce_motion = true; + brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let bounds = brief_frame(&mut w, &mut app, &ctx, width, vec![]); + let card = control_rect(&w, "barcode-card-default-0"); + let second = control_rect(&w, "barcode-card-default-1"); + let edit = control_rect(&w, "barcode-edit-default-0"); + let delete = control_rect(&w, "barcode-remove-default-0"); + assert!(card.right() <= bounds.right() + 1.0 && second.right() <= bounds.right() + 1.0); + assert!(card.contains_rect(edit) && card.contains_rect(delete)); + assert!(bounds.contains_rect(control_rect(&w, "source-library"))); + assert!(edit.left() < card.left() + 52.0 && edit.right() < delete.left()); + assert!(card.bottom() <= second.top()); + assert!(w.creation_view_geometry["controls"]["dimensions"].is_null()); + assert!(w.creation_view_geometry["controls"]["material"].is_null()); + assert!(w.creation_view_geometry["controls"]["output-width"].is_null()); + assert!(w.creation_view_geometry["controls"]["barcode-input-default"].is_null()); + let add = control_rect(&w, "barcode-add-default").center(); + brief_frame(&mut w, &mut app, &ctx, width, click_events(add)); + assert!(control_rect(&w, "barcode-input-default").is_positive(), "SPU can still be blank"); + } + } + + #[test] + fn detail_barcode_selector_changes_the_brief_used_by_the_form() { + let (mut w, mut app, requests) = barcode_fixture(); + w.creation_brief["identifier"] = json!("QA-DESK-001"); + w.creation_brief["images"] = json!([{"source":"test-reference","name":"产品图.png","purpose":"product"}]); + let ctx = egui::Context::default(); + w.reduce_motion = true; + for _ in 0..2 { brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); } + let picker = control_rect(&w, "detail-barcode").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(picker)); + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); + let option = control_rect(&w, "detail-barcode-option-1").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(option)); + assert_eq!(w.creation_brief["detailBarcode"], "CY001307N35V01"); + assert_eq!(w.creation_draft()["brief"]["detailBarcode"], "CY001307N35V01"); + let enter = control_rect(&w, "enter-canvas").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(enter)); + assert!(matches!(requests.try_recv(), Ok(Request::Save(_, _, _)))); + assert_eq!(w.pending_slot_apply.as_ref().unwrap()["brief"]["detailBarcode"], "CY001307N35V01"); + } + + #[test] + fn template_form_shows_unknown_fields_and_starts_with_optional_requirements_collapsed() { + let (mut w, mut app, _) = barcode_fixture(); + w.creation_brief["note"] = json!("已保存的特殊制作要求"); + w.reduce_motion = true; + let ctx = egui::Context::default(); + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); + assert!(w.creation_view_geometry["controls"]["special-requirements-input"].is_null()); + let disclosure = control_rect(&w, "special-requirements").center(); + brief_frame(&mut w, &mut app, &ctx, 760.0, click_events(disclosure)); + brief_frame(&mut w, &mut app, &ctx, 760.0, vec![]); + assert!(control_rect(&w, "special-requirements-input").is_positive()); + assert_eq!(w.creation_brief["note"], "已保存的特殊制作要求"); + + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + intake_fields(ui, egui::Id::unique("unknown-field-test"), 360.0, + &json!([{"id":"unexpected","label":"扩展字段","type":"future-kind"}]), &mut json!({}), true); + }); + let text = out.shapes.iter().filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.galley.text()), + _ => None, + }).collect::>(); + assert!(text.iter().any(|text| text.contains("暂不支持此字段类型(future-kind)")), "{text:?}"); + out.textures_delta.clear(); + } + + #[test] + #[ignore = "offscreen GPU visual evidence; requires PHOTOCRAFT_AGENT_QA_OUT"] + fn barcode_form_visual_acceptance() { + let directory = std::env::var("PHOTOCRAFT_AGENT_QA_OUT").expect("explicit evidence directory"); + for (width, height) in [(248.0, 2100.0), (900.0, 1600.0)] { + let (mut w, app, _) = barcode_fixture(); + w.creation_brief["name"] = json!("轻量可调工作台"); + w.creation_brief["identifier"] = json!("QA-DESK-001"); + w.creation_brief["detailBarcode"] = json!("CY001307N35V01"); + w.reduce_motion = true; + let mut h = egui_kittest::Harness::builder().with_size(vec2(width, height)).wgpu().build_ui_state( + |ui, state: &mut (Workspace, PhotocraftApp)| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + stitch_ui::scope(ui, |ui| state.0.brief_ui(&mut state.1, ui)); + } + }, (w, app)); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(4); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("barcode-form-{width}.png"))).unwrap(); + } + } + #[test] fn resumed_project_shows_continue_after_the_originals_settle() { let (mut w, mut app, _) = brief_fixture(); @@ -3811,7 +4265,7 @@ mod tests { assert_eq!(app.session.documents().len(), 1); assert_eq!(workspace.creation_brief, before); assert!(workspace.creation_dirty); - assert!(workspace.error.contains("产品参考图")); + assert!(workspace.creation_reads.reference_import_error.contains("产品参考图")); assert!(requests.try_recv().is_err()); } @@ -3851,7 +4305,7 @@ mod tests { else if mode == "count" { (0..9).map(|_| reference_drop("D:\\photos\\oak.png")).collect() } else { vec![reference_drop("D:\\photos\\oak.png")] }; app.open_dropped(&ctx, files, Some(at)); - assert!(!app.jiansun.as_ref().unwrap().error.is_empty(), "{mode} should explain why the drop was not imported"); + assert!(!app.jiansun.as_ref().unwrap().creation_reads.reference_import_error.is_empty(), "{mode} should explain why the drop was not imported"); assert_eq!(app.session.documents().len(), 1, "{mode} should not accidentally open a new document"); assert!(requests.try_recv().is_err(), "{mode} must not dispatch an import"); } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs index 928df6ca..ef1c71f6 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs @@ -38,6 +38,11 @@ pub(super) struct UiState { thumbnail_errors: HashMap, cache_order: VecDeque, pub(super) reference_previews: HashMap, + pub(super) reference_import_error: String, + pub(super) reference_import_paths: Option>, + imported_reference_files: Vec<(String, String)>, + #[cfg(not(target_arch = "wasm32"))] + imported_reference_previews: Vec>, pub(super) resource_set: Value, pub(super) resource_component: String, pub(super) resource_query: String, @@ -83,7 +88,7 @@ fn brief_reference(brief: &Value, source: &str) -> bool { } impl Workspace { - fn creation_read_scope(&mut self, app: &PhotocraftApp) { + pub(super) fn creation_read_scope(&mut self, app: &PhotocraftApp) { let scope = Scope { account: self.account["id"].as_str().unwrap_or("").into(), origin: self.origin.clone(), @@ -99,6 +104,11 @@ impl Workspace { self.creation_reads.desired.clear(); self.creation_reads.catalog_errors.clear(); self.creation_reads.thumbnail_errors.clear(); + self.creation_reads.reference_import_error.clear(); + self.creation_reads.reference_import_paths = None; + self.creation_reads.imported_reference_files.clear(); + #[cfg(not(target_arch = "wasm32"))] + self.creation_reads.imported_reference_previews.clear(); self.creation_catalog.clear(); self.creation_reads.resource_set = Value::Null; self.creation_reads.resource_component.clear(); @@ -166,6 +176,68 @@ impl Workspace { pub(super) fn queue_creation_thumbnail(&mut self, app: &PhotocraftApp, id: &str) { self.queue_creation_thumbnail_kind(app, "material", id, None); } + pub(super) fn match_imported_reference_paths(&mut self, app: &PhotocraftApp, images: &[Value]) { + self.creation_read_scope(app); + let Some(paths) = self.creation_reads.reference_import_paths.take() else { return }; + if paths.len() == images.len() { + self.creation_reads.imported_reference_files.extend(paths.into_iter().zip(images) + .filter_map(|(path, image)| Some((image["source"].as_str()?.to_owned(), path)))); + } + } + + pub(super) fn poll_imported_reference_previews(&mut self, app: &PhotocraftApp, ctx: &egui::Context) { + #[cfg(target_arch = "wasm32")] + let _ = (app, ctx); + #[cfg(not(target_arch = "wasm32"))] + { + use std::sync::mpsc::{self, TryRecvError}; + if self.creation_reads.imported_reference_files.is_empty() && self.creation_reads.imported_reference_previews.is_empty() { + return; + } + self.creation_read_scope(app); + let files = std::mem::take(&mut self.creation_reads.imported_reference_files); + if !files.is_empty() { + let (send, receive) = mpsc::channel(); + let ctx = ctx.clone(); + let worker = std::thread::Builder::new().name("product-reference-previews".into()).spawn(move || { + let previews: ImportedPreviews = files.into_iter().map(|(source, path)| { + let decoded = imported_reference_preview(&source, &path); + (source, decoded) + }).collect(); + let _ = send.send(previews); + ctx.request_repaint(); + }); + if worker.is_ok() { + self.creation_reads.imported_reference_previews.push(receive); + } else { + self.creation_reads.reference_import_error = "无法生成本地参考图预览".into(); + } + } + let mut previews = Vec::new(); + self.creation_reads.imported_reference_previews.retain(|receive| { + match receive.try_recv() { + Ok(batch) => { previews.extend(batch); false } + Err(TryRecvError::Empty) => true, + Err(TryRecvError::Disconnected) => false, + } + }); + for (source, preview) in previews { + if !brief_reference(&self.creation_brief, &source) { continue; } + let key = reference_key(&source); + match preview { + Ok(image) => { + let texture = ctx.load_texture(&key, image, egui::TextureOptions::LINEAR); + self.store_creation_thumbnail(key, texture); + } + Err(error) if !self.creation_reference_saved(app, &source) => { + self.creation_reads.thumbnail_errors.insert(key, error); + } + Err(_) => {} + } + } + } + } + pub(super) fn creation_reference_saved(&self, app: &PhotocraftApp, source: &str) -> bool { self.creation_doc.is_some() && self.creation_doc == app.session.active().map(|state| state.doc.id.0) && brief_reference(&self.creation["brief"], source) } @@ -374,6 +446,13 @@ impl Workspace { self.pump_creation_reads(); return true; } + self.store_creation_thumbnail(id, texture); + self.pump_creation_reads(); + true + } + + fn store_creation_thumbnail(&mut self, id: String, texture: egui::TextureHandle) { + self.creation_reads.thumbnail_errors.remove(&id); self.creation_reads.cache_order.retain(|old| old != &id); self.creation_reads.cache_order.push_back(id.clone()); self.creation_thumbs.insert(id, texture); @@ -383,15 +462,91 @@ impl Workspace { }; self.creation_thumbs.remove(&old); } - self.pump_creation_reads(); - true } } +#[cfg(not(target_arch = "wasm32"))] +type ImportedPreviews = Vec<(String, Result)>; + +#[cfg(not(target_arch = "wasm32"))] +fn imported_reference_preview(source: &str, path: &str) -> Result { + use photocraft_codecs::{ChannelLayout, DecodeOptions, Format, Limits, SampleType}; + use sha2::{Digest, Sha256}; + use std::{fs::File, io::Read}; + + // The receipt identifies a normalized PNG, so verify against that same + // encoding before using pixels from a source file that may have changed. + const MAX_BYTES: usize = 20 * 1024 * 1024; + let file = File::open(path).map_err(|_| "原参考图已移动或无法读取")?; + if !file.metadata().is_ok_and(|metadata| metadata.is_file() && metadata.len() <= MAX_BYTES as u64) { + return Err("原参考图无法读取或超过20 MB".into()); + } + let mut bytes = Vec::new(); + file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes).map_err(|_| "原参考图读取中断")?; + if bytes.len() > MAX_BYTES { return Err("原参考图超过20 MB".into()); } + let mut decoded = photocraft_codecs::decode_with(&bytes, &DecodeOptions { + limits: Limits { max_width: 8192, max_height: 8192, max_pixels: 24_000_000, max_alloc: 192 * 1024 * 1024 }, + ..Default::default() + }).map_err(|_| "原参考图无法解码")?; + decoded.meta = Default::default(); + let encoded = photocraft_codecs::encode(&decoded, Format::Png, &Default::default()).map_err(|_| "无法核对参考图内容")?; + if source != format!("local:{:x}", Sha256::digest(encoded)) { + return Err("原参考图内容已变化,请重新添加要使用的图片".into()); + } + let rgba = decoded.convert(ChannelLayout::Rgba, SampleType::U8); + let width = rgba.width() as usize; + let height = rgba.height() as usize; + let longest = width.max(height); + if longest == 0 { return Err("参考图尺寸无效".into()); } + let edge = longest.min(320); + let size = [(width * edge / longest).max(1), (height * edge / longest).max(1)]; + let mut thumb = Vec::with_capacity(size[0] * size[1] * 4); + for y in 0..size[1] { + for x in 0..size[0] { + let offset = (y * height / size[1] * width + x * width / size[0]) * 4; + thumb.extend_from_slice(rgba.data().get(offset..offset + 4).ok_or("参考图像素不完整")?); + } + } + Ok(egui::ColorImage::from_rgba_unmultiplied(size, &thumb)) +} + #[cfg(test)] mod tests { use std::sync::mpsc; use super::*; + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn local_import_preview_uses_the_receipt_pixels_without_saving_the_brief() { + use sha2::{Digest, Sha256}; + let (mut w, app, requests) = fixture(); + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("product.png"); + let rgba = [240, 80, 35, 255, 10, 155, 240, 255]; + use photocraft_codecs::{ChannelLayout, Image, SampleType}; + let mut png = Image::new(2, 1, ChannelLayout::Rgba, SampleType::U8).unwrap(); + png.data_mut().copy_from_slice(&rgba); + let encoded = photocraft_codecs::encode(&png, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(&path, &encoded).unwrap(); + let mut normalized = photocraft_codecs::decode(&encoded).unwrap(); + normalized.meta = Default::default(); + let canonical = photocraft_codecs::encode(&normalized, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let source = format!("local:{:x}", Sha256::digest(&canonical)); + let path = path.to_str().unwrap(); + let preview = imported_reference_preview(&source, path).unwrap(); + assert_eq!(preview.size, [2, 1]); + assert_eq!(preview.pixels[0], egui::Color32::from_rgb(240, 80, 35)); + assert_eq!(preview.pixels[1], egui::Color32::from_rgb(10, 155, 240)); + assert!(imported_reference_preview("local:changed-file", path).is_err()); + + w.creation_read_scope(&app); + w.creation_reads.reference_import_paths = Some(vec![path.into()]); + let images = json!([{"source":source,"purpose":"product","name":"product.png"}]); + w.match_imported_reference_paths(&app, images.as_array().unwrap()); + assert!(!w.creation_reference_saved(&app, &source)); + assert_eq!(w.creation_reads.imported_reference_files, vec![(source, path.to_owned())]); + assert!(requests.try_recv().is_err(), "reading the original pixels doesn't need a save or backend request"); + } + fn fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver) { let (tx, requests) = mpsc::channel(); let (_, rx) = mpsc::channel(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs index 55fa9c03..0de230ca 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_ui.rs @@ -2079,7 +2079,8 @@ pub(super) fn file_drop_zone(ui: &mut Ui, id: egui::Id, width: f32, drop_pointer let background=painter.add(egui::Shape::Noop); let interacting=enabled && (active || response.hovered() || response.has_focus()); let strength=ui.ctx().animate_bool_with_time(id.with("drop-material"),interacting,if reduced {0.0} else {timing::MATERIAL as f32}); - material(ui,id,rect,12.0,0.52*strength,background); + let gain = 0.52 * strength; + material_over(ui, id, rect, 12.0, gain, background, material_fallback(gain), Color32::TRANSPARENT); let color = drop_halo_outline(ui, id.with("rim"), rect, 12.0, active, reduced); let title = if active { "释放以上传图片" } else if rect.width() < 230.0 { "添加参考图" } else { "拖放图片,或点击添加参考图" }; let foreground = if enabled { t.text } else { t.text_faint };