PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Type tool: list fonts' real style names, including numeric subfamilies (#1844)
Minseo Lee9f23d652627c
diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rsindex f9342da83..bbf2419bc 100644--- a/crates/engine/src/type_cmds.rs+++ b/crates/engine/src/type_cmds.rs@@ -130,26 +130,41 @@ pub fn apply_char_props(s: &mut CharStyle, p: &Value) -> bool {s.postscript_name = None;hit(true);}- if let Some(v) = p.get("postscriptName").and_then(Value::as_str) {- s.postscript_name = Some(v.to_string());- hit(true);- }if let Some(v) = p.get("fontStyle").and_then(Value::as_str) {s.font_style = v.to_string();+ s.postscript_name = None;let l = v.to_lowercase();s.italic = l.contains("italic") || l.contains("oblique");let g = photocraft_text::fonts::guess_from_postscript(&format!("X-{}", v.replace(' ', "")));s.weight = g.weight;+ if let Some(face) = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.named_face(&s.font_family, v) {+ s.weight = face.weight.round() as u16;+ s.italic = face.italic;+ s.postscript_name = face.postscript_name;+ }hit(true);}if let Some(v) = p.get("weight").and_then(Value::as_f64) {- s.weight = v.clamp(1.0, 1000.0) as u16;+ let weight = v.clamp(1.0, 1000.0) as u16;+ if s.weight != weight {+ s.postscript_name = None;+ s.font_style.clear();+ }+ s.weight = weight;hit(true);}if let Some(v) = p.get("italic").and_then(Value::as_bool) {+ if s.italic != v {+ s.postscript_name = None;+ s.font_style.clear();+ }s.italic = v;hit(true);}+ if let Some(v) = p.get("postscriptName").and_then(Value::as_str) {+ s.postscript_name = Some(v.to_string());+ hit(true);+ }if let Some(v) = f32p(p, "size") {s.size_pt = v.max(0.01);hit(true);@@ -768,7 +783,7 @@ pub fn specs() -> Vec<CommandSpec> {let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());match p.get("family").and_then(Value::as_str) {Some(f) => {- let faces: Vec<Value> = eng.fonts.faces(f).into_iter().map(|x| json!({ "family": x.family, "weight": x.weight, "italic": x.italic, "axes": x.axes })).collect();+ let faces: Vec<Value> = eng.fonts.faces(f).into_iter().map(|x| json!({ "family": x.family, "style": x.style, "postscriptName": x.postscript_name, "weight": x.weight, "italic": x.italic, "axes": x.axes })).collect();Ok(json!({ "faces": faces }))}None => Ok(json!({ "families": eng.fonts.families() })),@@ -795,6 +810,21 @@ mod tests {}}+ #[test]+ fn named_face_metadata_replaces_old_postscript_identity() {+ let mut style = CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-Regular".into()), ..Default::default() };+ apply_char_props(&mut style, &json!({"fontStyle": "SemiBold"}));+ assert_eq!(style.weight, 600);+ assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold"));+ apply_char_props(&mut style, &json!({"weight": 400}));+ assert!(style.postscript_name.is_none());+ assert!(style.font_style.is_empty());+ apply_char_props(&mut style, &json!({"fontStyle": "unknown-style"}));+ assert!(style.postscript_name.is_none());+ apply_char_props(&mut style, &json!({"fontStyle": "Regular", "postscriptName": "ExplicitFace"}));+ assert_eq!(style.postscript_name.as_deref(), Some("ExplicitFace"));+ }+#[test]fn absurd_type_size_and_tracking_are_rejected_as_bad_params() {let mut s = session();diff --git a/crates/text/src/font_names_tests.rs b/crates/text/src/font_names_tests.rsnew file mode 100644index 000000000..f5104ac58--- /dev/null+++ b/crates/text/src/font_names_tests.rs@@ -0,0 +1,150 @@+//! Reproduce numeric subfamilies without redistributing proprietary fonts.+use super::*;+use photocraft_doc::text::CharStyle;++fn numeric_font(source: &[u8], style: &str, ps: &str) -> Vec<u8> {+ let mut bytes = source.to_vec();+ let count = u16::from_be_bytes(bytes[4..6].try_into().unwrap()) as usize;+ let mut name_record = 0;+ for i in 0..count {+ let r = 12 + i * 16;+ let offset = u32::from_be_bytes(bytes[r + 8..r + 12].try_into().unwrap()) as usize;+ match &bytes[r..r + 4] {+ b"name" => name_record = r,+ b"OS/2" => bytes[offset + 4..offset + 6].copy_from_slice(&400u16.to_be_bytes()),+ _ => {}+ }+ }+ let legacy = format!("Numeric Test {style}");+ let names = [(1u16, legacy.as_str()), (2, "Regular"), (6, ps), (16, "Numeric Test"), (17, style)];+ let mut table = Vec::new();+ let mut strings = Vec::new();+ for value in [0u16, names.len() as u16, (6 + names.len() * 12) as u16] {+ table.extend(value.to_be_bytes());+ }+ for (id, value) in names {+ let encoded: Vec<_> = value.encode_utf16().flat_map(u16::to_be_bytes).collect();+ for n in [3, 1, 0x409, id, encoded.len() as u16, strings.len() as u16] {+ table.extend(n.to_be_bytes());+ }+ strings.extend(encoded);+ }+ table.extend(strings);+ let offset = bytes.len() as u32;+ bytes[name_record + 8..name_record + 12].copy_from_slice(&offset.to_be_bytes());+ bytes[name_record + 12..name_record + 16].copy_from_slice(&(table.len() as u32).to_be_bytes());+ bytes.extend(table);+ bytes+}++#[test]+fn numeric_subfamilies_with_identical_weights_select_distinct_faces() {+ let mut db = FontDb::new();+ db.register_font_data(numeric_font(INTER_REGULAR, "20", "UnrelatedPS20"));+ db.register_font_data(numeric_font(INTER_SEMIBOLD, "30", "UnrelatedPS30"));+ let faces = db.faces("Numeric Test");+ assert_eq!(faces.iter().map(|f| f.style.as_str()).collect::<Vec<_>>(), ["20", "30"]);+ assert!(faces.iter().all(|f| f.weight == 400.0));+ assert_eq!(db.resolve_postscript("UnrelatedPS30").family, "Numeric Test");+ assert!(db.resolve_postscript("UnrelatedPS30").exact);+ let mut a = CharStyle { font_family: "Numeric Test".into(), font_style: "20".into(), ..Default::default() };+ let mut b = CharStyle { font_style: "30".into(), ..a.clone() };+ db.select_named_face(&mut a);+ db.select_named_face(&mut b);+ assert_ne!(a.font_family, b.font_family);+ assert_eq!(db.faces(&a.font_family)[0].postscript_name.as_deref(), Some("UnrelatedPS20"));+ assert_eq!(db.faces(&b.font_family)[0].postscript_name.as_deref(), Some("UnrelatedPS30"));+ assert!(!db.families().iter().any(|f| f.starts_with(".PhotoCraft-face-")));+ let alias = b.font_family.clone();+ b.font_family = "Numeric Test".into();+ db.select_named_face(&mut b);+ assert_eq!(b.font_family, alias);+}++#[test]+fn numeric_styles_shape_different_outlines_and_keep_psd_identity() {+ use photocraft_doc::{TextLayer, text::TextRun};+ let mut engine = crate::TextEngine::new();+ engine.fonts.register_font_data(numeric_font(INTER_REGULAR, "20", "UnrelatedPS20"));+ engine.fonts.register_font_data(numeric_font(INTER_SEMIBOLD, "30", "UnrelatedPS30"));+ let layer = |style: &str| TextLayer {+ text: "Hamburgefonstiv".into(),+ runs: vec![TextRun {+ len: 14,+ style: CharStyle {+ font_family: "Numeric Test".into(),+ font_style: style.into(),+ size_pt: 32.0,+ postscript_name: Some(format!("UnrelatedPS{style}")),+ ..Default::default()+ },+ }],+ ..Default::default()+ };+ let a = engine.layout(&layer("20"), 72.0);+ let b = engine.layout(&layer("30"), 72.0);+ assert_ne!(a.lines[0].x1, b.lines[0].x1);+ let original = layer("30");+ let bytes = crate::psd::build_tysh(&original, 72.0, None);+ let reopened = crate::psd::text_layer_from_tysh(&bytes, 72.0).unwrap();+ assert_eq!(reopened.char_runs()[0].style.postscript_name.as_deref(), Some("UnrelatedPS30"));+ let c = engine.layout(&reopened, 72.0);+ assert!((b.lines[0].x1 - c.lines[0].x1).abs() < 0.01);+}++#[test]+fn explicit_weight_is_not_overridden_by_a_stale_style_name() {+ let mut db = FontDb::new();+ let mut style = CharStyle { font_family: "Inter".into(), font_style: "Regular".into(), weight: 600, ..Default::default() };+ db.select_named_face(&mut style);+ assert_eq!(style.font_family, "Inter");+ assert_eq!(style.weight, 600);+ assert!(db.named_face("Inter", "Medium").is_some());+ assert!(db.named_face("missing", "20").is_none());+ assert!(isolated_face(Blob::new(Arc::new(vec![0; 16])), 0).is_none());+}++#[test]+fn collection_isolation_preserves_requested_face() {+ // Two faces with identical attributes: the second must not fall back to the first.+ let sources = [numeric_font(INTER_REGULAR, "20", "Collection20"), numeric_font(INTER_SEMIBOLD, "30", "Collection30")];+ let mut bytes = b"ttcf\0\x01\0\0\0\0\0\x02".to_vec();+ bytes.extend(20u32.to_be_bytes());+ bytes.extend((20 + sources[0].len() as u32).to_be_bytes());+ for source in sources {+ let start = bytes.len();+ bytes.extend(source);+ let count = u16::from_be_bytes(bytes[start + 4..start + 6].try_into().unwrap()) as usize;+ for i in 0..count {+ let r = start + 12 + i * 16 + 8;+ let offset = u32::from_be_bytes(bytes[r..r + 4].try_into().unwrap()) + start as u32;+ bytes[r..r + 4].copy_from_slice(&offset.to_be_bytes());+ }+ }+ let blob = Blob::new(Arc::new(bytes));+ assert!(isolated_face(blob.clone(), 2).is_none());+ let mut db = FontDb::new();+ db.register_blob(blob.clone());+ let mut style = CharStyle { font_family: "Numeric Test".into(), font_style: "30".into(), ..Default::default() };+ db.select_named_face(&mut style);+ assert_eq!(db.faces(&style.font_family)[0].postscript_name.as_deref(), Some("Collection30"));+ let isolated = isolated_face(blob, 1).unwrap();+ let font = skrifa::FontRef::from_index(isolated.as_ref(), 0).unwrap();+ assert_eq!(font.localized_strings(StringId::POSTSCRIPT_NAME).english_or_first().unwrap().to_string(), "Collection30");+}++#[test]+#[ignore = "requires locally installed Yoon 500 fonts; no font files are distributed"]+fn installed_yoon_numeric_faces() {+ let mut db = FontDb::with_system_fonts();+ for family in ["Yoon YoonGothic500", "Yoon YoonMyungjo500"] {+ let faces = db.faces(family);+ for name in ["20", "30", "40", "50"] {+ let face = faces.iter().find(|f| f.style == name).expect("installed numeric face");+ let mut style =+ CharStyle { font_family: family.into(), font_style: name.into(), postscript_name: face.postscript_name.clone(), ..Default::default() };+ db.select_named_face(&mut style);+ assert_eq!(db.faces(&style.font_family)[0].postscript_name, face.postscript_name);+ }+ }+}diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rsindex a2e400fcb..c11fe8026 100644--- a/crates/text/src/fonts.rs+++ b/crates/text/src/fonts.rs@@ -8,7 +8,7 @@ use std::sync::Arc;use std::sync::atomic::{AtomicU64, Ordering};use parley::FontContext;-use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle, FontWeight, FontWidth, GenericFamily, SourceCache};+use parley::fontique::{Blob, Collection, CollectionOptions, FontInfoOverride, FontStyle, FontWeight, FontWidth, GenericFamily, SourceCache};use skrifa::raw::{FileRef, TableProvider, types::Tag};use skrifa::{MetadataProvider, string::StringId};@@ -68,6 +68,10 @@ pub fn generation() -> u64 {#[derive(Clone, Debug, PartialEq)]pub struct FaceInfo {pub family: String,+ /// OpenType typographic subfamily (name 17), or legacy subfamily (name 2).+ pub style: String,+ /// Stable face identity, including faces that share the same CSS attributes.+ pub postscript_name: Option<String>,/// CSS weight (100–900); variable fonts report their default.pub weight: f32,pub italic: bool,@@ -91,6 +95,8 @@ pub struct FontDb {/// PostScript name → (family, weight, italic), filled lazily.ps_cache: HashMap<String, Option<ResolvedFont>>,fallbacks: Vec<String>,+ face_cache: HashMap<String, Vec<FaceInfo>>,+ face_aliases: HashMap<(String, usize), String>,}impl Default for FontDb {@@ -108,6 +114,8 @@ impl FontDb {system_loaded: false,ps_cache: HashMap::new(),fallbacks: Vec::new(),+ face_cache: HashMap::new(),+ face_aliases: HashMap::new(),};for (_, bytes) in BUNDLED {db.register_font_data(bytes.to_vec());@@ -150,6 +158,7 @@ impl FontDb {self.fcx.collection.load_fonts_from_paths([f]);}self.ps_cache.clear();+ self.face_cache.clear();self.refresh_generics();}}@@ -179,6 +188,7 @@ impl FontDb {// metrics differ from the public family's.names.sort_by_key(|n| (is_hidden_family(n), n.to_lowercase()));self.ps_cache.clear();+ self.face_cache.clear();self.refresh_generics();GENERATION.fetch_add(1, Ordering::Relaxed);names@@ -247,20 +257,75 @@ impl FontDb {.is_some_and(|features| features.feature_records().iter().any(|record| record.feature_tag() == feature))}- /// Faces of a family (weights, italics, variation axes).+ /// Faces of a family, preserving names even when multiple faces share CSS attributes.pub fn faces(&mut self, family: &str) -> Vec<FaceInfo> {+ if let Some(faces) = self.face_cache.get(family) {+ return faces.clone();+ }let Some(info) = self.fcx.collection.family_by_name(family) else {return Vec::new();};- info.fonts()+ let faces: Vec<_> = info+ .fonts().iter()- .map(|f| FaceInfo {- family: info.name().to_string(),- weight: f.weight().value(),- italic: !matches!(f.style(), FontStyle::Normal),- axes: f.axes().iter().map(|a| (a.tag.to_string(), a.min, a.default, a.max)).collect(),+ .map(|f| {+ let blob = f.load(Some(&mut self.fcx.source_cache));+ let font = blob.as_ref().and_then(|b| skrifa::FontRef::from_index(b.as_ref(), f.index()).ok());+ let name = |id| font.as_ref().and_then(|f| f.localized_strings(id).english_or_first()).map(|s| s.to_string()).filter(|s| !s.is_empty());+ let italic = !matches!(f.style(), FontStyle::Normal);+ FaceInfo {+ family: info.name().to_string(),+ style: name(StringId::TYPOGRAPHIC_SUBFAMILY_NAME)+ .or_else(|| name(StringId::SUBFAMILY_NAME))+ .unwrap_or_else(|| fallback_style(f.weight().value(), italic)),+ postscript_name: name(StringId::POSTSCRIPT_NAME),+ weight: f.weight().value(),+ italic,+ axes: f.axes().iter().map(|a| (a.tag.to_string(), a.min, a.default, a.max)).collect(),+ }+ })+ .collect();+ self.face_cache.insert(family.to_string(), faces.clone());+ faces+ }++ /// Resolve a menu style to its actual metadata instead of guessing from its spelling.+ pub fn named_face(&mut self, family: &str, style: &str) -> Option<FaceInfo> {+ self.faces(family).into_iter().find(|f| f.style.eq_ignore_ascii_case(style))+ }++ /// Select an exact face for shaping. Private aliases are runtime-only: the document keeps+ /// its public family and PostScript name. CSS matching alone cannot distinguish e.g. the+ /// numeric subfamilies of Yoon fonts, all of which declare weight 400 / normal.+ 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))).or_else(|| {+ faces.iter().position(|f| {+ !style.font_style.is_empty()+ && f.style.eq_ignore_ascii_case(&style.font_style)+ && f.weight.round() as u16 == style.weight+ && f.italic == style.italic})- .collect()+ });+ let Some(index) = index else { return };+ let Some(face) = faces.get(index) else { return };+ let key = (family.clone(), index);+ let alias = if let Some(alias) = self.face_aliases.get(&key) {+ alias.clone()+ } else {+ let Some(info) = self.fcx.collection.family_by_name(&family) else { return };+ let Some(font) = info.fonts().get(index) else { return };+ let Some(blob) = font.load(Some(&mut self.fcx.source_cache)) else { return };+ let Some(blob) = isolated_face(blob, font.index()) else { return };+ let alias = format!(".PhotoCraft-face-{}-{index}", info.id().to_u64());+ self.fcx.collection.register_fonts(blob, Some(FontInfoOverride { family_name: Some(&alias), ..Default::default() }));+ self.face_aliases.insert(key, alias.clone());+ alias+ };+ style.font_family = alias;+ style.weight = face.weight.round() as u16;+ style.italic = face.italic;}/// Finds a face by PostScript name (as stored in PSD files): exact match by reading the@@ -287,26 +352,15 @@ impl FontDb {fn find_exact(&mut self, ps: &str, family_guess: &str) -> Option<ResolvedFont> {let first_word = family_guess.split(' ').next().unwrap_or(family_guess).to_lowercase();- let candidates: Vec<String> = self.families().into_iter().filter(|f| f.to_lowercase().replace(' ', "").starts_with(&first_word)).collect();+ let mut candidates = self.families();+ candidates.sort_by_key(|f| !f.to_lowercase().replace(' ', "").starts_with(&first_word));for fam in candidates {- let Some(info) = self.fcx.collection.family_by_name(&fam) else {- continue;- };- for font in info.fonts() {- let Some(blob) = font.load(Some(&mut self.fcx.source_cache)) else {- continue;- };- let Ok(fr) = skrifa::FontRef::from_index(blob.as_ref(), font.index()) else {- continue;- };- let name = fr.localized_strings(StringId::POSTSCRIPT_NAME).english_or_first().map(|s| s.to_string());- if name.as_deref() == Some(ps) {- return Some(ResolvedFont {- family: info.name().to_string(),- weight: font.weight().value().round() as u16,- italic: !matches!(font.style(), FontStyle::Normal),- exact: true,- });+ for face in self.faces(&fam) {+ let Some(name) = face.postscript_name else { continue };+ let resolved = ResolvedFont { family: face.family, weight: face.weight.round() as u16, italic: face.italic, exact: true };+ self.ps_cache.insert(name.clone(), Some(resolved.clone()));+ if name == ps {+ return Some(resolved);}}}@@ -314,6 +368,46 @@ impl FontDb {}}+/// Make a collection expose only the requested face without rewriting any font tables.+/// TTC table offsets are absolute; changing its face directory preserves them verbatim.+fn isolated_face(blob: Blob<u8>, index: u32) -> Option<Blob<u8>> {+ match FileRef::new(blob.as_ref()).ok()? {+ FileRef::Font(_) => (index == 0).then_some(blob),+ FileRef::Collection(collection) => {+ collection.get(index).ok()?;+ // Bound a copy of untrusted font data. Ordinary single-face fonts need no copy.+ if blob.as_ref().len() > 256 * 1024 * 1024 {+ return None;+ }+ let offset = 12usize.checked_add(usize::try_from(index).ok()?.checked_mul(4)?)?;+ let face_offset: [u8; 4] = blob.as_ref().get(offset..offset.checked_add(4)?)?.try_into().ok()?;+ let mut bytes = blob.as_ref().to_vec();+ bytes.get_mut(8..12)?.copy_from_slice(&1u32.to_be_bytes());+ bytes.get_mut(12..16)?.copy_from_slice(&face_offset);+ Some(Blob::new(Arc::new(bytes)))+ }+ }+}++fn fallback_style(weight: f32, italic: bool) -> String {+ let name = match weight.round() as i32 {+ ..=150 => "Thin",+ 151..=250 => "ExtraLight",+ 251..=350 => "Light",+ 351..=450 => "Regular",+ 451..=550 => "Medium",+ 551..=650 => "SemiBold",+ 651..=750 => "Bold",+ 751..=850 => "ExtraBold",+ _ => "Black",+ };+ match (name, italic) {+ ("Regular", true) => "Italic".into(),+ (_, true) => format!("{name} Italic"),+ (_, false) => name.into(),+ }+}+/// Number of faces in a font file (1 for TTF/OTF, n for TTC/OTC, 0 if unreadable).pub fn face_count(bytes: &[u8]) -> usize {match FileRef::new(bytes) {@@ -483,3 +577,7 @@ mod tests {assert!(files.is_empty());}}++#[cfg(test)]+#[path = "font_names_tests.rs"]+mod font_names_tests;diff --git a/crates/text/src/glyphs.rs b/crates/text/src/glyphs.rsindex 26c55ce44..77e97db6b 100644--- a/crates/text/src/glyphs.rs+++ b/crates/text/src/glyphs.rs@@ -67,6 +67,13 @@ pub fn in_category(c: char, category: &str) -> bool {}impl FontDb {+ /// Character coverage of the exact named face used by the type tool.+ pub fn charmap_for_style(&mut self, style: &CharStyle) -> Vec<char> {+ let mut style = style.clone();+ self.select_named_face(&mut style);+ self.charmap(&style.font_family, style.weight, style.italic)+ }+/// Characters mapped by the face of `family` nearest to `weight`/`italic`, ascending/// (controls and whitespace other than the space excluded). Empty for an unknown family.pub fn charmap(&mut self, family: &str, weight: u16, italic: bool) -> Vec<char> {diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rsindex d32dfc089..01b999d8c 100644--- a/crates/text/src/layout.rs+++ b/crates/text/src/layout.rs@@ -418,7 +418,9 @@ impl Layouter {// Resolve families (PostScript names from PSDs, unknown families).for r in &runs {let mut s = r.style.clone();- if let Some(ps) = s.postscript_name.clone() {+ if let Some(ps) = s.postscript_name.clone()+ && !fonts.faces(&s.font_family).iter().any(|f| f.postscript_name.as_deref() == Some(&ps))+ {let f = fonts.resolve_postscript(&ps);// An exact face match wins; a guessed family only fills a missing family.if f.exact || (!fonts.has_family(&s.font_family) && fonts.has_family(&f.family)) {@@ -431,6 +433,7 @@ impl Layouter {if !fonts.has_family(&s.font_family) {crate::served::request(&s.font_family);}+ fonts.select_named_face(&mut s);out.styles.push(s);}let run_starts: Vec<usize> = runsdiff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/type_panels_ui.rsindex 01fa36324..87d4263f6 100644--- a/crates/ui-egui/src/type_panels_ui.rs+++ b/crates/ui-egui/src/type_panels_ui.rs@@ -533,8 +533,7 @@ fn glyph_font(app: &PhotocraftApp) -> (String, String) {&& let Some(r) = tl.char_runs().first(){let fam = if r.style.font_family.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { r.style.font_family.clone() };- let style =- if r.style.font_style.is_empty() { if r.style.italic { tl!("Italic").into() } else { tl!("Regular").into() } } else { r.style.font_style.clone() };+ let style = crate::type_tool::selected_style(&r.style);return (fam, style);}(photocraft_text::fonts::DEFAULT_FAMILY.into(), tl!("Regular").into())@@ -569,7 +568,7 @@ fn charmap(ctx: &egui::Context, family: &str, style: &str) -> std::sync::Arc<Vecreturn v;}let st = char_style_for(family, style);- let v = std::sync::Arc::new(photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.charmap(family, st.weight, st.italic));+ let v = std::sync::Arc::new(photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.charmap_for_style(&st));ctx.data_mut(|d| d.insert_temp(id, v.clone()));v}diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rsindex e01711ea4..784ba7f1a 100644--- a/crates/ui-egui/src/type_tool.rs+++ b/crates/ui-egui/src/type_tool.rs@@ -714,11 +714,12 @@ fn weight_name(w: f32) -> &'static str {}}-/// Style names ("Regular", "Bold Italic", …) available for a family.+/// Style names available for a family: each face's actual OpenType subfamily (including numeric+/// and nonstandard ones), plus the standard weights a variable face's `wght` axis covers.pub fn styles(family: &str) -> Vec<String> {- let faces = photocraft_text::shared().lock().map(|mut e| e.fonts.faces(family)).unwrap_or_default();+ let faces = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(family);let v = style_names(&faces);- if v.is_empty() { vec![tl!("Regular").into()] } else { v }+ if v.is_empty() { vec!["Regular".into()] } else { v }}/// [`styles`] of these faces, lightest first. A variable face reports only its default instance@@ -733,15 +734,31 @@ fn style_names(faces: &[photocraft_text::FaceInfo]) -> Vec<String> {};(weight.round() as i32, italic, name)};- let mut v: Vec<(i32, bool, String)> = faces.iter().map(|f| label(f.weight, f.italic)).collect();+ let mut v: Vec<(i32, bool, String)> = faces.iter().map(|f| (f.weight.round() as i32, f.italic, f.style.clone())).collect();for f in faces {if let Some((_, min, _, max)) = f.axes.iter().find(|a| a.0 == "wght") {v.extend((100..=900).step_by(100).map(|w| w as f32).filter(|w| (*min..=*max).contains(w)).map(|w| label(w, f.italic)));}}v.sort();- v.dedup_by(|a, b| a.2 == b.2);- v.into_iter().map(|x| x.2).collect()+ let mut names: Vec<String> = Vec::new();+ for (_, _, name) in v {+ if !names.contains(&name) {+ names.push(name);+ }+ }+ names+}++/// PSD text can identify a face only by its PostScript name. Show its real subfamily too.+pub(crate) fn selected_style(style: &photocraft_doc::text::CharStyle) -> String {+ if let Some(ps) = &style.postscript_name {+ let faces = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(&style.font_family);+ if let Some(face) = faces.into_iter().find(|f| f.postscript_name.as_ref() == Some(ps)) {+ return face.style;+ }+ }+ if style.font_style.is_empty() { if style.italic { "Italic".into() } else { "Regular".into() } } else { style.font_style.clone() }}/// Localized style label for the dropdown. The raw string stays the engine's `fontStyle` key;@@ -895,7 +912,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let run = tl.char_runs().into_iter().next().map(|r| r.style);// The size at the selection (else the first run), as the layer shows it (#124).let size = styles_at(app).map_or(tl.size_pt, |(c, _)| c.size_pt) * shown_scale(app);- Some((tl.font_family.clone(), run.as_ref().map(|s| s.font_style.clone()).unwrap_or_default(), size, styles_at(app).map_or(tl.color, |(c, _)| c.color)))+ Some((tl.font_family.clone(), run.as_ref().map(selected_style).unwrap_or_default(), size, styles_at(app).map_or(tl.color, |(c, _)| c.color)))});let o = app.ui.tool_options.clone();let (mut fam, mut style, mut size) = match &shown {@@ -1221,7 +1238,7 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa}});row(ui, &mut |ui| {- let mut style = if c.font_style.is_empty() { "Regular".to_string() } else { c.font_style.clone() };+ let mut style = selected_style(&c);let opts: Vec<(String, String)> = styles(&fam).into_iter().map(|s| (s.clone(), style_label(&s))).collect();let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect();if crate::widgets::dropdown(ui, "props-type-style", &mut style, &opts_ref, full) {diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rsindex 5fc1e1684..1405a6854 100644--- a/crates/ui-egui/src/type_tool_tests.rs+++ b/crates/ui-egui/src/type_tool_tests.rs@@ -1125,11 +1125,35 @@ fn temporary_type_transform_large_document_preview() {crate::type_transform::cancel_drag(&mut app);}+#[test]+fn font_styles_keep_metadata_names_and_numeric_labels() {+ let styles = super::styles("Inter");+ assert!(styles.contains(&"Regular".into()));+ assert!(styles.contains(&"SemiBold".into()));+ assert_eq!(super::style_label("20"), "20");+ assert_eq!(super::style_label("30"), "30");+ assert_eq!(super::styles("Missing test family"), ["Regular"]);+}++#[test]+fn postscript_only_style_shows_actual_subfamily() {+ let style = photocraft_doc::text::CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-SemiBold".into()), ..Default::default() };+ assert_eq!(super::selected_style(&style), "SemiBold");+}+/// A variable face lists every standard weight of its `wght` axis, not only its default instance/// (Montserrat from Google Fonts: its default instance is Thin).#[test]fn variable_faces_list_the_weights_of_their_axis() {- let face = |weight: f32, italic: bool, axes: Vec<(String, f32, f32, f32)>| photocraft_text::FaceInfo { family: "Montserrat".into(), weight, italic, axes };+ let face = |weight: f32, italic: bool, axes: Vec<(String, f32, f32, f32)>| {+ let base = match weight as i32 {+ 100 => "Thin",+ 300 => "Light",+ _ => "Bold",+ };+ let style = if italic { format!("{base} Italic") } else { base.to_string() };+ photocraft_text::FaceInfo { family: "Montserrat".into(), style, postscript_name: None, weight, italic, axes }+ };let full = || vec![("wght".to_string(), 100.0, 100.0, 900.0)];let names = super::style_names(&[face(100.0, false, full()), face(100.0, true, full())]);assert_eq!(names.len(), 18, "{names:?}");