Repository: fonttools/fonttools

Issue:
Make the upcoming glyf table with cubics opt-in, behind a flag
Now that a glyf table with support for cubic curves is on the roadmap for OpenType 2.0 and that fontTools already supports that output, it can happen that such a glyf table gets produced inadvertently and results in a font that doesn't work except in bleeding-edge environments that run the latest Harfbuzz.

Previously, trying to introduce cubic béziers into the glyf table would crash, and I think it should keep crashing by default for the time being, until at least the spec of the new table format is officially released and implementers can catch up. The new format could be behind a flag, either on fontTools using the config system, or specifically on ttGlyphPens as suggested by @anthrotype . 

We'll look into reproducing this issue and possibly propose a PR.


Discussion:
More context from @anthrotype 
> fontmake or ufo2ft would not currently let you build such cubic ttf fonts, because cu2qu is always run for ttfs at the moment. it's only if you build the fonts yourself (e.g. fontBuilder) using fonttools API that you may incur in this. [...] the bar for that is relatively high.

> I think decompiling/compiling glyf with cubic flags should continue to work without flags of sorts. but building new cubic glyf glyphs shouhld be guarded by a flag so it doesn't happen accidentally.
Note that you can hack test fonts relatively easily, including variable:

1. Prepare your `.designspace` file and `.ufo` sources with cubic glyphs as normal.
2. In all `.glif` files, search & replace all `"curve"` with `"qcurve"`.
3. Use `fontmake` to create a TrueType font from the sources:  
`$ fontmake -o variable -m <yourfont.designspace>`
4. Write a tool that processes binary TTFs to:
 * for all simple glyphs, for all off-curve points, set flags bit 7
 * update `head.glyphDataFormat` to 1

This is based on the technique ([Building ttf-cubic fonts](https://github.com/Lorp/samsa/blob/master/docs/technote-ttf-cubic.md#building-ttf-cubic-fonts)) that I used to make experimental "ttf-cubic" fonts.
FWIW for Google Fonts use we'd much rather have an opt-in to any capability to produce off-spec fonts. If my icon compiler (using fontbuilder) forgets to cu2qu I want an error (as was the case before), not the silent production of a binary that won't work when I deploy it.

EDIT: an explicit opt-out would be better than nothing, but it still leaves me open to someone forgetting to add it and getting a nasty, non-obvious, surprise.
maybe we can leave the TTGlyphPen as it is and just need to change the FontBuilder. We can add an option to FontBuilder constructor with the `glyphDataFormat=0` defaulting to the currently spec'ed format (0, no cubics) and that's going to be used in the `setupHead` method as well; then if one passes cubic TTGlyphs to setupGlyf method and did not explicitly request `glyphDataFormat=1` when making the builder, then it means they didn't want to do it intentionally and we let it fail with an error.
> maybe we can leave the TTGlyphPen as it is and just need to change the FontBuilder. We can add an option to FontBuilder constructor with the `glyphDataFormat=0` defaulting to the currently spec'ed format (0, no cubics) and that's going to be used in the `setupHead` method as well; then if one passes cubic TTGlyphs to setupGlyf method and did not explicitly request `glyphDataFormat=1` when making the builder, then it means they didn't want to do it intentionally and we let it fail with an error.

SGTM.

Resolving patch:
diff --git a/Lib/fontTools/fontBuilder.py b/Lib/fontTools/fontBuilder.py
--- a/Lib/fontTools/fontBuilder.py
+++ b/Lib/fontTools/fontBuilder.py
@@ -131,6 +131,7 @@ def drawTestGlyph(pen):
 
 from .ttLib import TTFont, newTable
 from .ttLib.tables._c_m_a_p import cmap_classes
+from .ttLib.tables._g_l_y_f import flagCubic
 from .misc.timeTools import timestampNow
 import struct
 from collections import OrderedDict
@@ -319,7 +320,7 @@ def drawTestGlyph(pen):
 
 
 class FontBuilder(object):
-    def __init__(self, unitsPerEm=None, font=None, isTTF=True):
+    def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0):
         """Initialize a FontBuilder instance.
 
         If the `font` argument is not given, a new `TTFont` will be
@@ -327,15 +328,31 @@ def __init__(self, unitsPerEm=None, font=None, isTTF=True):
         the font will be a glyf-based TTF; if `isTTF` is False it will be
         a CFF-based OTF.
 
+        The `glyphDataFormat` argument corresponds to the `head` table field
+        that defines the format of the TrueType `glyf` table (default=0).
+        TrueType glyphs historically can only contain quadratic splines and static
+        components, but there's a proposal to add support for cubic Bezier curves as well
+        as variable composites/components at
+        https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md
+        You can experiment with the new features by setting `glyphDataFormat` to 1.
+        A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added
+        that contain cubic splines or varcomposites. This is to prevent accidentally
+        creating fonts that are incompatible with existing TrueType implementations.
+
         If `font` is given, it must be a `TTFont` instance and `unitsPerEm`
-        must _not_ be given. The `isTTF` argument will be ignored.
+        must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored.
         """
         if font is None:
             self.font = TTFont(recalcTimestamp=False)
             self.isTTF = isTTF
             now = timestampNow()
             assert unitsPerEm is not None
-            self.setupHead(unitsPerEm=unitsPerEm, created=now, modified=now)
+            self.setupHead(
+                unitsPerEm=unitsPerEm,
+                create=now,
+                modified=now,
+                glyphDataFormat=glyphDataFormat,
+            )
             self.setupMaxp()
         else:
             assert unitsPerEm is None
@@ -631,7 +648,7 @@ def setupCFF2Regions(self, regions):
         for fontDict in topDict.FDArray:
             fontDict.Private.vstore = vstore
 
-    def setupGlyf(self, glyphs, calcGlyphBounds=True):
+    def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True):
         """Create the `glyf` table from a dict, that maps glyph names
         to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
         as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
@@ -639,8 +656,26 @@ def setupGlyf(self, glyphs, calcGlyphBounds=True):
         If `calcGlyphBounds` is True, the bounds of all glyphs will be
         calculated. Only pass False if your glyph objects already have
         their bounding box values set.
+
+        If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains
+        cubic curves or is a variable composite but head.glyphDataFormat=0.
+        Set it to False to skip the check if you know in advance all the glyphs are
+        compatible with the specified glyphDataFormat.
         """
         assert self.isTTF
+
+        if validateGlyphFormat and self.font["head"].glyphDataFormat == 0:
+            for name, g in glyphs.items():
+                if g.isVarComposite():
+                    raise ValueError(
+                        f"Glyph {name!r} is a variable composite, but glyphDataFormat=0"
+                    )
+                elif g.numberOfContours > 0 and any(f & flagCubic for f in g.flags):
+                    raise ValueError(
+                        f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; "
+                        "either convert to quadratics with cu2qu or set glyphDataFormat=1."
+                    )
+
         self.font["loca"] = newTable("loca")
         self.font["glyf"] = newTable("glyf")
         self.font["glyf"].glyphs = glyphs


Test patch:
diff --git a/Tests/fontBuilder/fontBuilder_test.py b/Tests/fontBuilder/fontBuilder_test.py
--- a/Tests/fontBuilder/fontBuilder_test.py
+++ b/Tests/fontBuilder/fontBuilder_test.py
@@ -137,6 +137,29 @@ def test_build_ttf(tmpdir):
     _verifyOutput(outPath)
 
 
+def test_build_cubic_ttf(tmp_path):
+    pen = TTGlyphPen(None)
+    pen.moveTo((100, 100))
+    pen.curveTo((200, 200), (300, 300), (400, 400))
+    pen.closePath()
+    glyph = pen.glyph()
+    glyphs = {"A": glyph}
+
+    # cubic outlines are not allowed in glyf table format 0
+    fb = FontBuilder(1000, isTTF=True, glyphDataFormat=0)
+    with pytest.raises(
+        ValueError, match="Glyph 'A' has cubic Bezier outlines, but glyphDataFormat=0"
+    ):
+        fb.setupGlyf(glyphs)
+    # can skip check if feeling adventurous
+    fb.setupGlyf(glyphs, validateGlyphFormat=False)
+
+    # cubics are (will be) allowed in glyf table format 1
+    fb = FontBuilder(1000, isTTF=True, glyphDataFormat=1)
+    fb.setupGlyf(glyphs)
+    assert "A" in fb.font["glyf"].glyphs
+
+
 def test_build_otf(tmpdir):
     outPath = os.path.join(str(tmpdir), "test.otf")