Skip to main content

patch_charter.py

#!/usr/bin/env python3

"""Put this script next to "Charter 210112.zip" and run.

Needs
* the font from https://practicaltypography.com/charter.html
* fonttools (https://github.com/fonttools/fonttools)

This fixes the sign of two font metrics, namely the descent values in
hhea.descent and OS/2.sTypoDescender. It seems that those are supposed
to be negative, but weren't. That lead to some line spacing issues.

The script also adds some useful space characters based on usual
metrics.

Written mostly with the help of the Claude LLM, so excuse any
weirdness.  My contributions are licensed as indicated below.

Written 2026 by Tobias Brink

To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the
public domain worldwide. This software is distributed without any
warranty.

You should have received a copy of the CC0 Public Domain Dedication
along with this software. If not, see
<https://creativecommons.org/publicdomain/zero/1.0/>.

"""

import hashlib
import tempfile
import subprocess
from pathlib import Path

import fontTools
from fontTools.misc.timeTools import timestampFromString
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables._g_l_y_f import Glyph

MODIFIED_DATE = "Tue Nov 03 22:45:43 2026"

ITALIC_BIT = 1 << 0
BOLD_BIT = 1 << 5

# Advance widths in font units at 1000 units per em (scaled if the font differs).
SPACE_WIDTHS = {
    0x2000: 500,   # en quad                  1/2 em
    0x2001: 1000,  # em quad                  1 em
    0x2002: 500,   # en space                 1/2 em
    0x2003: 1000,  # em space                 1 em
    0x2004: 333,   # three-per-em space       1/3 em
    0x2005: 250,   # four-per-em space        1/4 em
    0x2006: 167,   # six-per-em space         1/6 em
    0x2009: 200,   # thin space               1/5 em
    0x200A: 62,    # hair space               1/16 em (62.5, rounded down)
    0x202F: 200,   # narrow no-break space    same as thin space
    0x205F: 222,   # medium mathematical sp.  4/18 em
}
# Not listed above, computed from the font itself:
#   U+00A0 = width of U+0020, U+2007 = width of "0", U+2008 = width of "."

HYPHENS = [0x00AD, 0x2010, 0x2011]

# (italic, bold) per style, used for a sanity check only
STYLE_FLAGS = {
    "regular": (False, False),
    "italic": (True, False),
    "bold": (False, True),
    "bolditalic": (True, True),
}


def patch_charter(src_path, out_path, style):
    if style not in STYLE_FLAGS:
        raise SystemExit(f"unknown style {style!r}; expected one of {sorted(STYLE_FLAGS)}")

    with open(src_path, "rb") as fh:
        digest = hashlib.sha256(fh.read()).hexdigest()
    src = TTFont(src_path, recalcTimestamp=False)
    upm = src["head"].unitsPerEm

    # Sanity check: is this file the style we think it is?
    italic, bold = STYLE_FLAGS[style]
    sel = src["OS/2"].fsSelection
    if bool(sel & ITALIC_BIT) != italic or bool(sel & BOLD_BIT) != bold:
        print(f"WARNING: {src_path} does not look like style {style!r}")

    # 1. Vertical metrics: keep the magnitudes, fix only the sign of the two
    #    descenders. usWinDescent is unsigned and stays as it is.
    src["hhea"].descent = -abs(src["hhea"].descent)
    src["OS/2"].sTypoDescender = -abs(src["OS/2"].sTypoDescender)

    # 2. Missing spaces: empty glyphs appended after all existing ones.
    nc = src.getBestCmap()
    glyf, hmtx = src["glyf"], src["hmtx"]
    order = src.getGlyphOrder()
    widths = {cp: round(w * upm / 1000) for cp, w in SPACE_WIDTHS.items()}
    widths[0x00A0] = hmtx[nc[0x0020]][0]  # no-break space = word space
    widths[0x2007] = hmtx[nc[0x0030]][0]  # figure space = width of "0"
    widths[0x2008] = hmtx[nc[0x002E]][0]  # punctuation space = width of "."
    alias = {}
    for cp, width in sorted(widths.items()):
        if cp in nc:
            continue
        name = f"uni{cp:04X}"
        if name in order:
            raise ValueError(f"glyph {name} already exists")
        order.append(name)
        glyf[name] = Glyph()
        hmtx[name] = (width, 0)
        alias[cp] = name

    # 3. Hyphens: reuse the font's own hyphen-minus glyph.
    for cp in HYPHENS:
        if cp not in nc:
            alias[cp] = nc[0x002D]

    src.setGlyphOrder(order)
    for table in src["cmap"].tables:
        if table.isUnicode() and table.format != 14:
            table.cmap.update(alias)

    # Modified date.
    src["head"].modified = timestampFromString(MODIFIED_DATE)

    src.flavor = "woff2"
    src.save(out_path)

    print(out_path)
    print("   ", src_path)
    print("    SHA256:", digest, f"fontTools {fontTools.version}")
    print("    added:", ", ".join(f"U+{cp:04X}" for cp in sorted(alias)[:10]))
    if len(alias) > 10:
        print("          ", ", ".join(f"U+{cp:04X}" for cp in sorted(alias)[10:20]))
    if len(alias) > 20:
        print("          ", ", ".join(f"U+{cp:04X}" for cp in sorted(alias)[20:30]))
    print(f"    hhea {src['hhea'].ascent}/{src['hhea'].descent}/{src['hhea'].lineGap}")
    print(f"    typo {src['OS/2'].sTypoAscender}/{src['OS/2'].sTypoDescender}/{src['OS/2'].sTypoLineGap}")
    print(f"    win {src['OS/2'].usWinAscent}/{src['OS/2'].usWinDescent}")


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as d:
        subprocess.run(["unzip", "Charter 210112.zip", "-d", d])
        ttf_basedir = Path(d) / "Charter 210112" / "TTF format (best for Windows)" / "Charter"
        for src, outname in [("Charter Regular.ttf",
                              "charter_regular.woff2"),
                             ("Charter Italic.ttf",
                              "charter_italic.woff2"),
                             ("Charter Bold.ttf",
                              "charter_bold.woff2"),
                             ("Charter Bold Italic.ttf",
                              "charter_bold_italic.woff2")]:
            style = "".join(outname.split(".")[0].split("_")[1:])
            patch_charter(ttf_basedir / src, outname, style)