### UFO lib Configuration Examples
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Examples of how to configure ufo2ft behavior using the UFO's lib.plist.
```APIDOC
## UFO lib Configuration
### Glyph Filters
```python
ufo.lib["com.github.googlei18n.ufo2ft.filters"] = [
{"name": "removeOverlaps", "kwargs": {"backend": "pathops"}}
]
```
### Feature Writers
```python
ufo.lib["com.github.googlei18n.ufo2ft.featureWriters"] = [
{"class": "KernFeatureWriter", "options": {"ignoreMarks": True}}
]
```
### Skipped Export Glyphs
```python
ufo.lib["public.skipExportGlyphs"] = ["space.alt"]
```
```
--------------------------------
### Install ufo2ft
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Install the ufo2ft library using pip.
```bash
pip install ufo2ft
```
--------------------------------
### Reading UFO Configuration Example
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
This example demonstrates how to read configuration settings like filters, production name usage, and color palettes from a UFO font's lib.plist using defcon and ufo2ft constants.
```python
from defcon import Font
from ufo2ft.constants import (
FILTERS_KEY,
FEATURE_WRITERS_KEY,
USE_PRODUCTION_NAMES,
COLOR_PALETTES_KEY,
)
ufo = Font("MyFont.ufo")
# Check configuration
if FILTERS_KEY in ufo.lib:
filters = ufo.lib[FILTERS_KEY]
print(f"Found {len(filters)} filters")
if USE_PRODUCTION_NAMES in ufo.lib:
use_prod_names = ufo.lib[USE_PRODUCTION_NAMES]
print(f"Use production names: {use_prod_names}")
if COLOR_PALETTES_KEY in ufo.lib:
palettes = ufo.lib[COLOR_PALETTES_KEY]
print(f"Found {len(palettes)} color palettes")
```
--------------------------------
### Compiling Font Outlines with TTFPreProcessor and OutlineTTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Example demonstrating the process of preprocessing UFO data and compiling it into a TTFont object using TTFPreProcessor and OutlineTTFCompiler.
```python
from defcon import Font
from ufo2ft.outlineCompiler import OutlineTTFCompiler
from ufo2ft.preProcessor import TTFPreProcessor
ufo = Font("MyFont.ufo")
# Preprocess
preprocessor = TTFPreProcessor(ufo)
glyphSet = preprocessor.process()
# Compile outlines
compiler = OutlineTTFCompiler(ufo, glyphSet=glyphSet)
font = compiler.compile()
print(f"Tables in font: {list(font.keys())}")
```
--------------------------------
### Example Usage of OTFPreProcessor
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Demonstrates how to use the OTFPreProcessor to preprocess a UFO font for OTF compilation, specifying glyphs to skip.
```python
from defcon import Font
from ufo2ft.preProcessor import OTFPreProcessor
ufo = Font("MyFont.ufo")
# Preprocess for OTF compilation
preprocessor = OTFPreProcessor(
ufo,
inplace=False,
skipExportGlyphs={"internal.glyph"},
)
glyphSet = preprocessor.process()
```
--------------------------------
### Compile OTF with KernFeatureWriter
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Example of using KernFeatureWriter programmatically to compile an OTF font with quantization enabled. Ensure defcon and ufo2ft are installed and the UFO font file exists.
```python
from defcon import Font
from ufo2ft import compileOTF
from ufo2ft.featureWriters import KernFeatureWriter
ufo = Font("MyFont-Regular.ufo")
# Use KernFeatureWriter with quantization
writer = KernFeatureWriter(ignoreMarks=True, quantization=1)
otf = compileOTF(ufo, featureWriters=[writer])
otf.save("MyFont-Regular.otf")
```
--------------------------------
### Complete TTF Compilation Pipeline Example
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Shows a full example of compiling a UFO font to TTF using TTFCompiler, including configuration of custom filters and saving the output. This is useful for end-to-end font generation with specific processing steps.
```python
from defcon import Font
from ufo2ft._compilers.ttfCompiler import TTFCompiler
from ufo2ft.filters.removeOverlaps import RemoveOverlapsFilter
ufo = Font("MyFont.ufo")
# Configure compiler with custom filters
compiler = TTFCompiler(
convertCubics=True,
flattenComponents=False,
filters=[
RemoveOverlapsFilter(backend="pathops"),
],
)
# Compile
ttf = compiler.compile(ufo)
# Inspect what happened
print(f"Table tags: {list(ttf.keys())}")
print(f"Glyph count: {len(ttf.getGlyphOrder())}")
# Save
ttf.save("MyFont.ttf")
```
--------------------------------
### Compiling and Using TTFont
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
Example demonstrating how to compile a UFO to a TTFont object, inspect its tables, access glyph order, and save the compiled font to a file or XML.
```python
from ufo2ft import compileTTF
ttf = compileTTF(ufo)
# Check tables
if "glyf" in ttf:
print("TrueType outlines present")
if "CFF " in ttf:
print("CFF outlines present")
# Access glyph order
glyphs = ttf.glyphOrder
print(f"Font has {len(glyphs)} glyphs")
# Access specific table
glyf_table = ttf["glyf"]
post_table = ttf["post"]
# Save to file
ttf.save("output.otf")
# Export to UFO for round-tripping
ttf.saveXML("output.ttx")
```
--------------------------------
### Configure KernFeatureWriter via UFO lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Example of configuring KernFeatureWriter using the UFO lib. This method allows specifying writer options directly within the UFO's metadata.
```python
ufo.lib["com.github.googlei18n.ufo2ft.featureWriters"] = [
{
"class": "KernFeatureWriter",
"options": {
"ignoreMarks": True,
"quantization": 1
}
}
]
```
--------------------------------
### Configuration
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Details all available options for controlling the font compilation process. This includes compiler parameters, UFO lib keys, feature writer and filter configurations, and color font setup.
```APIDOC
## Configuration
### Description
This section outlines all configurable options that control the behavior of the ufo2ft compiler, including parameters, UFO lib keys, and settings for advanced features.
### Compiler Parameters
- `removeOverlaps` (bool): Whether to remove contour overlaps.
- `inplace` (bool): Whether to modify UFO data in-place.
- `skipExportGlyphs` (bool): Whether to skip exporting glyphs.
- ... (other parameters)
### UFO Lib Keys
- `com.github.googlei18n.ufo2ft.*`: Namespace for ufo2ft-specific configurations within the UFO's `lib.plist`.
### Feature Writer and Filter Configuration
- Options for customizing the behavior of loaded feature writers and glyph filters.
### Color Font Setup
- Configuration options for generating color fonts (COLR/CPAL tables).
```
--------------------------------
### Compile OTF with Automatic Feature Generation
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Generate an OpenType font (OTF) with automatic feature generation. This example includes `KernFeatureWriter` and `MarkFeatureWriter`.
```python
from ufo2ft import compileOTF
from ufo2ft.featureWriters import KernFeatureWriter, MarkFeatureWriter
writers = [
KernFeatureWriter(ignoreMarks=True),
MarkFeatureWriter(asciiDigits=True),
]
otf = compileOTF(ufo, featureWriters=writers)
```
--------------------------------
### Compile Single UFO to TTF
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Use this to compile a single UFO font file into a TTF. Ensure the defcon and ufo2ft libraries are installed.
```python
from defcon import Font
from ufo2ft import compileTTF
ufo = Font("Regular.ufo")
ttf = compileTTF(ufo)
ttf.save("Regular.ttf")
```
--------------------------------
### Configure Feature Writers via lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Specify custom feature writers and their options by setting the 'com.github.googlei18n.ufo2ft.featureWriters' key in the UFO's lib. This example configures the 'KernFeatureWriter' to ignore marks.
```python
ufo.lib["com.github.googlei18n.ufo2ft.featureWriters"] = [
{"class": "KernFeatureWriter", "options": {"ignoreMarks": True}}
]
```
--------------------------------
### Example: Flatten Component Nesting
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Shows how to apply FlattenComponentsFilter to compileTTF to ensure glyphs have at most one level of component references. This is useful for simplifying glyph structures.
```python
from ufo2ft import compileTTF
from ufo2ft.filters.flattenComponents import FlattenComponentsFilter
# Flatten component nesting
filters = [FlattenComponentsFilter()]
ttf = compileTTF(ufo, filters=filters)
```
--------------------------------
### Example: InvalidFontData due to Missing Component
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
Illustrates a scenario where InvalidFontData is raised because a component references a non-existent glyph. The code shows how to fix this by defining the missing glyph first.
```python
# This will raise InvalidFontData
ufo["acuteaccent"].appendComponent("nonexistentglyph", (100, 0))
ttf = compileTTF(ufo) # Raises InvalidFontData
```
```python
# Define the component first
missing = ufo.newGlyph("nonexistentglyph")
missing.width = 100
# Then reference it
ufo["acuteaccent"].appendComponent("nonexistentglyph", (100, 0))
```
--------------------------------
### Compile Interpolatable TTFs from DesignSpace Document
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/main-functions.md
This example demonstrates how to load a DesignSpaceDocument, add UFO sources with their respective locations, and then compile them into interpolatable TrueType fonts. The compiled fonts are then saved with a .ttf extension.
```python
from fontTools.designspaceLib import DesignSpaceDocument
from defcon import Font
from ufo2ft import compileInterpolatableTTFsFromDS
# Load DesignSpace and UFOs
ds = DesignSpaceDocument()
ds.addSource(Font("Light.ufo"), location={"Weight": 100})
ds.addSource(Font("Regular.ufo"), location={"Weight": 400})
ds.addSource(Font("Bold.ufo"), location={"Weight": 700})
# Compile masters
compiled_ds = compileInterpolatableTTFsFromDS(ds)
for source in compiled_ds.sources:
ttf = source.font
filename = source.filename or f"{source.filename}"
ttf.save(filename.replace(".ufo", ".ttf"))
```
--------------------------------
### Compile and Save TTF using OutlineTTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Example demonstrating how to use OutlineTTFCompiler to compile a UFO font into a TTF file. It involves pre-processing the UFO, initializing the compiler with specific parameters, compiling the font, and saving the resulting TTF.
```python
from defcon import Font
from ufo2ft.outlineCompiler import OutlineTTFCompiler
from ufo2ft.preProcessor import TTFPreProcessor
ufo = Font("MyFont.ufo")
preprocessor = TTFPreProcessor(ufo)
glyphSet = preprocessor.process()
compiler = OutlineTTFCompiler(
ufo,
glyphSet=glyphSet,
glyphDataFormat=0,
roundCoordinates=True,
dropImpliedOnCurves=False,
)
ttf = compiler.compile()
ttf.save("MyFont.ttf")
```
--------------------------------
### Custom Preprocessing with TTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Utilize TTFCompiler for custom preprocessing pipelines by providing a list of filters. This example demonstrates using RemoveOverlapsFilter with the 'pathops' backend.
```python
from ufo2ft._compilers.ttfCompiler import TTFCompiler
from ufo2ft.filters.removeOverlaps import RemoveOverlapsFilter
ufo = Font("MyFont.ufo")
compiler = TTFCompiler(
filters=[
RemoveOverlapsFilter(backend="pathops"),
]
)
ttf = compiler.compile(ufo)
```
--------------------------------
### Configure UFO Filters via lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Customize glyph filters by setting the 'com.github.googlei18n.ufo2ft.filters' key in the UFO's lib. This example shows how to enable overlap removal using the 'pathops' backend.
```python
ufo.lib["com.github.googlei18n.ufo2ft.filters"] = [
{"name": "removeOverlaps", "kwargs": {"backend": "pathops"}}
]
```
--------------------------------
### Propagate Anchors via Code
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Instantiate and use the PropagateAnchorsFilter directly in your Python code. This example shows how to use a callable function to determine which glyphs to process.
```python
from ufo2ft import compileTTF
from ufo2ft.filters.propagateAnchors import PropagateAnchorsFilter
def include_func(glyph):
if glyph.unicode:
return 0x007F < glyph.unicode < 0x00FF
return False
filters = [PropagateAnchorsFilter(include=include_func)]
ttf = compileTTF(ufo, filters=filters)
```
--------------------------------
### Example: Handle Invalid Font Data
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
Shows how to use a try-except block to catch InvalidFontData errors during TTF compilation. This is useful for validating input UFOs.
```python
from ufo2ft import compileTTF
from ufo2ft.errors import InvalidFontData
try:
ttf = compileTTF(ufo)
except InvalidFontData as e:
print(f"Font data error: {e}")
```
--------------------------------
### Compile Variable TrueType Fonts
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Example of using VariableTTFsCompiler to build variable TrueType fonts from a DesignSpace document. It demonstrates loading the DesignSpace, initializing the compiler with specific options, compiling the fonts, and saving them.
```python
from fontTools.designspaceLib import DesignSpaceDocument
from defcon import Font
from ufo2ft._compilers.variableTTFsCompiler import VariableTTFsCompiler
ds = DesignSpaceDocument.fromfile("MyFont.designspace")
for source in ds.sources:
source.font = Font(source.path)
compiler = VariableTTFsCompiler(
optimizeGvar=True,
variableFontNames=["MyFont-VF"]
)
vfonts = compiler.compile_variable(ds)
for filename, font in vfonts.items():
font.save(filename)
```
--------------------------------
### Generate GPOS Mark Features
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Example of using MarkFeatureWriter to compile GPOS mark features for a UFO font. Specify custom mark glyphs and control ASCII digit handling.
```python
from defcon import Font
from ufo2ft import compileOTF
from ufo2ft.featureWriters import MarkFeatureWriter
ufo = Font("MyFont-Regular.ufo")
writer = MarkFeatureWriter(
marks={"acutecomb", "gravecomb"},
asciiDigits=False
)
otf = compileOTF(ufo, featureWriters=[writer])
otf.save("MyFont-Regular.otf")
```
--------------------------------
### Catch and Handle InvalidFeaturesData Error
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
This Python example demonstrates how to use a try-except block to catch the InvalidFeaturesData error during OTF compilation. It prints informative messages to guide the user on checking their features.fea file for common issues.
```python
from defcon import Font
from ufo2ft import compileOTF
from ufo2ft.errors import InvalidFeaturesData
ufo = Font("MyFont.ufo")
try:
otf = compileOTF(ufo)
except InvalidFeaturesData as e:
print(f"Feature compilation failed:")
print(f" Error: {e}")
print("\nPlease check your features.fea file:")
print(" - All glyphs referenced exist in the font")
print(" - All glyph classes are properly defined")
print(" - Feature syntax is valid Adobe FEA")
print(" - Include file paths are relative to UFO directory")
```
--------------------------------
### Initialize OTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Instantiate OTFCompiler with specific CFF optimization, version, and subroutinizer settings. Requires a defcon Font object.
```python
from defcon import Font
from ufo2ft._compilers.otfCompiler import OTFCompiler
from ufo2ft.constants import CFFOptimization
ufo = Font("MyFont-Regular.ufo")
compiler = OTFCompiler(
optimizeCFF=CFFOptimization.SUBROUTINIZE,
cffVersion=1,
subroutinizer="cffsubr"
)
otf = compiler.compile(ufo)
otf.save("MyFont-Regular.otf")
```
--------------------------------
### Load Filters Programmatically
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Demonstrates loading filters from UFO lib and from a string specification.
```python
def loadFilters(ufo: Font) -> tuple[list[BaseFilter], list[BaseFilter]]
```
```python
def loadFilterFromString(spec: str) -> BaseFilter
```
```python
from ufo2ft.filters import loadFilterFromString
# Load built-in filter
f = loadFilterFromString("RemoveOverlapsFilter()")
# Load from custom module
f = loadFilterFromString("mymodule::MyCustomFilter(param=value)")
```
--------------------------------
### KernFeatureWriter Initialization and Usage
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Demonstrates how to initialize and use the KernFeatureWriter class to compile GPOS kern features into an OpenType font.
```APIDOC
## KernFeatureWriter
**Module:** `ufo2ft.featureWriters.kernFeatureWriter`
Generates kern (GPOS) features from UFO kerning data.
### Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| features | iterable[str] | ["kern"] | Feature codes to generate (usually just "kern"). |
| mode | str | "skip" | "skip" or "append". |
| ignoreMarks | bool | True | Add `ignoreMarks` flag to lookups with base-mark kerning pairs. |
| markGlyphSet | set | None | Glyph names marked as marks (read from GDEF if not provided). |
| quantization | int | None | Round kerning values to nearest multiple of this value. If None, no quantization. |
### Example: Via Code
```python
from defcon import Font
from ufo2ft import compileOTF
from ufo2ft.featureWriters import KernFeatureWriter
ufo = Font("MyFont-Regular.ufo")
# Use KernFeatureWriter with quantization
writer = KernFeatureWriter(ignoreMarks=True, quantization=1)
otf = compileOTF(ufo, featureWriters=[writer])
otf.save("MyFont-Regular.otf")
```
### Example: Via UFO lib
```python
ufo.lib["com.github.googlei18n.ufo2ft.featureWriters"] = [
{
"class": "KernFeatureWriter",
"options": {
"ignoreMarks": True,
"quantization": 1
}
}
]
```
```
--------------------------------
### Override Default Feature Writers
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Pass a custom list of feature writers to compileOTF to override the default set. This example includes KernFeatureWriter and GdefFeatureWriter.
```python
from ufo2ft import compileOTF
from ufo2ft.featureWriters import GdefFeatureWriter, KernFeatureWriter
writers = [
KernFeatureWriter(ignoreMarks=True),
GdefFeatureWriter(),
]
otf = compileOTF(ufo, featureWriters=writers)
```
--------------------------------
### OTFCompiler - Batch Compilation
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Illustrates batch compilation of multiple UFO files into OTF format using OTFCompiler with specific optimization and glyph skipping settings.
```APIDOC
## OTFCompiler for Batch Compilation
### Description
This pattern demonstrates how to use the `OTFCompiler` for batch compilation of multiple UFO files into the OTF format, allowing for settings like CFF optimization and skipping specific glyphs.
### Method
`OTFCompiler.compile`
### Parameters
- `optimizeCFF` (CFFOptimization): Specifies the CFF optimization level.
- `skipExportGlyphs` (set): A set of glyph names to skip during export.
### Request Example
```python
from pathlib import Path
from ufo2ft._compilers.otfCompiler import OTFCompiler
from ufo2ft.constants import CFFOptimization
from defcon import Font
compiler = OTFCompiler(
optimizeCFF=CFFOptimization.SUBROUTINIZE,
skipExportGlyphs={"internal.glyph"}
)
for ufo_path in Path(".").glob("*.ufo"):
ufo = Font(ufo_path)
otf = compiler.compile(ufo)
otf.save(ufo_path.with_suffix(".otf"))
```
```
--------------------------------
### Custom Feature Compilation with TTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Integrate custom feature writers into TTFCompiler for advanced feature generation. This example includes KernFeatureWriter and MarkFeatureWriter with specific configurations.
```python
from ufo2ft._compilers.ttfcompiler import TTFCompiler
from ufo2ft.featureWriters import KernFeatureWriter, MarkFeatureWriter
compiler = TTFCompiler(
featureWriters=[
KernFeatureWriter(ignoreMarks=True, quantization=1),
MarkFeatureWriter(marks={"acute", "grave"}),
]
)
ttf = compiler.compile(ufo)
```
--------------------------------
### OutlineTTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Initializes the OutlineTTFCompiler with UFO font data and glyph set, and compiles TrueType outlines.
```APIDOC
## OutlineTTFCompiler
### Description
Compiler for TrueType outlines (glyf table).
### Parameters
- **glyphDataFormat** (int, optional, default=0): glyf table format: 0 (v0, all quadratic) or 1 (v1, mixed).
- **roundCoordinates** (bool, optional, default=True): Round glyph coordinates to integers. Set False for variable fonts.
- **dropImpliedOnCurves** (bool, optional, default=False): Remove on-curve points between two off-curves.
- **autoUseMyMetrics** (bool, optional, default=True): Set useMyMetrics flag on components.
### Tables Generated
- `glyf`: TrueType glyph outlines
- `loca`: Glyph location table
- `head`, `hhea`, `maxp`, `hmtx`, `vmtx`, `vhea`, `post`, `OS/2`, `name`, `cmap`
### Example
```python
from defcon import Font
from ufo2ft.outlineCompiler import OutlineTTFCompiler
from ufo2ft.preProcessor import TTFPreProcessor
ufo = Font("MyFont.ufo")
preprocessor = TTFPreProcessor(ufo)
glyphSet = preprocessor.process()
compiler = OutlineTTFCompiler(
ufo,
glyphSet=glyphSet,
glyphDataFormat=0,
roundCoordinates=True,
dropImpliedOnCurves=False,
)
ttf = compiler.compile()
ttf.save("MyFont.ttf")
```
```
--------------------------------
### Remove Overlaps using pathops backend
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Apply the RemoveOverlapsFilter to a UFO object to remove overlapping contours. This example specifically uses the 'pathops' backend for the operation.
```python
from ufo2ft import compileTTF
from ufo2ft.filters.removeOverlaps import RemoveOverlapsFilter
# Remove overlaps using pathops backend
filters = [RemoveOverlapsFilter(backend="pathops")]
ttf = compileTTF(ufo, filters=filters)
```
--------------------------------
### Configure Color Layers with colorLayerMapping in ufo2ft
Source: https://github.com/googlefonts/ufo2ft/blob/main/README.rst
Use the 'com.github.googlei18n.ufo2ft.colorLayerMapping' key in the font lib to define color layers. This maps layer names to palette color indices and is used by ufo2ft to set up the COLR table.
```xml
com.github.googlei18n.ufo2ft.colorLayerMapping
color.1
1
color.2
0
```
--------------------------------
### Example: Handle Invalid DesignSpace Data
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
Shows how to catch InvalidDesignSpaceData errors when compiling variable TTFs. This is helpful for validating DesignSpace files and axis configurations.
```python
from ufo2ft import compileVariableTTFs
from ufo2ft.errors import InvalidDesignSpaceData
try:
vfonts = compileVariableTTFs(designspace)
except InvalidDesignSpaceData as e:
print(f"DesignSpace error: {e}")
```
--------------------------------
### UFO2FT Documentation File Dependencies
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/MANIFEST.md
Lists the main markdown files and their relationships within the UFO2FT documentation. This helps understand the organization and interlinking of API references, types, configuration, and error documentation.
```markdown
API_REFERENCE_INDEX.md
├── README.md (overview)
├── api-reference/main-functions.md (compileTTF, compileOTF, etc.)
├── api-reference/filters.md (filter reference)
├── api-reference/feature-writers.md (writer reference)
├── api-reference/compilers.md (compiler classes)
├── api-reference/preprocessors-and-outlines.md (low-level)
├── types.md (type definitions)
├── configuration.md (all options)
└── errors.md (error reference)
```
--------------------------------
### Example: Handle Invalid Features Data
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
Demonstrates catching InvalidFeaturesData errors during OTF compilation. This is useful for debugging feature file syntax and OpenType code.
```python
from ufo2ft import compileOTF
from ufo2ft.errors import InvalidFeaturesData
try:
otf = compileOTF(ufo)
except InvalidFeaturesData as e:
print(f"Feature error: {e}")
```
--------------------------------
### Inject Custom Filters into TTFPreProcessor
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Demonstrates how to mix custom filters with default filters when initializing TTFPreProcessor. Use this to customize the preprocessing stage of UFO to font conversion.
```python
from defcon import Font
from ufo2ft.filters import DecomposeComponentsFilter
from ufo2ft.preProcessor import TTFPreProcessor
ufo = Font("MyFont.ufo")
# Mix custom filters with defaults
filters = [
DecomposeComponentsFilter(pre=True),
..., # Load UFO lib filters here
]
preprocessor = TTFPreProcessor(
ufo,
filters=filters,
)
glyphSet = preprocessor.process()
```
--------------------------------
### Example: Decompose Specific Glyphs
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Demonstrates how to use DecomposeComponentsFilter to decompose only a specified set of glyphs during UFO to TTF compilation. Ensure the filter is passed to the compileTTF function.
```python
from ufo2ft import compileTTF
from ufo2ft.filters.decomposeComponents import DecomposeComponentsFilter
# Decompose only specific glyphs
filters = [DecomposeComponentsFilter(include={"a", "b", "c"})]
ttf = compileTTF(ufo, filters=filters)
```
--------------------------------
### Main Compilation Functions
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/COMPLETION_SUMMARY.txt
These are the primary entry point functions for compiling UFO data into various font formats using the ufo2ft library.
```APIDOC
## compileTTF()
### Description
Compiles UFO data into a TrueType font.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileOTF()
### Description
Compiles UFO data into a CFF-based OpenType font.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileInterpolatableTTFs()
### Description
Compiles multi-master TrueType fonts from UFO data.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileInterpolatableTTFsFromDS()
### Description
Compiles multi-master TrueType fonts from DesignSpace data.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileInterpolatableOTFsFromDS()
### Description
Compiles multi-master CFF-based OpenType fonts from DesignSpace data.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileVariableTTFs()
### Description
Compiles variable TrueType fonts.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileVariableTTF()
### Description
Compiles a single variable TrueType font (legacy).
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileVariableCFF2s()
### Description
Compiles variable CFF2 fonts.
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
## compileVariableCFF2()
### Description
Compiles a single variable CFF2 font (legacy).
### Method
(Not specified, assumed to be a Python function call)
### Endpoint
(Not applicable, Python function)
### Parameters
(Details not provided in source, but documentation coverage states '40+ parameters for main functions')
### Request Example
(Not applicable, Python function)
### Response
(Details not provided in source, but implies font file output)
```
--------------------------------
### Configure Skipped Export Glyphs via lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Define glyphs to be excluded from export by setting the 'public.skipExportGlyphs' key in the UFO's lib. This example skips the 'space.alt' glyph.
```python
ufo.lib["public.skipExportGlyphs"] = ["space.alt"]
```
--------------------------------
### Initialize TTFPreProcessor with standard parameters
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Use TTFPreProcessor for TrueType-flavored fonts. It includes filters for cubic to quadratic conversion, component decomposition, overlap removal, and contour sorting by default.
```python
from defcon import Font
from ufo2ft.preProcessor import TTFPreProcessor
ufo = Font("MyFont.ufo")
preprocessor = TTFPreProcessor(
ufo,
convertCubics=True,
cubicConversionError=0.001,
flattenComponents=False,
removeOverlaps=True,
)
glyphSet = preprocessor.process()
print(f"Processed {len(glyphSet)} glyphs")
```
--------------------------------
### Catch and Handle InvalidFontData Errors
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
Provides an example of catching the InvalidFontData error during UFO compilation. It prints detailed error messages and suggests common checks for resolving the issue.
```python
from defcon import Font
from ufo2ft import compileTTF
from ufo2ft.errors import InvalidFontData
ufo = Font("MyFont.ufo")
try:
ttf = compileTTF(ufo)
except InvalidFontData as e:
print(f"Compilation failed due to invalid font data:")
print(f" Error: {e}")
print("Please check:")
print(" - All component references point to existing glyphs")
print(" - Glyph names are valid PostScript names")
print(" - Font metrics are properly set")
print(" - Contours are not self-intersecting in problematic ways")
```
--------------------------------
### loadFilters
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Loads filter configurations from the UFO lib's `com.github.googlei18n.ufo2ft.filters` key. It returns a tuple containing lists of pre-filters and post-filters.
```APIDOC
## loadFilters
### Description
Load filter configurations from UFO lib.
### Function Signature
```python
def loadFilters(ufo: Font) -> tuple[list[BaseFilter], list[BaseFilter]]
```
Returns a tuple of (preFilters, postFilters) loaded from `com.github.googlei18n.ufo2ft.filters` lib key.
```
--------------------------------
### Configure Color Layers with colorLayers in ufo2ft
Source: https://github.com/googlefonts/ufo2ft/blob/main/README.rst
Use the 'com.github.googlei18n.ufo2ft.colorLayers' key when color layers are already separate UFO glyphs. This maps base glyph names to an array of color layers, each defined by a glyph name and palette color index.
```xml
com.github.googlei18n.ufo2ft.colorLayers
alef-ar
alef-ar.color0
2
alefHamzaabove-ar
alefHamzaabove-ar.color0
1
alefHamzaabove-ar.color1
2
```
--------------------------------
### Configure Filters in Python Code
Source: https://github.com/googlefonts/ufo2ft/blob/main/README.rst
Set the 'com.github.googlei18n.ufo2ft.filters' key in the UFO's lib dictionary to configure filters programmatically. This allows for dynamic inclusion logic.
```python
from defcon import Font
from ufo2ft import compileOTF
ufo = Font("MyFont-Regular.ufo")
ufo.lib["com.github.googlei18n.ufo2ft.filters"] = [
{"name": "propagateAnchors", "pre": True, "include": ["a", "b"]}
]
otf = compileOTF(ufo)
otf.save("MyFont-Regular.otf")
```
--------------------------------
### Configure Filters in UFO Lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/configuration.md
Store filter configurations directly in the UFO lib for reproducibility. This method is preferred for managing filter settings.
```python
# Good: Configuration in UFO
ufo.lib["com.github.googlei18n.ufo2ft.filters"] = [
{"name": "removeOverlaps", "kwargs": {"backend": "pathops"}}
]
ttf = compileTTF(ufo)
# Also okay: Configuration via code
filters = [RemoveOverlapsFilter(backend="pathops")]
ttf = compileTTF(ufo, filters=filters)
```
--------------------------------
### Handle Syntax Error in Feature File
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
This example demonstrates a syntax error in the features.fea file, specifically a missing semicolon, which leads to an InvalidFeaturesData error during compilation. The solution is to correct the syntax.
```python
# features.fea contains:
# feature kern {
# pos a b -50 # Missing semicolon!
# } kern;
otf = compileOTF(ufo) # Raises InvalidFeaturesData
```
--------------------------------
### Initialize and Use CursFeatureWriter
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Demonstrates how to initialize the CursFeatureWriter and use it to compile a UFO font into an OpenType font with cursive features.
```python
from defcon import Font
from ufo2ft import compileOTF
from ufo2ft.featureWriters import CursFeatureWriter
ufo = Font("MyFont-Regular.ufo")
writer = CursFeatureWriter()
otf = compileOTF(ufo, featureWriters=[writer])
otf.save("MyFont-Regular.otf")
```
--------------------------------
### Compile CFF Outlines with OutlineOTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Use OutlineOTFCompiler to compile CFF outlines from a UFO font. Specify CFF version and rounding tolerance. Requires OTFPreProcessor to prepare the glyph set.
```python
from defcon import Font
from ufo2ft.outlineCompiler import OutlineOTFCompiler
from ufo2ft.preProcessor import OTFPreProcessor
ufo = Font("MyFont.ufo")
preprocessor = OTFPreProcessor(ufo)
glyphSet = preprocessor.process()
compiler = OutlineOTFCompiler(
ufo,
glyphSet=glyphSet,
cffVersion=1,
roundTolerance=0.5,
)
otf = compiler.compile()
otf.save("MyFont.otf")
```
--------------------------------
### Handle Undefined Glyph in Feature
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
This example illustrates a common scenario where an InvalidFeaturesData error is raised because a feature references a glyph that does not exist in the font. The solution involves defining the glyph or removing the reference.
```python
# features.fea contains:
# feature kern {
# pos a b -50;
# pos undefined_glyph c -50; # 'undefined_glyph' doesn't exist
# } kern;
otf = compileOTF(ufo) # Raises InvalidFeaturesData
```
--------------------------------
### Apply CubicToQuadraticFilter via UFO lib
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/filters.md
Demonstrates how to apply the CubicToQuadraticFilter by configuring it within the UFO lib's 'com.github.googlei18n.ufo2ft.filters' key. This method is useful for applying filters without direct code instantiation.
```python
from defcon import Font
from ufo2ft import compileTTF
ufo = Font("MyFont.ufo")
ufo.lib["com.github.googlei18n.ufo2ft.filters"] = [
{
"name": "cubicToQuadratic",
"pre": False,
"conversionError": 0.001,
"reverseDirection": True,
}
]
ttf = compileTTF(ufo)
```
--------------------------------
### Catch and Handle InvalidDesignSpaceData Error
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
This example demonstrates how to use a try-except block to catch the `InvalidDesignSpaceData` error during variable font compilation. It prints a user-friendly message and provides guidance on checking the DesignSpace configuration.
```python
from fontTools.designspaceLib import DesignSpaceDocument
from defcon import Font
from ufo2ft import compileVariableTTFs
from ufo2ft.errors import InvalidDesignSpaceData
ds = DesignSpaceDocument()
# Add sources with UFOs loaded
try:
vfonts = compileVariableTTFs(ds)
except InvalidDesignSpaceData as e:
print(f"Variable font compilation failed:")
print(f" Error: {e}")
print("\nPlease check your DesignSpace:")
print(" - All sources have .font attribute set to loaded UFOs")
print(" - Master outlines are compatible (same contour structure)")
print(" - Default source location is defined")
print(" - Axis values are consistent")
```
--------------------------------
### BasePreProcessor
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/preprocessors-and-outlines.md
Abstract base class for single-UFO preprocessing. It prepares glyphs by applying filters, decomposing components, and removing overlaps.
```APIDOC
## BasePreProcessor
### Description
Abstract base class for single-UFO preprocessing. It prepares glyphs for outline compilation by applying filters, decomposing components, and removing overlaps.
### Module
`ufo2ft.preProcessor`
### Parameters
#### Parameters
- **ufo** (Font) - Required - The UFO to preprocess.
- **inplace** (bool) - Optional - Modify UFO directly (True) or copy glyphs (False). Defaults to False.
- **layerName** (str) - Optional - Process specific layer instead of default. Defaults to None.
- **skipExportGlyphs** (set) - Optional - Glyph names to exclude from export. Defaults to None.
- **preliminaryOpenTypeCategories** (dict) - Optional - Pre-computed OpenType glyph categories. Defaults to None.
- **filters** (list) - Optional - Custom filter instances. Can include ellipsis (`...`) to mix with UFO lib filters. Defaults to None.
### Methods
#### initDefaultFilters(**kwargs) -> list[BaseFilter]
Create default filter set for this preprocessor. Subclasses override to define defaults.
#### process() -> _GlyphSet
Apply pre-filters, default filters, and post-filters in order. Returns modified glyph set.
### Example
```python
from defcon import Font
from ufo2ft.preProcessor import OTFPreProcessor
ufo = Font("MyFont.ufo")
# Preprocess for OTF compilation
preprocessor = OTFPreProcessor(
ufo,
inplace=False,
skipExportGlyphs={"internal.glyph"},
)
glyphSet = preprocessor.process()
```
```
--------------------------------
### Example: InvalidFontData due to Invalid Glyph Name
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
Demonstrates how an invalid glyph name (too long or containing invalid characters) can trigger an InvalidFontData error. The solution shows how to create a valid glyph name.
```python
# Too long or invalid characters
ufo.newGlyph("This is a very long glyph name with spaces and numbers 123")
ttf = compileTTF(ufo) # Raises InvalidFontData
```
```python
ufo.newGlyph("VeryLongGlyphNameWithNumbers.123") # Valid
```
--------------------------------
### Compile Font with CFF Optimization
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/types.md
Demonstrates how to use the CFFOptimization enum to control CFF optimization during OTF compilation. Boolean values can also be used as shortcuts.
```python
from ufo2ft import compileOTF
from ufo2ft.constants import CFFOptimization
# No optimization
otf = compileOTF(ufo, optimizeCFF=CFFOptimization.NONE)
# Only specialization
otf = compileOTF(ufo, optimizeCFF=CFFOptimization.SPECIALIZE)
# Both (default)
otf = compileOTF(ufo, optimizeCFF=CFFOptimization.SUBROUTINIZE)
# Using boolean value
otf = compileOTF(ufo, optimizeCFF=True) # Equivalent to SUBROUTINIZE
otf = compileOTF(ufo, optimizeCFF=False) # Equivalent to NONE
```
--------------------------------
### Handle Incompatible Outlines Error
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/errors.md
This example illustrates a scenario that triggers `InvalidDesignSpaceData` due to incompatible outlines between master UFOs. It sets up two sources with potentially different glyph structures and shows the expected error.
```python
# Light.ufo has "A" with 2 contours
# Bold.ufo has "A" with 3 contours (or as components)
ds = DesignSpaceDocument()
ds.addSource(Font("Light.ufo"), location={"Weight": 100})
ds.addSource(Font("Bold.ufo"), location={"Weight": 700})
vfonts = compileVariableTTFs(ds) # Raises InvalidDesignSpaceData
```
--------------------------------
### Run fontmake for UFO compilation
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/API_REFERENCE_INDEX.md
Use fontmake to compile UFO files into OTF or TTF formats, or to build variable fonts from designspaces.
```bash
fontmake -u MyFont.ufo -o otf
```
```bash
fontmake -u MyFont.ufo -o ttf
```
```bash
fontmake MyFont.designspace -o variable
```
--------------------------------
### Compile UFO to OTF Font
Source: https://github.com/googlefonts/ufo2ft/blob/main/README.rst
Use compileOTF to generate an OpenType font binary from a UFO font object. Ensure defcon and ufo2ft are imported.
```python
from defcon import Font
from ufo2ft import compileOTF
ufo = Font('MyFont-Regular.ufo')
otf = compileOTF(ufo)
otf.save('MyFont-Regular.otf')
```
--------------------------------
### Compile UFO to TTF using TTFCompiler
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/compilers.md
Demonstrates how to instantiate and use the TTFCompiler to convert a UFO font file into a TrueType-flavored OpenType font. Custom compilation parameters like cubicConversionError and flattenComponents can be specified.
```python
from defcon import Font
from ufo2ft._compilers.ttfCompiler import TTFCompiler
ufo = Font("MyFont-Regular.ufo")
compiler = TTFCompiler(
convertCubics=True,
cubicConversionError=0.001,
flattenComponents=False
)
ttf = compiler.compile(ufo)
ttf.save("MyFont-Regular.ttf")
```
--------------------------------
### Configure fontTools Tables
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/configuration.md
Pass fontTools configuration via the `ftConfig` parameter to specify which tables to include during compilation.
```python
from ufo2ft import compileTTF
ttf = compileTTF(
ufo,
ftConfig={
"tables": ["glyf", "head", "hhea", "hmtx", "maxp", "post"],
# fontTools-specific options
}
)
```
--------------------------------
### Configure Color Font Layers
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/configuration.md
Map glyph names to color layer definitions and palette indices for COLR/CPAL color fonts.
```python
ufo.lib["com.github.googlei18n.ufo2ft.colorLayers"] = {
"emoji_base": [
["emoji_base.layer0", 0], # [glyph_name, palette_index]
["emoji_base.layer1", 1]
]
}
```
--------------------------------
### Load Feature Writer from String Specification
Source: https://github.com/googlefonts/ufo2ft/blob/main/_autodocs/api-reference/feature-writers.md
Load a feature writer by providing a string specification. This can include custom modules and options. The format is `[module::]ClassName[(key1=value1, key2=value2)]`.
```python
from ufo2ft.featureWriters import loadFeatureWriterFromString
# Load built-in writer
writer = loadFeatureWriterFromString("KernFeatureWriter(ignoreMarks=False)")
# Load from custom module
writer = loadFeatureWriterFromString("mymodule::MyWriter(option=value)")
```
--------------------------------
### Configure Filters in UFO lib.plist
Source: https://github.com/googlefonts/ufo2ft/blob/main/README.rst
Add 'com.github.googlei18n.ufo2ft.filters' to the UFO's lib.plist to modify glyphs. Filters can run before or after composite glyph decomposition.
```xml
com.github.googlei18n.ufo2ft.filters
name
propagateAnchors
pre
include
a
b
```