public inbox for git-commits@fedoraproject.org
help / color / mirror / Atom feed
From: Akira TAGOH <tagoh@redhat.com>
To: git-commits@fedoraproject.org
Subject: [rpms/fontconfig] f45: Fix monospace detection
Date: Wed, 18 Nov 2026 13:23:38 GMT	[thread overview]
Message-ID: <179500821883.1.3524655353302441461.rpms-fontconfig-5d0ba8c986c2@fedoraproject.org> (raw)

            A new commit has been pushed.

            Repo   : rpms/fontconfig
            Branch : f45
            Commit : 5d0ba8c986c2813cde0a2c6552b15ef859fd9717
            Author : Akira TAGOH <tagoh@redhat.com>
            Date   : 2026-10-09T22:49:57+09:00
            Stats  : +937/-0 in 2 file(s)
            URL    : https://src.fedoraproject.org/rpms/fontconfig/c/5d0ba8c986c2813cde0a2c6552b15ef859fd9717?branch=f45

            Log:
            Fix monospace detection

- Resolves: rhbz#2548466

---
diff --git a/fontconfig-fix-mono-detection.patch b/fontconfig-fix-mono-detection.patch
new file mode 100644
index 0000000..b1f0783
--- /dev/null
+++ b/fontconfig-fix-mono-detection.patch
@@ -0,0 +1,935 @@
+From 4bbe98115afa53d99b2c0266c985491118506d21 Mon Sep 17 00:00:00 2001
+From: Akira TAGOH <akira@tagoh.org>
+Date: Fri, 9 Oct 2026 22:25:04 +0900
+Subject: [PATCH] Detect monospace grid fonts the advance heuristic missed
+
+FcFreeTypeSpacing() keyed off the first three distinct advances, so a
+monospace font with a few intentionally wide glyphs (2x em dash, 3x
+two-em dash) was reported PROPORTIONAL -- e.g. Noto Sans Mono and Latin
+Modern Mono.
+
+When the existing rule yields proportional, additionally try to recover
+fonts whose advances sit on an integer cell grid (>= 98%).  Recovery is
+gated on monospaced ASCII, which keeps uniform full-width scripts and
+emoji from being promoted, and stays name-independent.
+
+Fold the advance tally into FcFreeTypeCharSet()'s glyph loop for scalable
+fonts to avoid a second cmap pass.  Update the Fontations backend in
+lockstep so both fc-query outputs stay identical, and add test-spacing.c
+plus matching Rust cases.
+
+Assisted-By: Claude Opus 4.8 <noreply@anthropic.com>
+Changelog: fixed
+---
+ fc-fontations/attributes.rs | 301 ++++++++++++++++++++++++++---------
+ src/fcfreetype.c            | 306 ++++++++++++++++++++++++++++++------
+ src/fcint.h                 |   9 ++
+ test/meson.build            |   1 +
+ test/test-spacing.c         | 120 ++++++++++++++
+ 5 files changed, 612 insertions(+), 125 deletions(-)
+ create mode 100644 test/test-spacing.c
+
+diff --git a/fc-fontations/attributes.rs b/fc-fontations/attributes.rs
+index ef49c15a..1d172998 100644
+--- a/fc-fontations/attributes.rs
++++ b/fc-fontations/attributes.rs
+@@ -292,53 +292,145 @@ impl<'a> AttributesToPattern<'a> {
+     }
+ 
+     // Determine FontConfig spacing property.
+-    // In fcfreetype.c FcFreeTypeSpacing a heuristic checks whether the glyphs
+-    //  for a bitmap font are "approximately equal".
+-    // For this purpose, fcfreetype.c selects the strike size closest to 16 px,
+-    // then iterates over available glyphs and checks whether the advance width
+-    // is within a relative tolerance of 1/33.
+-    // We'll do this based on skrifa advances here - if needed, this can be
+-    // moved to selecting a particular bitmap strike size and compare pixel
+-    // widths.
+-    fn spacing_from_advances(advances: impl Iterator<Item = f32>) -> Option<i32> {
+-        let mut encountered_advances = Vec::new();
++    //
++    // This mirrors FcSpacingClassify() in src/fcfreetype.c -- the two must stay
++    // in sync so the FreeType and Fontations backends agree (enforced by
++    // test_fontations_ft_query.py).  It runs in two stages:
++    //   1. reproduce the legacy rule (single width -> MONO; two widths in a 2:1
++    //      ratio -> DUAL), so nothing that already had a spacing is reclassified;
++    //   2. only when the legacy rule yields proportional, recover a grid font --
++    //      one whose nonzero advances are integer multiples k*W of a base cell W
++    //      -- but only if the font monospaces its ASCII letters.  That gate is
++    //      what keeps uniform full-width scripts, emoji and symbol fonts (grid
++    //      conformant but not monospaced Latin) from being promoted.
++    //
++    // Takes (codepoint, advance) pairs.  Returns None for proportional fonts (no
++    // FC_SPACING element is emitted).
++    fn spacing_from_advances(advances: impl Iterator<Item = (u32, f32)>) -> Option<i32> {
++        const MAX_CLUSTERS: usize = 64; // real grid fonts have only a few distinct advances
++        const GRID_PERCENT: i64 = 98; // min % of advances that must sit on the cell grid
++        const SIGNIFICANT: i64 = 20; // a base-cell candidate holds >= total/20 (5%)
++        const MIN_ASCII: i64 = 20; // min ASCII letters/digits needed to judge Latin spacing
+ 
+         let approximately_equal =
+-            |a: f32, b: f32| (a - b).abs() / a.abs().max(b.abs()) <= 1.0 / 33.0;
+-
+-        'outer: for advance in advances {
+-            let mut may_push: Option<f32> = None;
+-            if encountered_advances.is_empty() {
+-                encountered_advances.push(advance);
++            |a: f32, b: f32| (a - b).abs() * 33.0 <= a.abs().max(b.abs());
++
++        // Cluster nonzero advances by 3% tolerance, and track whether the ASCII
++        // letters/digits share a single advance.
++        let mut value: Vec<f32> = Vec::new();
++        let mut count: Vec<i64> = Vec::new();
++        let mut total: i64 = 0;
++        let mut overflow = false;
++        let mut ascii_width = 0.0f32;
++        let mut ascii_count: i64 = 0;
++        let mut ascii_varies = false;
++
++        'collect: for (codepoint, advance) in advances {
++            if advance <= 0.0 {
+                 continue;
+             }
+-
+-            for encountered in encountered_advances.iter() {
+-                if encountered_advances.len() >= 3 {
+-                    break 'outer;
++            if (0x30..=0x39).contains(&codepoint)
++                || (0x41..=0x5A).contains(&codepoint)
++                || (0x61..=0x7A).contains(&codepoint)
++            {
++                if ascii_count == 0 {
++                    ascii_width = advance;
++                } else if !approximately_equal(advance, ascii_width) {
++                    ascii_varies = true;
+                 }
+-                if approximately_equal(advance, *encountered) {
+-                    may_push = None;
+-                    break;
++                ascii_count += 1;
++            }
++            if overflow {
++                continue;
++            }
++            for (i, v) in value.iter().enumerate() {
++                if approximately_equal(advance, *v) {
++                    count[i] += 1;
++                    total += 1;
++                    continue 'collect;
+                 }
+-                may_push = Some(advance);
+             }
+-            if let Some(push) = may_push {
+-                encountered_advances.push(push);
++            if value.len() >= MAX_CLUSTERS {
++                // Far more distinct widths than any cell-grid font: proportional.
++                overflow = true;
++                continue;
+             }
++            value.push(advance);
++            count.push(1);
++            total += 1;
+         }
+ 
+-        match encountered_advances.len() {
+-            1 => Some(FC_SPACING_MONO as i32),
+-            2 if approximately_equal(
+-                encountered_advances[0].min(encountered_advances[1]) * 2.0,
+-                encountered_advances[0].max(encountered_advances[1]),
+-            ) =>
+-            {
+-                Some(FC_SPACING_DUAL as i32)
++        // Stage 1 -- legacy classification, preserved verbatim.
++        if !overflow {
++            // No advances, or every glyph the same width: MONO.
++            if total <= 0 || value.len() <= 1 {
++                return Some(FC_SPACING_MONO as i32);
+             }
++            // Exactly two widths in a 2:1 ratio: DUAL.
++            if value.len() == 2 {
++                let lo = value[0].min(value[1]);
++                let hi = value[0].max(value[1]);
++                if approximately_equal(lo * 2.0, hi) {
++                    return Some(FC_SPACING_DUAL as i32);
++                }
++            }
++        }
+ 
+-            _ => None,
++        // Stage 2 -- recover grid fonts that monospace their ASCII.
++        let ascii_monospaced = ascii_count >= MIN_ASCII && !ascii_varies;
++        if overflow || !ascii_monospaced {
++            return None;
++        }
++
++        let on_grid_for = |w: f32| -> i64 {
++            let mut on = 0;
++            for (i, v) in value.iter().enumerate() {
++                let mult = (*v / w).round();
++                if mult >= 1.0 && approximately_equal(*v, mult * w) {
++                    on += count[i];
++                }
++            }
++            on
++        };
++
++        // Try every significant cluster's width as the base cell W, and keep
++        // whichever puts the most advances on an integer grid.  Only real
++        // clusters are candidates: synthesising finer ones (e.g. W/2) would let
++        // the scattered advances of a proportional font land on a dense grid by
++        // coincidence.
++        let mut best_on_grid: i64 = 0;
++        let mut best_w: f32 = 0.0;
++        for i in 0..value.len() {
++            if count[i] * SIGNIFICANT < total {
++                continue; // ignore minor clusters as base-cell candidates
++            }
++            let w = value[i];
++            if w <= 0.0 {
++                continue;
++            }
++            let on = on_grid_for(w);
++            if on > best_on_grid {
++                best_on_grid = on;
++                best_w = w;
++            }
++        }
++
++        if best_w <= 0.0 || best_on_grid * 100 < total * GRID_PERCENT {
++            return None;
++        }
++
++        // On a grid: single-width is mono, dual-width (half/full cell, e.g. CJK)
++        // is dual.  Decide from the most populated cluster.
++        let mut dom = 0;
++        for i in 1..count.len() {
++            if count[i] > count[dom] {
++                dom = i;
++            }
++        }
++        if approximately_equal(value[dom], 2.0 * best_w) {
++            Some(FC_SPACING_DUAL as i32)
++        } else {
++            Some(FC_SPACING_MONO as i32)
+         }
+     }
+ 
+@@ -358,10 +450,10 @@ impl<'a> AttributesToPattern<'a> {
+             .font_ref
+             .charmap()
+             .mappings()
+-            .filter_map(|(_codepoint, gid)| {
++            .filter_map(|(codepoint, gid)| {
+                 glyph_metrics
+                     .advance_width(gid)
+-                    .and_then(|adv| if adv > 0.0 { Some(adv) } else { None })
++                    .and_then(|adv| if adv > 0.0 { Some((codepoint, adv)) } else { None })
+             });
+ 
+         Self::spacing_from_advances(advances)
+@@ -564,72 +656,127 @@ mod test {
+     use crate::attributes::AttributesToPattern;
+     use fontconfig_bindings::{FC_SPACING_DUAL, FC_SPACING_MONO};
+ 
+-    const THRESHOLD_FACTOR_DOWN: f32 = 1.0 - 1.0 / 33.0;
+-    const THRESHOLD_FACTOR_UP: f32 = 1.0 + 1.0 / 33.0;
++    // ASCII letter coverage for a synthetic font.
++    enum Ascii {
++        None,       // no Latin letters (e.g. CJK / emoji / symbol fonts)
++        Mono(f32),  // Latin letters present and all at this advance (monospaced)
++        Varies,     // Latin letters present but proportional
++    }
++
++    // Build (codepoint, advance) glyphs from (advance, count) cluster pairs.
++    // The cluster glyphs are given non-ASCII codepoints so only the explicit
++    // Ascii spec drives the ASCII-monospace gate.
++    fn glyphs(pairs: &[(f32, usize)], ascii: Ascii) -> Vec<(u32, f32)> {
++        let mut v = Vec::new();
++        let mut cp = 0x3000u32; // CJK area: never ASCII
++        for &(adv, count) in pairs {
++            for _ in 0..count {
++                v.push((cp, adv));
++                cp += 1;
++            }
++        }
++        match ascii {
++            Ascii::None => {}
++            // 26 lowercase letters (>= MIN_ASCII) at one advance.
++            Ascii::Mono(w) => v.extend((0x61..=0x7Au32).map(|c| (c, w))),
++            // 26 lowercase letters at increasing advances.
++            Ascii::Varies => {
++                v.extend((0x61..=0x7Au32).enumerate().map(|(i, c)| (c, 500.0 + i as f32 * 50.0)))
++            }
++        }
++        v
++    }
+ 
+-    fn assert_spacing(advances: impl Iterator<Item = f32>, expectation: Option<i32>) {
++    // The cases below mirror test/test-spacing.c (the FreeType-side unit test)
++    // so both backends are checked against the same real-font corpus.
++    fn assert_spacing(pairs: &[(f32, usize)], ascii: Ascii, expectation: Option<i32>) {
+         assert_eq!(
+-            AttributesToPattern::spacing_from_advances(advances),
++            AttributesToPattern::spacing_from_advances(glyphs(pairs, ascii).into_iter()),
+             expectation
+         );
+     }
+ 
+     #[test]
+     fn spacing_mono() {
+-        assert_spacing([10.0].iter().cloned(), Some(FC_SPACING_MONO as i32));
+-
++        // Uniform width -> MONO via the legacy stage (ASCII irrelevant).
++        assert_spacing(&[(600.0, 1000)], Ascii::None, Some(FC_SPACING_MONO as i32));
++        // Grid font with a 2x em dash plus a stray off-grid glyph, monospaced
++        // ASCII: recovered as MONO (mirrors Noto Sans Mono at 99.97%).  The old
++        // "first three distinct advances" rule wrongly reported this proportional.
+         assert_spacing(
+-            [
+-                10.0,
+-                10.0,
+-                10.0,
+-                10.0 * THRESHOLD_FACTOR_UP,
+-                10.0 * THRESHOLD_FACTOR_DOWN,
+-            ]
+-            .iter()
+-            .cloned(),
++            &[(563.0, 9994), (1126.0, 3), (800.0, 3)],
++            Ascii::Mono(563.0),
+             Some(FC_SPACING_MONO as i32),
+         );
+     }
+ 
+     #[test]
+-    fn spacing_proportional() {
++    fn spacing_dual() {
++        // Two widths in a 2:1 ratio -> DUAL via the legacy stage, preserved even
++        // without Latin (mirrors Droid Sans Japanese).
+         assert_spacing(
+-            [10.0, 10.0 * THRESHOLD_FACTOR_UP + 0.01].iter().cloned(),
+-            None,
++            &[(128.0, 63), (256.0, 6555)],
++            Ascii::None,
++            Some(FC_SPACING_DUAL as i32),
+         );
++    }
+ 
++    #[test]
++    fn spacing_ascii_gate() {
++        // Same uniform full-width grid, classified only by the ASCII gate:
++        // promoted to MONO with monospaced ASCII, proportional without it
++        // (the latter mirrors Noto Serif Tangut / Hentaigana / emoji).
+         assert_spacing(
+-            [10.0, 10.0 * THRESHOLD_FACTOR_DOWN - 0.01].iter().cloned(),
++            &[(1000.0, 9800), (2000.0, 150), (3000.0, 50)],
++            Ascii::Mono(1000.0),
++            Some(FC_SPACING_MONO as i32),
++        );
++        assert_spacing(
++            &[(1000.0, 9800), (2000.0, 150), (3000.0, 50)],
++            Ascii::None,
+             None,
+         );
+-
+-        assert_spacing([10.0, 15.0].iter().cloned(), None);
+-
+-        assert_spacing([10.0, 15.0, 20.0].iter().cloned(), None);
+     }
+ 
+     #[test]
+-    fn advances_dual() {
+-        assert_spacing([10.0, 20.0].iter().cloned(), Some(FC_SPACING_DUAL as i32));
+-
++    fn spacing_proportional() {
++        // Proportional by design -- stays proportional even if named "Mono"
++        // (mirrors Latin Modern Mono Prop at 27% grid conformance).
+         assert_spacing(
+-            [10.0, 20.0, 10.0, 20.0, 10.0, 20.0].iter().cloned(),
+-            Some(FC_SPACING_DUAL as i32),
++            &[(261.0, 270), (400.0, 250), (550.0, 240), (700.0, 240)],
++            Ascii::Mono(261.0),
++            None,
+         );
+-
++        // CJK "mono": 73% on the 500/1000 grid, ~26% Hangul off-grid at 920.
++        // Half-width Latin is monospaced, yet the grid threshold still rejects it.
+         assert_spacing(
+-            [
+-                10.0,
+-                20.0 * THRESHOLD_FACTOR_UP,
+-                10.0,
+-                20.0,
+-                10.0 * THRESHOLD_FACTOR_DOWN,
+-                20.0,
+-            ]
+-            .iter()
+-            .cloned(),
+-            Some(FC_SPACING_DUAL as i32),
++            &[(1000.0, 6000), (500.0, 1300), (920.0, 2700)],
++            Ascii::Mono(500.0),
++            None,
++        );
++        // One dominant width (94.9%) plus a scattered tail -- proportional
++        // (mirrors AlgolRevived).  The tail sits on a 63 (W/2) grid, so a
++        // half-width base-cell candidate would wrongly promote this to DUAL;
++        // only whole-cluster candidates keep it proportional.
++        assert_spacing(
++            &[
++                (126.0, 9190),
++                (190.0, 100),
++                (310.0, 90),
++                (440.0, 85),
++                (570.0, 80),
++                (695.0, 75),
++                (820.0, 61),
++            ],
++            Ascii::Mono(126.0),
++            None,
++        );
++        // Grid-conformant but with proportional Latin -> rejected by the ASCII
++        // gate (e.g. an ideographic font that includes proportional Latin).
++        assert_spacing(
++            &[(1000.0, 9800), (2000.0, 150), (3000.0, 50)],
++            Ascii::Varies,
++            None,
+         );
+     }
+ }
+diff --git a/src/fcfreetype.c b/src/fcfreetype.c
+index e3acf189..5b6adbe7 100644
+--- a/src/fcfreetype.c
++++ b/src/fcfreetype.c
+@@ -504,6 +504,9 @@ FcFontHasHint (FT_Face face);
+ static int
+ FcFreeTypeSpacing (FT_Face face);
+ 
++static FcCharSet *
++FcFreeTypeCharSetAndSpacingInternal (FT_Face face, int *spacing);
++
+ #define NUM_FC_MAC_ROMAN_FAKE (int)(sizeof (fcMacRomanFake) / sizeof (fcMacRomanFake[0]))
+ 
+ /* From http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/ROMAN.TXT */
+@@ -1953,10 +1956,14 @@ FcFreeTypeQueryFaceInternal (const FT_Face   face,
+     /*
+      * Compute the unicode coverage for the font
+      */
+-    if (cs_share && *cs_share)
++    spacing = FC_SPACING_PROPORTIONAL;
++    if (cs_share && *cs_share) {
+ 	cs = FcCharSetCopy (*cs_share);
+-    else {
+-	cs = FcFreeTypeCharSet (face, NULL);
++	/* Charset reused from a sibling face, but spacing is per-face. */
++	spacing = FcFreeTypeSpacing (face);
++    } else {
++	/* Compute charset and spacing together in one cmap traversal. */
++	cs = FcFreeTypeCharSetAndSpacingInternal (face, &spacing);
+ 	if (cs_share)
+ 	    *cs_share = FcCharSetCopy (cs);
+     }
+@@ -1968,7 +1975,6 @@ FcFreeTypeQueryFaceInternal (const FT_Face   face,
+     if (!FcPatternObjectAddBool (pat, FC_SYMBOL_OBJECT, symbol))
+ 	goto bail1;
+ 
+-    spacing = FcFreeTypeSpacing (face);
+ #if HAVE_FT_GET_BDF_PROPERTY
+     /* For PCF fonts, override the computed spacing with the one from
+        the property */
+@@ -2406,13 +2412,205 @@ static inline FcBool fc_approximately_equal (int x, int y)
+     return abs (x - y) * 33 <= fc_max (abs (x), abs (y));
+ }
+ 
++/*
++ * Monospace (FC_SPACING) detection.
++ *
++ * Two-stage, deliberately additive:
++ *
++ *  1. Reproduce the historical classification (a font whose advances collapse
++ *     to a single width is MONO; two widths in a 2:1 ratio is DUAL).  Whatever
++ *     that recognises is returned unchanged, so this code never reclassifies a
++ *     font that already had a spacing -- in particular CJK / ideographic, emoji
++ *     and symbol fonts (whose uniform full-cell advances are not monospaced
++ *     Latin text) keep exactly the spacing they had before.
++ *
++ *  2. Only when the legacy rule says PROPORTIONAL do we try to recover a grid
++ *     font: a monospace font lays every glyph on a fixed cell grid, so every
++ *     nonzero advance is an integer multiple k*W of a base cell W (a wide glyph
++ *     -- an em dash, a CJK ideograph -- spans 2 or 3 cells).  This recovers
++ *     fonts such as Noto Sans Mono and Latin Modern Mono, which the legacy rule
++ *     wrongly rejected because of a handful of intentionally wide glyphs.
++ *
++ * Recovery is gated on the font actually monospacing its ASCII letters: that is
++ * the defining trait of a Latin monospace font, and it is what keeps uniform
++ * full-width scripts (ideographic, kana, emoji) from being promoted.
++ * The gate is name-independent -- a font named "...Mono" that is proportional by
++ * design never passes it.
++ */
++#define FC_SPACING_MAX_CLUSTERS 64 /* real grid fonts have only a few distinct advances */
++#define FC_SPACING_GRID_PERCENT 98 /* min % of advances that must sit on the cell grid */
++#define FC_SPACING_SIGNIFICANT  20 /* a cluster is a base-cell candidate at >= total/20 (5%) */
++#define FC_SPACING_MIN_ASCII    20 /* min ASCII letters/digits needed to judge Latin spacing */
++
++typedef struct _FcAdvanceClusters
++{
++    int    value[FC_SPACING_MAX_CLUSTERS]; /* representative advance of each cluster */
++    int    count[FC_SPACING_MAX_CLUSTERS]; /* glyphs tallied into each cluster */
++    int    num;                            /* clusters in use */
++    int    total;                          /* total nonzero advances tallied */
++    FcBool overflow;                       /* more distinct advances than any grid font has */
++    int    ascii_width;                    /* advance of the first ASCII letter/digit seen */
++    int    ascii_count;                    /* ASCII letters/digits seen */
++    FcBool ascii_varies;                   /* an ASCII letter/digit had a different advance */
++} FcAdvanceClusters;
++
++static void
++FcAdvanceClustersAdd (FcAdvanceClusters *c, FcChar32 ucs4, FT_Pos advance)
++{
++    int a = (int)advance;
++    int j;
++
++    if (a <= 0)
++	return;
++    /* Track whether the ASCII letters/digits share a single advance -- the
++     * defining trait of a Latin monospace font. */
++    if ((ucs4 >= '0' && ucs4 <= '9') ||
++        (ucs4 >= 'A' && ucs4 <= 'Z') ||
++        (ucs4 >= 'a' && ucs4 <= 'z')) {
++	if (c->ascii_count == 0)
++	    c->ascii_width = a;
++	else if (!fc_approximately_equal (a, c->ascii_width))
++	    c->ascii_varies = FcTrue;
++	c->ascii_count++;
++    }
++    if (c->overflow)
++	return;
++    for (j = 0; j < c->num; j++)
++	if (fc_approximately_equal (a, c->value[j])) {
++	    c->count[j]++;
++	    c->total++;
++	    return;
++	}
++    if (c->num >= FC_SPACING_MAX_CLUSTERS) {
++	/* Far more distinct widths than any cell-grid font: proportional. */
++	c->overflow = FcTrue;
++	return;
++    }
++    c->value[c->num] = a;
++    c->count[c->num] = 1;
++    c->num++;
++    c->total++;
++}
++
++static FcBool
++FcAdvanceClustersAsciiMono (const FcAdvanceClusters *c)
++{
++    return c->ascii_count >= FC_SPACING_MIN_ASCII && !c->ascii_varies;
++}
++
++/*
++ * Classify a font from its advance-width clusters.  Exposed (via fcint.h) so
++ * the heuristic can be unit tested with synthetic cluster data.
++ */
++FcPrivate int
++FcSpacingClassify (const int *value,
++                   const int *count,
++                   int        num,
++                   int        total,
++                   FcBool     overflow,
++                   FcBool     ascii_monospaced)
++{
++    int  i, k;
++    long best_on_grid = 0;
++    int  best_w = 0;
++    int  dom;
++
++    /*
++     * Stage 1 -- legacy classification, preserved verbatim.
++     * (A font with more than FC_SPACING_MAX_CLUSTERS distinct advances had >= 3
++     * distinct advances under the old rule too, i.e. PROPORTIONAL.)
++     */
++    if (!overflow) {
++	/* No advances, or every glyph the same width: MONO. */
++	if (total <= 0 || num <= 1)
++	    return FC_SPACING_MONO;
++	/* Exactly two widths in a 2:1 ratio: DUAL. */
++	if (num == 2 &&
++	    fc_approximately_equal (fc_min (value[0], value[1]) * 2,
++	                            fc_max (value[0], value[1])))
++	    return FC_SPACING_DUAL;
++    }
++
++    /*
++     * Stage 2 -- the legacy rule says PROPORTIONAL.  Recover grid fonts, but
++     * only those that monospace their ASCII (genuine Latin monospace); this
++     * leaves uniform full-width scripts, emoji and symbol fonts proportional.
++     */
++    if (overflow || !ascii_monospaced)
++	return FC_SPACING_PROPORTIONAL;
++
++    /*
++     * Try every significant cluster's width as the base cell W, and keep
++     * whichever W places the most advances on an integer grid.  Only real
++     * clusters are candidates: a genuine dual-width font has its base cell
++     * populated (so it is a candidate in its own right), whereas synthesising
++     * finer candidates (e.g. W/2) would let the scattered advances of a
++     * proportional font land on a dense grid by coincidence.
++     */
++    for (i = 0; i < num; i++) {
++	int  w = value[i];
++	long on_grid = 0;
++
++	if (count[i] * FC_SPACING_SIGNIFICANT < total)
++	    continue; /* ignore minor clusters as base-cell candidates */
++	if (w <= 0)
++	    continue;
++	for (k = 0; k < num; k++) {
++	    int mult = (value[k] + w / 2) / w; /* nearest integer multiple */
++	    if (mult >= 1 && fc_approximately_equal (value[k], mult * w))
++		on_grid += count[k];
++	}
++	if (on_grid > best_on_grid) {
++	    best_on_grid = on_grid;
++	    best_w = w;
++	}
++    }
++
++    if (best_w <= 0 ||
++        best_on_grid * 100 < (long)total * FC_SPACING_GRID_PERCENT)
++	return FC_SPACING_PROPORTIONAL;
++
++    /*
++     * On a grid: single-width is mono, dual-width (half/full cell, e.g. CJK)
++     * is dual.  Decide from the most populated cluster.
++     */
++    dom = 0;
++    for (i = 1; i < num; i++)
++	if (count[i] > count[dom])
++	    dom = i;
++    if (fc_approximately_equal (value[dom], 2 * best_w))
++	return FC_SPACING_DUAL;
++    return FC_SPACING_MONO;
++}
++
++/*
++ * For a bitmap (non-scalable) font, select the strike closest to 16px so the
++ * advances we read back are meaningful.
++ */
++static void
++FcFreeTypeSelectSpacingStrike (FT_Face face)
++{
++    FT_Int strike_index = 0, i;
++
++    if ((face->face_flags & FT_FACE_FLAG_SCALABLE) ||
++        face->num_fixed_sizes <= 0 ||
++        !FT_Get_Sfnt_Table (face, ft_sfnt_head))
++	return;
++    /* Select the face closest to 16 pixels tall */
++    for (i = 1; i < face->num_fixed_sizes; i++) {
++	if (abs (face->available_sizes[i].height - 16) <
++	    abs (face->available_sizes[strike_index].height - 16))
++	    strike_index = i;
++    }
++    FT_Select_Size (face, strike_index);
++}
++
+ static int
+ FcFreeTypeSpacing (FT_Face face)
+ {
+-    FT_Int       load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH | FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING;
+-    FT_Pos       advances[3] = { 0 };
+-    unsigned int num_advances = 0;
+-    int          o;
++    FT_Int            load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH | FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING;
++    FcAdvanceClusters clusters = { 0 };
++    int               o;
+ 
+     /* When using scalable fonts, only report those glyphs
+      * which can be scaled; otherwise those fonts will
+@@ -2422,20 +2620,8 @@ FcFreeTypeSpacing (FT_Face face)
+      */
+     if (face->face_flags & FT_FACE_FLAG_SCALABLE)
+ 	load_flags |= FT_LOAD_NO_BITMAP;
+-
+-    if (!(face->face_flags & FT_FACE_FLAG_SCALABLE) &&
+-        face->num_fixed_sizes > 0 &&
+-        FT_Get_Sfnt_Table (face, ft_sfnt_head)) {
+-	FT_Int strike_index = 0, i;
+-	/* Select the face closest to 16 pixels tall */
+-	for (i = 1; i < face->num_fixed_sizes; i++) {
+-	    if (abs (face->available_sizes[i].height - 16) <
+-	        abs (face->available_sizes[strike_index].height - 16))
+-		strike_index = i;
+-	}
+-
+-	FT_Select_Size (face, strike_index);
+-    }
++    else
++	FcFreeTypeSelectSpacingStrike (face);
+ 
+     for (o = 0; o < NUM_DECODE; o++) {
+ 	FcChar32 ucs4;
+@@ -2445,38 +2631,44 @@ FcFreeTypeSpacing (FT_Face face)
+ 	    continue;
+ 
+ 	ucs4 = FT_Get_First_Char (face, &glyph);
+-	while (glyph != 0 && num_advances < 3) {
++	while (glyph != 0 && !clusters.overflow) {
+ 	    FT_Pos advance = 0;
+-	    if (!FT_Get_Advance (face, glyph, load_flags, &advance) && advance) {
+-		unsigned int j;
+-		for (j = 0; j < num_advances; j++)
+-		    if (fc_approximately_equal (advance, advances[j]))
+-			break;
+-		if (j == num_advances)
+-		    advances[num_advances++] = advance;
+-	    }
++	    if (!FT_Get_Advance (face, glyph, load_flags, &advance))
++		FcAdvanceClustersAdd (&clusters, ucs4, advance);
+ 
+ 	    ucs4 = FT_Get_Next_Char (face, ucs4, &glyph);
+ 	}
+ 	break;
+     }
+ 
+-    if (num_advances <= 1)
+-	return FC_SPACING_MONO;
+-    else if (num_advances == 2 &&
+-             fc_approximately_equal (fc_min (advances[0], advances[1]) * 2,
+-                                     fc_max (advances[0], advances[1])))
+-	return FC_SPACING_DUAL;
+-    else
+-	return FC_SPACING_PROPORTIONAL;
++    return FcSpacingClassify (clusters.value, clusters.count, clusters.num,
++                              clusters.total, clusters.overflow,
++                              FcAdvanceClustersAsciiMono (&clusters));
+ }
+ 
+-FcCharSet *
+-FcFreeTypeCharSet (FT_Face face, FcBlanks *blanks FC_UNUSED)
++/*
++ * Build the font's charset and, when spacing is non-NULL, its FC_SPACING in a
++ * single cmap traversal.  Folding the advance tally into the charset glyph
++ * loop keeps the heuristic off the startup path's critical cost: it reuses the
++ * traversal FcFreeTypeCharSet already performs rather than walking the cmap a
++ * second time.
++ */
++static FcCharSet *
++FcFreeTypeCharSetAndSpacingInternal (FT_Face face, int *spacing)
+ {
+-    const FT_Int load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH | FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING;
+-    FcCharSet   *fcs;
+-    int          o;
++    const FT_Int      load_flags = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH | FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING;
++    const FT_Int      advance_flags = load_flags | FT_LOAD_NO_BITMAP;
++    FcCharSet        *fcs;
++    int               o;
++    FcAdvanceClusters clusters = { 0 };
++    /*
++     * Fold the advance tally into the charset loop only for scalable fonts.
++     * A bitmap font needs a strike selected (FT_Select_Size) to yield
++     * meaningful advances, but that selection also changes what FT_Load_Glyph
++     * returns for the charset's control-char contour check -- so for those we
++     * leave the charset pass untouched and compute spacing separately below.
++     */
++    FcBool fold = spacing && (face->face_flags & FT_FACE_FLAG_SCALABLE);
+ 
+     fcs = FcCharSetCreate();
+     if (!fcs)
+@@ -2508,6 +2700,12 @@ FcFreeTypeCharSet (FT_Face face, FcBlanks *blanks FC_UNUSED)
+ 	    if (good)
+ 		FcCharSetAddChar (fcs, ucs4);
+ 
++	    if (fold && !clusters.overflow) {
++		FT_Pos advance = 0;
++		if (!FT_Get_Advance (face, glyph, advance_flags, &advance))
++		    FcAdvanceClustersAdd (&clusters, ucs4, advance);
++	    }
++
+ 	    ucs4 = FT_Get_Next_Char (face, ucs4, &glyph);
+ 	}
+ 	if (fcFontEncodings[o] == FT_ENCODING_MS_SYMBOL) {
+@@ -2539,6 +2737,15 @@ FcFreeTypeCharSet (FT_Face face, FcBlanks *blanks FC_UNUSED)
+ 	break;
+     }
+ 
++    if (fold)
++	*spacing = FcSpacingClassify (clusters.value, clusters.count, clusters.num,
++	                              clusters.total, clusters.overflow,
++	                              FcAdvanceClustersAsciiMono (&clusters));
++    else if (spacing)
++	/* Bitmap font: separate pass so strike selection cannot disturb the
++	 * charset computed above. */
++	*spacing = FcFreeTypeSpacing (face);
++
+     return fcs;
+ bail:
+     FcCharSetDestroy (fcs);
+@@ -2546,12 +2753,15 @@ bail:
+ }
+ 
+ FcCharSet *
+-FcFreeTypeCharSetAndSpacing (FT_Face face, FcBlanks *blanks FC_UNUSED, int *spacing)
++FcFreeTypeCharSet (FT_Face face, FcBlanks *blanks FC_UNUSED)
+ {
+-    if (spacing)
+-	*spacing = FcFreeTypeSpacing (face);
++    return FcFreeTypeCharSetAndSpacingInternal (face, NULL);
++}
+ 
+-    return FcFreeTypeCharSet (face, blanks);
++FcCharSet *
++FcFreeTypeCharSetAndSpacing (FT_Face face, FcBlanks *blanks FC_UNUSED, int *spacing)
++{
++    return FcFreeTypeCharSetAndSpacingInternal (face, spacing);
+ }
+ 
+ /* Graphite Rules Table */
+diff --git a/src/fcint.h b/src/fcint.h
+index 2c5b5d48..84766ebf 100644
+--- a/src/fcint.h
++++ b/src/fcint.h
+@@ -1233,6 +1233,15 @@ FcDirScanConfig (FcFontSet     *set,
+ FcPrivate int
+ FcFontDebug (void);
+ 
++/* fcfreetype.c */
++FcPrivate int
++FcSpacingClassify (const int *value,
++                   const int *count,
++                   int        num,
++                   int        total,
++                   FcBool     overflow,
++                   FcBool     ascii_monospaced);
++
+ /* fcfs.c */
+ 
+ FcPrivate FcBool
+diff --git a/test/test-spacing.c b/test/test-spacing.c
+new file mode 100644
+index 00000000..b69779aa
+--- /dev/null
++++ b/test/test-spacing.c
+@@ -0,0 +1,120 @@
++/* Copyright (C) 2026 fontconfig Authors */
++/* SPDX-License-Identifier: HPND */
++
++/*
++ * Unit test for the FC_SPACING classifier (FcSpacingClassify).
++ *
++ * The classifier is name-independent and runs in two stages:
++ *   1. the legacy rule (single width -> MONO; two widths in a 2:1 ratio ->
++ *      DUAL) is reproduced verbatim, so nothing that already had a spacing is
++ *      reclassified;
++ *   2. only when the legacy rule yields PROPORTIONAL do we attempt grid-based
++ *      recovery, and only for fonts that monospace their ASCII letters.
++ *
++ * The cases mirror a real-font corpus measured on a live system (see the
++ * monospace-detection plan).  They assert:
++ *   - genuine grid fonts with a few intentionally wide glyphs (Noto Sans Mono,
++ *     Latin Modern Mono) are recovered as MONO;
++ *   - proportional-by-design fonts stay PROPORTIONAL even when named "Mono";
++ *   - uniform full-width scripts / emoji / symbol fonts (grid-conformant but no
++ *     monospaced ASCII) are NOT promoted;
++ *   - fonts the legacy rule already recognised (incl. CJK dual) are preserved.
++ */
++#include "fcint.h"
++
++#include <fontconfig/fontconfig.h>
++#include <stdio.h>
++
++typedef struct _SpacingCase
++{
++    const char *name;
++    int         value[8];
++    int         count[8];
++    int         num;
++    FcBool      overflow;
++    FcBool      ascii_monospaced;
++    int         expected;
++} SpacingCase;
++
++static int
++total_of (const SpacingCase *c)
++{
++    int i, total = 0;
++    for (i = 0; i < c->num; i++)
++	total += c->count[i];
++    return total;
++}
++
++static const char *
++spacing_name (int spacing)
++{
++    switch (spacing) {
++    case FC_SPACING_PROPORTIONAL: return "PROPORTIONAL";
++    case FC_SPACING_DUAL: return "DUAL";
++    case FC_SPACING_MONO: return "MONO";
++    case FC_SPACING_CHARCELL: return "CHARCELL";
++    default: return "?";
++    }
++}
++
++static const SpacingCase cases[] = {
++    /* name                               values                    counts                     n  ovf      ascii    expected */
++
++    /* Legacy stage: no advances / one uniform width -> MONO (ASCII irrelevant). */
++    { "empty",                            { 0 },                    { 0 },                     0, FcFalse, FcFalse, FC_SPACING_MONO },
++    { "single width",                     { 600 },                  { 1000 },                  1, FcFalse, FcTrue,  FC_SPACING_MONO },
++    { "Liberation Mono",                  { 1229 },                 { 1000 },                  1, FcFalse, FcTrue,  FC_SPACING_MONO },
++    { "IBM Plex Mono",                    { 600 },                  { 5000 },                  1, FcFalse, FcTrue,  FC_SPACING_MONO },
++    /* Legacy stage: two widths in 2:1 -> DUAL, preserved even without ASCII
++     * (mirrors Droid Sans Japanese: half/full-width CJK, no Latin). */
++    { "CJK dual, no ASCII (legacy)",      { 128, 256 },             { 63, 6555 },              2, FcFalse, FcFalse, FC_SPACING_DUAL },
++
++    /* Recovery stage: grid fonts with intentionally wide glyphs and monospaced
++     * ASCII -> MONO.  The legacy rule wrongly rejected these. */
++    { "Noto Sans Mono (99.97%)",          { 563, 1126, 800 },       { 9994, 3, 3 },            3, FcFalse, FcTrue,  FC_SPACING_MONO },
++    { "Latin Modern Mono (99.44%)",       { 525, 1050, 300 },       { 9944, 50, 6 },           3, FcFalse, FcTrue,  FC_SPACING_MONO },
++
++    /* The ASCII gate is the decider between these two: identical uniform
++     * full-width grid, promoted only when the ASCII is monospaced. */
++    { "full-width grid, ASCII mono",      { 1000, 2000, 3000 },     { 9800, 150, 50 },         3, FcFalse, FcTrue,  FC_SPACING_MONO },
++    { "full-width grid, no ASCII (CJK)",  { 1000, 2000, 3000 },     { 9800, 150, 50 },         3, FcFalse, FcFalse, FC_SPACING_PROPORTIONAL },
++
++    /* Recovery stage, rejected on grid conformance (ASCII is monospaced). */
++    { "Latin Modern Mono Prop (27%)",     { 261, 400, 550, 700 },   { 270, 250, 240, 240 },    4, FcFalse, FcTrue,  FC_SPACING_PROPORTIONAL },
++    { "Noto Sans Mono CJK (73%)",         { 1000, 500, 920 },       { 6000, 1300, 2700 },      3, FcFalse, FcTrue,  FC_SPACING_PROPORTIONAL },
++    /* One dominant width (94.9%) + scattered tail (mirrors AlgolRevived): the
++     * tail sits on a 63 (W/2) grid, so a half-width candidate would wrongly
++     * promote it; whole-cluster candidates keep it proportional. */
++    { "single width + scattered tail",    { 126, 190, 310, 440, 570, 695, 820 }, { 9190, 100, 90, 85, 80, 75, 61 }, 7, FcFalse, FcTrue, FC_SPACING_PROPORTIONAL },
++
++    /* Recovery stage, rejected by the ASCII gate: grid-conformant advances but
++     * proportional Latin (e.g. an ideographic font that includes proportional
++     * Latin, or a plain proportional font). */
++    { "proportional Latin (no ASCII mono)", { 500, 600, 700, 800, 900, 1000 }, { 160, 170, 170, 170, 170, 160 }, 6, FcFalse, FcFalse, FC_SPACING_PROPORTIONAL },
++    /* Too many distinct widths to be any cell grid. */
++    { "overflow",                         { 100, 200 },             { 10, 10 },                2, FcTrue,  FcFalse, FC_SPACING_PROPORTIONAL },
++};
++
++int
++main (void)
++{
++    size_t i;
++    int    ret = 0;
++
++    for (i = 0; i < sizeof (cases) / sizeof (cases[0]); i++) {
++	const SpacingCase *c = &cases[i];
++	int                total = total_of (c);
++	int                got = FcSpacingClassify (c->value, c->count, c->num,
++	                                             total, c->overflow,
++	                                             c->ascii_monospaced);
++	if (got != c->expected) {
++	    fprintf (stderr, "FAIL: %-34s expected %s, got %s\n",
++	             c->name, spacing_name (c->expected), spacing_name (got));
++	    ret = 1;
++	} else {
++	    printf ("ok: %-34s %s\n", c->name, spacing_name (got));
++	}
++    }
++
++    return ret;
++}
+-- 
+2.56.0
+

diff --git a/fontconfig.spec b/fontconfig.spec
index fdb0d4d..38b6eef 100644
--- a/fontconfig.spec
+++ b/fontconfig.spec
@@ -23,6 +23,8 @@ Patch4:		%{name}-drop-lang-from-pkgkit-format.patch
 Patch6:		%{name}-lower-nonlatin-conf.patch
 # Fedora specific
 Patch7:		%{name}-update-fcgenericfamily.patch
+## Backport
+Patch100:	%{name}-fix-mono-detection.patch
 
 BuildRequires:	libxml2-devel
 BuildRequires:	freetype-devel >= %{freetype_version}

                 reply	other threads:[~2026-11-18 13:23 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=179500821883.1.3524655353302441461.rpms-fontconfig-5d0ba8c986c2@fedoraproject.org \
    --to=tagoh@redhat.com \
    --cc=git-commits@fedoraproject.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox