PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix small caps rendering across fonts (#1644)
McClabec58d20bd39f4
diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rsindex 3154790a1..3a883eee3 100644--- a/crates/text/src/fonts.rs+++ b/crates/text/src/fonts.rs@@ -7,8 +7,8 @@ use std::collections::HashMap;use std::sync::Arc;use parley::FontContext;-use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle, GenericFamily, SourceCache};-use skrifa::raw::FileRef;+use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle, FontWeight, FontWidth, GenericFamily, SourceCache};+use skrifa::raw::{FileRef, TableProvider, types::Tag};use skrifa::{MetadataProvider, string::StringId};/// Family used when a style names no family or an unknown one.@@ -210,6 +210,31 @@ impl FontDb {self.fcx.collection.family_id(name).is_some()}+ /// Whether the face selected for a character style exposes an OpenType GSUB feature.+ ///+ /// This deliberately checks the matched face, rather than every face in the family: a+ /// regular face can lack a feature that its italic or bold sibling has (or vice versa).+ pub(crate) fn selected_face_has_feature(&mut self, family: &str, weight: u16, italic: bool, feature: Tag) -> bool {+ let family = if family.is_empty() || !self.has_family(family) { DEFAULT_FAMILY } else { family };+ let Some(info) = self.fcx.collection.family_by_name(family) else {+ return false;+ };+ let style = if italic { FontStyle::Italic } else { FontStyle::Normal };+ let Some(font) = info.match_font(FontWidth::default(), style, FontWeight::new(weight.clamp(1, 1000) as f32), true) else {+ return false;+ };+ let Some(blob) = font.load(Some(&mut self.fcx.source_cache)) else {+ return false;+ };+ let Ok(font) = skrifa::FontRef::from_index(blob.as_ref(), font.index()) else {+ return false;+ };+ font.gsub()+ .ok()+ .and_then(|gsub| gsub.feature_list().ok())+ .is_some_and(|features| features.feature_records().iter().any(|record| record.feature_tag() == feature))+ }+/// Faces of a family (weights, italics, variation axes).pub fn faces(&mut self, family: &str) -> Vec<FaceInfo> {let Some(info) = self.fcx.collection.family_by_name(family) else {diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rsindex 8046a1331..d198f275f 100644--- a/crates/text/src/layout.rs+++ b/crates/text/src/layout.rs@@ -23,9 +23,30 @@ use parley::{};use photocraft_doc::TextLayer;use photocraft_doc::text::{Caps, CharStyle, Kerning, Orientation, TextAlign, TextDirection, TextShape};+use skrifa::raw::types::Tag;use crate::fonts::FontDb;+/// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same+/// readable hierarchy for every font instead of silently rendering lowercase text unchanged.+const SYNTHETIC_SMALL_CAPS_SCALE: f32 = 0.7;++/// The rendering path for a `SmallCaps` character style.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum SmallCapsMode {+ None,+ OpenType,+ Synthetic,+}++fn small_caps_mode(caps: Caps, face_has_smcp: bool) -> SmallCapsMode {+ match caps {+ Caps::SmallCaps if face_has_smcp => SmallCapsMode::OpenType,+ Caps::SmallCaps => SmallCapsMode::Synthetic,+ _ => SmallCapsMode::None,+ }+}+/// Index of the character run whose style a glyph uses, plus the vertical-type class of its/// characters ([`VClass`] as `u8`; always 0 in horizontal type).#[derive(Clone, Copy, Debug, Default, PartialEq)]@@ -449,6 +470,17 @@ impl Layouter {};let mut ptext = String::with_capacity(prefix.len() + content.len());ptext.push_str(prefix);+ // A real `smcp` substitution must receive lowercase source text; only the fallback+ // path uppercases it and scales it down.+ let small_caps: Vec<SmallCapsMode> = out+ .styles+ .iter()+ .map(|style| small_caps_mode(style.caps, fonts.selected_face_has_feature(&style.font_family, style.weight, style.italic, Tag::new(b"smcp"))))+ .collect();+ // Ranges in `ptext` for lowercase characters rendered as synthetic small caps.+ // They have the same UTF-8 length as their uppercase form, so the layer's byte-based+ // run and caret offsets remain unchanged.+ let mut synthetic_small_caps: Vec<(Range<usize>, f32)> = Vec::new();for (i, ch) in content.char_indices() {// A forced line break ends the line but not the paragraph. The line breaker knows// it as a newline, which has the same length, so text offsets don't move.@@ -456,11 +488,16 @@ impl Layouter {ptext.push('\n');continue;}- let caps = out.styles[style_at(prange.start + i)].caps;- if caps == Caps::AllCaps {+ let style = &out.styles[style_at(prange.start + i)];+ let caps = style.caps;+ if caps == Caps::AllCaps || small_caps[style_at(prange.start + i)] == SmallCapsMode::Synthetic {let up: String = ch.to_uppercase().collect();if up.len() == ch.len_utf8() {ptext.push_str(&up);+ if caps == Caps::SmallCaps && ch.is_lowercase() {+ let end = ptext.len();+ synthetic_small_caps.push((end - up.len()..end, style.size_pt * k * SYNTHETIC_SMALL_CAPS_SCALE));+ }continue;}}@@ -474,7 +511,7 @@ impl Layouter {// Paragraph-start style as the default (covers the direction mark and empty// paragraphs), then every run piece intersecting this paragraph.let si0 = style_at(prange.start);- for p in style_props(&out.styles[si0], k, &fallback, si0 as u32) {+ for p in style_props(&out.styles[si0], k, &fallback, si0 as u32, small_caps[si0]) {b.push_default(p);}for (ri, st) in out.styles.iter().enumerate() {@@ -484,7 +521,7 @@ impl Layouter {continue;}let range = (a - prange.start + prefix.len())..(z - prange.start + prefix.len());- for p in style_props(st, k, &fallback, ri as u32) {+ for p in style_props(st, k, &fallback, ri as u32, small_caps[ri]) {b.push(p, range.clone());}if vertical {@@ -495,7 +532,7 @@ impl Layouter {if cls == VClass::Rotate || from >= to {return;}- let mut feats = feature_list(st);+ let mut feats = feature_list(st, small_caps[ri]);feats.push("\"vert\" 1".into());let r = (range.start + from)..(range.start + to);b.push(StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), r.clone());@@ -517,6 +554,9 @@ impl Layouter {}}}+ for (range, size) in synthetic_small_caps {+ b.push(StyleProperty::FontSize(size), range);+ }b.build(&ptext)};let indent_start = ps.start_indent_pt * k;@@ -1014,7 +1054,7 @@ impl skrifa::outline::OutlinePen for YMax {}/// OpenType feature settings of a character style (CSS `font-feature-settings` items).-fn feature_list(st: &CharStyle) -> Vec<String> {+fn feature_list(st: &CharStyle, small_caps: SmallCapsMode) -> Vec<String> {let mut feats: Vec<String> = Vec::new();// Optical and manual kerning replace the font's kerning table; a character with a manual// kern is manually kerned whatever its mode (as in Photoshop).@@ -1028,7 +1068,7 @@ fn feature_list(st: &CharStyle) -> Vec<String> {if st.discretionary_ligatures {feats.push("\"dlig\" 1".into());}- if st.caps == Caps::SmallCaps {+ if small_caps == SmallCapsMode::OpenType {feats.push("\"smcp\" 1".into());}for f in &st.features {@@ -1039,7 +1079,7 @@ fn feature_list(st: &CharStyle) -> Vec<String> {feats}-fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32) -> Vec<StyleProperty<'static, RunBrush>> {+fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32, small_caps: SmallCapsMode) -> Vec<StyleProperty<'static, RunBrush>> {let px = (st.size_pt * k).max(0.01);let mut fam: Vec<String> = Vec::new();if !st.font_family.is_empty() {@@ -1052,7 +1092,7 @@ fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32) -> Vec<Styfam.extend(fallback.iter().map(|f| quote(f)));}fam.push("sans-serif".into());- let feats = feature_list(st);+ let feats = feature_list(st, small_caps);let vars: Vec<String> = st.variations.iter().filter(|v| v.axis.len() == 4 && v.axis.is_ascii()).map(|v| format!("\"{}\" {}", v.axis, v.value)).collect();vec![StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))),@@ -1154,3 +1194,21 @@ fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option<f32> {}best}++#[cfg(test)]+mod tests {+ use super::{SmallCapsMode, feature_list, small_caps_mode};+ use photocraft_doc::text::{Caps, CharStyle};++ #[test]+ fn uses_real_small_caps_only_when_the_selected_face_supports_smcp() {+ let style = CharStyle { caps: Caps::SmallCaps, ..Default::default() };+ let real = small_caps_mode(style.caps, true);+ let synthetic = small_caps_mode(style.caps, false);++ assert_eq!(real, SmallCapsMode::OpenType);+ assert!(feature_list(&style, real).iter().any(|feature| feature == "\"smcp\" 1"));+ assert_eq!(synthetic, SmallCapsMode::Synthetic);+ assert!(!feature_list(&style, synthetic).iter().any(|feature| feature == "\"smcp\" 1"));+ }+}diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 9242830f7..e1b23efee 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -1,6 +1,6 @@use photocraft_color::{Color, PixelFormat, SampleType};use photocraft_doc::TextLayer;-use photocraft_doc::text::{CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape};+use photocraft_doc::text::{Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape};use photocraft_geom::Affine;use crate::{TextEngine, fonts};@@ -55,6 +55,20 @@ fn metrics_are_stable_and_scale_with_dpi() {assert!(a.lines[0].ascent > 8.0 && a.lines[0].ascent < 13.0);}+#[test]+fn small_caps_are_synthesized_when_the_font_has_no_small_caps_feature() {+ let style = CharStyle { font_family: "Inter".into(), size_pt: 40.0, caps: Caps::SmallCaps, ..Default::default() };+ let mut engine = TextEngine::new();+ let small = engine.layout(&styled("aA", style), 72.0);+ let upper = engine.layout(&styled("AA", CharStyle { font_family: "Inter".into(), size_pt: 40.0, ..Default::default() }), 72.0);+ assert_eq!(small.glyphs.len(), 2);+ assert_eq!(small.glyphs[0].id, upper.glyphs[0].id, "lowercase uses the uppercase glyph");+ assert_eq!(small.glyphs[1].id, upper.glyphs[1].id, "uppercase remains uppercase");+ let size = |layout: &crate::TextLayout, glyph: usize| layout.faces[layout.glyphs[glyph].face as usize].size_px;+ assert!((size(&small, 0) - 28.0).abs() < 0.01, "{}", size(&small, 0));+ assert!((size(&small, 1) - 40.0).abs() < 0.01, "{}", size(&small, 1));+}+#[test]fn auto_and_explicit_leading() {let mut e = TextEngine::new();