diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs index 0a01bc01..af1ed76d 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs @@ -368,11 +368,18 @@ pub fn enterprise(pack: &Value, prepared: &Value, component: &str, document: Opt .filter(|output| output["component"] == component && document.is_none_or(|id| output["id"] == id)).cloned().collect(); if outputs.is_empty() { return Err("当前固定模板没有所选组件,请检查模板更新".into()); } if document.is_some() { for output in &mut outputs { output["top"] = json!(0); } } - for font in prepared["fonts"].as_array().ok_or("模板字体清单无效")? { - let bytes = fs::read(font.as_str().ok_or("字体路径无效")?).map_err(|_| "模板字体无法读取")?; + let substitutions = load_font_substitutions(pack, prepared, component); + let fonts = prepared["fonts"].as_array().ok_or("模板字体清单无效")?; + if !fonts.is_empty() || !substitutions.is_empty() { let shared = photocraft_text::shared(); let mut engine = shared.lock().map_err(|_| "字体引擎不可用")?; - if engine.fonts.register_font_data(bytes).is_empty() { return Err("模板字体无法加载".into()); } + for font in fonts { + let bytes = fs::read(font.as_str().ok_or("字体路径无效")?).map_err(|_| "模板字体无法读取")?; + if engine.fonts.register_font_data(bytes).is_empty() { return Err("模板字体无法加载".into()); } + } + if !substitutions.is_empty() { + engine.fonts.register_postscript_substitutions(substitutions); + } } let sources = prepared["originals"].as_array().cloned().unwrap_or_else(|| vec![json!({ "assetId":pack["enterprise"]["originalAssetId"],"originalPath":prepared["originalPath"],"canvas":pack["enterprise"]["canvas"] @@ -563,6 +570,112 @@ fn scale_text_points(layers: &mut [Layer], scale: f32) { } } +fn parse_font_substitutions(value: &Value, out: &mut HashMap) { + const FROM_KEYS: &[&str] = &[ + "from", "source", "missing", "original", "original_postscript_name", + "missing_postscript_name", "source_postscript_name", "postscript_name", + ]; + const TO_KEYS: &[&str] = &[ + "to", "target", "replacement", "substitute", "substitute_postscript_name", + "replacement_postscript_name", "target_postscript_name", "postscript_name", + ]; + let mut insert = |source: &str, target: &str| { + let source = source.trim(); + let target = target.trim(); + if !source.is_empty() && !target.is_empty() && source != target { + out.insert(source.to_string(), target.to_string()); + } + }; + match value { + Value::Object(map) => { + for (source, target) in map { + if let Some(target_str) = target.as_str() { + insert(source, target_str); + } else if let Some(target_str) = first_str(target, TO_KEYS) { + insert(source, target_str); + } + } + } + Value::Array(items) => { + for item in items { + if let (Some(source), Some(target)) = (first_str(item, FROM_KEYS), first_str(item, TO_KEYS)) { + insert(source, target); + } + } + } + _ => {} + } +} + +fn read_font_manifest_from_bundle(bundle_path: &Path, manifest_entry: &str, out: &mut HashMap) -> bool { + let Ok(file) = fs::File::open(bundle_path) else { return false }; + let Ok(mut archive) = zip::ZipArchive::new(file) else { return false }; + let Ok(mut entry) = archive.by_name(manifest_entry) else { return false }; + let Ok(manifest) = serde_json::from_reader::<_, Value>(&mut entry) else { return false }; + for key in ["font_substitutions", "fontSubstitutions"] { + if let Some(subs) = manifest.get(key) { + parse_font_substitutions(subs, out); + } + } + true +} + +fn load_font_substitutions(pack: &Value, prepared: &Value, component: &str) -> HashMap { + let mut out = HashMap::new(); + if let Some(manifest_path) = pack.get("xiaoyi") + .and_then(|x| x.get("fontManifests")) + .and_then(|m| m.get(component)) + .and_then(Value::as_str) + { + let mut bundle_candidates = Vec::new(); + if let Some(explicit) = prepared["bundlePath"].as_str() { + bundle_candidates.push(Path::new(explicit).to_path_buf()); + } + if let Some(rev) = pack["enterprise"]["manifestRevision"].as_str().filter(|s| !s.is_empty()) { + let mut dirs = Vec::new(); + for p in prepared["fonts"].as_array().into_iter().flatten().filter_map(Value::as_str) { + if let Some(dir) = Path::new(p).parent() { + dirs.push(dir.to_path_buf()); + } + } + for asset in pack["xiaoyi"]["assets"].as_array().into_iter().flatten() { + if let Some(dir) = asset["localPath"].as_str().and_then(|p| Path::new(p).parent()) { + dirs.push(dir.to_path_buf()); + } + } + for dir in dirs { + bundle_candidates.push(dir.join(rev)); + bundle_candidates.push(dir.join(format!("{rev}.zip"))); + } + } + for candidate in bundle_candidates { + if read_font_manifest_from_bundle(&candidate, manifest_path, &mut out) { + break; + } + } + } + if let Some(xiaoyi) = pack.get("xiaoyi") { + for key in ["font_substitutions", "fontSubstitutions"] { + if let Some(subs) = xiaoyi.get(key) { + parse_font_substitutions(subs, &mut out); + } + } + } + if let Some(manifest) = prepared.get("fontManifest") { + for key in ["font_substitutions", "fontSubstitutions"] { + if let Some(subs) = manifest.get(key) { + parse_font_substitutions(subs, &mut out); + } + } + } + for key in ["font_substitutions", "fontSubstitutions"] { + if let Some(subs) = prepared.get(key) { + parse_font_substitutions(subs, &mut out); + } + } + out +} + #[test] fn jiansun_stacked_text_keeps_pixel_size_and_line_spacing() { let mut layer = Layer::new("copy", LayerContent::Text(photocraft_doc::TextLayer { @@ -1631,4 +1744,61 @@ mod tests { let err = enterprise_source(&pack, &source, &[&bad_output], &uuid::Uuid::nil().to_string()).unwrap_err(); assert!(err.contains("K01-T99") && err.contains("外层同ID文字") && err.contains("卖点1"), "unexpected err: {err}"); } + + #[test] + fn enterprise_wires_font_substitutions_from_manifest_bundle_and_falls_back_smoothly() { + use std::io::Write as _; + let dir = tempfile::tempdir().unwrap(); + let rev = "a".repeat(64); + let bundle_path = dir.path().join(&rev); + let manifest_entry = "SFY-COATRACK-001/主图/字体清单.json"; + { + let file = fs::File::create(&bundle_path).unwrap(); + let mut zip = zip::ZipWriter::new(file); + zip.start_file(manifest_entry, zip::write::SimpleFileOptions::default()).unwrap(); + let content = json!({ + "font_substitutions": { + "Alibaba-PuHuiTi-M": "AlibabaPuHuiTi-Medium", + "Alibaba-PuHuiTi-R": "AlibabaPuHuiTi-Regular", + "Missing-Source": "NonExistent-Target" + } + }); + zip.write_all(content.to_string().as_bytes()).unwrap(); + zip.finish().unwrap(); + } + let dummy_font = dir.path().join("AlibabaPuHuiTi-Medium.ttf"); + fs::write(&dummy_font, b"").unwrap(); + let pack = json!({ + "enterprise": { "manifestRevision": rev }, + "xiaoyi": { + "fontManifests": { "main_images": manifest_entry }, + "assets": [{ "type": "font", "component": "main_images", "localPath": dummy_font }] + } + }); + let prepared = json!({ "fonts": [] }); + let subs = load_font_substitutions(&pack, &prepared, "main_images"); + assert_eq!(subs.get("Alibaba-PuHuiTi-M").map(String::as_str), Some("AlibabaPuHuiTi-Medium")); + assert_eq!(subs.get("Alibaba-PuHuiTi-R").map(String::as_str), Some("AlibabaPuHuiTi-Regular")); + assert_eq!(subs.get("Missing-Source").map(String::as_str), Some("NonExistent-Target")); + + // Missing bundle or manifest falls back smoothly to empty map without errors. + let missing_pack = json!({ + "enterprise": { "manifestRevision": "b".repeat(64) }, + "xiaoyi": { "fontManifests": { "main_images": manifest_entry } } + }); + assert!(load_font_substitutions(&missing_pack, &prepared, "main_images").is_empty()); + + // Verify FontDb substitution resolution & smooth fallback on shared engine. + let mut db = photocraft_text::FontDb::new(); + db.register_font_data(photocraft_text::fonts::INTER_MEDIUM.to_vec()); + db.register_postscript_substitutions([ + ("Alibaba-PuHuiTi-M", "Inter-Medium"), + ("Missing-Source", "NonExistent-Target"), + ]); + let hit = db.resolve_postscript("Alibaba-PuHuiTi-M"); + assert!(hit.exact); + assert_eq!(hit.family, "Inter"); + let miss = db.resolve_postscript("Missing-Source"); + assert!(!miss.exact); + } } diff --git a/apps/detail-photocraft/crates/text/src/fonts.rs b/apps/detail-photocraft/crates/text/src/fonts.rs index 416ae783..b0f412a1 100644 --- a/apps/detail-photocraft/crates/text/src/fonts.rs +++ b/apps/detail-photocraft/crates/text/src/fonts.rs @@ -191,6 +191,8 @@ pub struct FontDb { system_loaded: bool, /// PostScript name → (family, weight, italic), filled lazily. ps_cache: HashMap>, + /// Manifest-declared PostScript substitutions (`missing_ps -> bundled_ps`). + ps_substitutions: HashMap, fallbacks: Vec, /// Preferences ▸ Type ▸ Missing Glyph Protection: route glyphs the chosen face lacks through /// [`Self::fallback_stack`] (#1909). Off, only the default family shapes the text. @@ -218,6 +220,7 @@ impl FontDb { fcx: FontContext { collection, source_cache: SourceCache::default() }, system_loaded: false, ps_cache: HashMap::new(), + ps_substitutions: HashMap::new(), fallbacks: Vec::new(), missing_glyph_protection: true, face_cache: HashMap::new(), @@ -295,6 +298,35 @@ impl FontDb { self.register_blob(Blob::new(Arc::new(bytes)), None) } + /// Registers PostScript-name substitution aliases (`source_ps -> target_ps`), e.g. from a + /// template font manifest's `font_substitutions`. Empty or self-referential pairs are ignored. + pub fn register_postscript_substitutions(&mut self, pairs: I) + where + I: IntoIterator, + K: Into, + V: Into, + { + let mut changed = false; + for (source, target) in pairs { + let source = source.into(); + let target = target.into(); + let source = source.trim(); + let target = target.trim(); + if source.is_empty() || target.is_empty() || source == target { + continue; + } + self.ps_cache.remove(source); + self.ps_substitutions.insert(source.to_string(), target.to_string()); + changed = true; + } + if changed { + GENERATION.fetch_add(1, Ordering::Relaxed); + if self.shared { + SHARED_GENERATION.fetch_add(1, Ordering::Relaxed); + } + } + } + /// Registers embedded font data without copying it. fn register_static_font(&mut self, bytes: &'static [u8]) -> Vec { self.register_blob(Blob::new(Arc::new(bytes)), None) @@ -515,7 +547,12 @@ impl FontDb { pub(crate) fn select_named_face(&mut self, style: &mut photocraft_doc::text::CharStyle) { let family = style.font_family.clone(); let faces = self.faces(&family); - let index = style.postscript_name.as_ref().and_then(|ps| faces.iter().position(|f| f.postscript_name.as_ref() == Some(ps))); + let index = style.postscript_name.as_ref().and_then(|ps| { + faces.iter().position(|f| f.postscript_name.as_ref() == Some(ps)).or_else(|| { + let target = self.ps_substitutions.get(ps)?; + faces.iter().position(|f| f.postscript_name.as_ref() == Some(target)) + }) + }); // The named instance is tried before the style-and-weight fallback: a variable face's own // style ("Regular") can match a populated `font_style` and would drop the instance's axes. let instance = match (index, &style.postscript_name) { @@ -602,7 +639,11 @@ impl FontDb { return r.clone(); } let guess = guess_from_postscript(ps); - let exact = self.find_exact(ps, &guess.family); + let exact = self.find_exact(ps, &guess.family).or_else(|| { + let target = self.ps_substitutions.get(ps).cloned()?; + let target_guess = guess_from_postscript(&target); + self.find_exact(&target, &target_guess.family) + }); let r = exact.unwrap_or_else(|| { // Keep the guessed family only if we have it; otherwise let fallback pick. let mut g = guess.clone(); diff --git a/apps/detail-photocraft/crates/text/src/fonts/font_names_tests.rs b/apps/detail-photocraft/crates/text/src/fonts/font_names_tests.rs index a1eda9b8..d5610710 100644 --- a/apps/detail-photocraft/crates/text/src/fonts/font_names_tests.rs +++ b/apps/detail-photocraft/crates/text/src/fonts/font_names_tests.rs @@ -468,3 +468,33 @@ fn postscript_name_of_a_named_instance_lays_out_at_that_instance() { assert!(explicit < family * 0.8, "wdth 75 is narrower: {explicit} vs {family}"); assert!((instance - explicit).abs() < 0.5, "instance: {instance} px, its axes: {explicit} px, default instance: {family} px"); } + +#[test] +fn postscript_substitutions_resolve_alias_and_fallback_when_target_missing() { + let mut db = FontDb::new(); + db.register_font_data(numeric_font(&INTER_SEMIBOLD, "Medium", "AlibabaPuHuiTi-Medium")); + db.register_postscript_substitutions([ + ("Alibaba-PuHuiTi-M", "AlibabaPuHuiTi-Medium"), + ("MissingFont-R", "NonExistent-Regular"), + ]); + + let resolved = db.resolve_postscript("Alibaba-PuHuiTi-M"); + assert!(resolved.exact, "expected exact match via substitution"); + assert_eq!(resolved.family, "Numeric Test"); + + let mut style = CharStyle { + font_family: resolved.family.clone(), + weight: resolved.weight, + italic: resolved.italic, + postscript_name: Some("Alibaba-PuHuiTi-M".into()), + ..Default::default() + }; + db.select_named_face(&mut style); + assert_ne!(style.font_family, "Numeric Test", "substitution should select the exact target face alias"); + assert_eq!(db.faces(&style.font_family)[0].postscript_name.as_deref(), Some("AlibabaPuHuiTi-Medium")); + + // Missing target font falls back smoothly without erroring or claiming an exact match. + let missing = db.resolve_postscript("MissingFont-R"); + assert!(!missing.exact); + assert_eq!(missing.family, "Missing Font"); +}