API Reference
Core Objects
Font
- class ufoLib2.objects.Font(*, layers: LayerSet | Iterable[Layer] = NOTHING, info: Info | Mapping[str, Any] = NOTHING, features: Features | str = NOTHING, groups: Dict[str, List[str]] = NOTHING, kerning: Mapping[Tuple[str, str], float] = NOTHING, lib: Mapping[str, Any] = NOTHING, data: DataSet | MutableMapping[str, bytes] = NOTHING, images: ImageSet | MutableMapping[str, bytes] = NOTHING, tempLib: Mapping[str, Any] = NOTHING)[source]
A data class representing a single Unified Font Object (UFO).
Font uses
fontTools.ufoLib.UFOReader
andfontTools.ufoLib.UFOWriter
to read and write UFO data from and to disk. It will default to reading lazily, loading glyphs, data and images as they are accessed. Copying a font implicitly loads everything eagerly before.The data model is formally specified at http://unifiedfontobject.org/versions/ufo3/index.html.
- Parameters:
layers (LayerSet) – A mapping of layer names to Layer objects.
info (Info) – The font Info object.
features (Features) – The font Features object.
groups (Dict[str, List[str]]) – A mapping of group names to a list of glyph names.
kerning (Dict[Tuple[str, str], float]) – A mapping of a tuple of first and second kerning pair to a kerning value.
lib (Dict[str, Any]) – A mapping of keys to arbitrary values.
data (DataSet) – A mapping of data file paths to arbitrary data.
images (ImageSet) – A mapping of image file paths to arbitrary image data.
tempLib (Dict[str, Any]) – A temporary mapping of keys to arbitrary values which unlike lib are not saved to disk.
- Behavior:
The Font object has some dict-like behavior for quick access to glyphs on the the default layer. For example, to get a glyph by name from the default layer:
glyph = font["aGlyphName"]
To iterate over all glyphs in the default layer:
for glyph in font: pass
To get the number of glyphs in the default layer:
glyphCount = len(font)
To find out if a font contains a particular glyph in the default layer by name:
exists = "aGlyphName" in font
To remove a glyph from the default layer by name:
del font["aGlyphName"]
To replace a glyph in the default layer with another
Glyph
object:font["aGlyphName"] = otherGlyph
To copy a font:
import copy fontCopy = copy.deepcopy(font)
Layers behave the same, for when you’re working on something other than the default layer.
- addGlyph(glyph: Glyph) None [source]
Appends glyph object to the default layer unless its name is already taken.
Note
Call the method on the layer directly if you want to overwrite entries with the same name or append copies of the glyph.
- appendGuideline(guideline: Guideline | Mapping[str, Any]) None [source]
Appends a guideline to the list of the font’s global guidelines.
Creates the global guideline list unless it already exists.
- Parameters:
guideline – A
Guideline
object or a mapping for the Guideline constructor.
- property bounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the default layer, taking the actual contours into account.
For defcon API compatibility only.
- close() None [source]
Closes the UFOReader if it still exists to finalize any outstanding file operations.
- property controlPointBounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking only the control points into account.
For defcon API compatibility only.
- get(name: str, default: T | None = None) T | Glyph | None [source]
Return the
Glyph
object for name if it is present in the default layer, otherwise returndefault
.
- property glyphOrder: list[str]
The font’s glyph order.
See http://unifiedfontobject.org/versions/ufo3/lib.plist/#publicglyphorder for semantics.
- Getter:
Return the font’s glyph order, if it is set in lib, or an empty list.
Note
The getter always returns a new list, modifications to it do not change the lib content.
- Setter:
Sets the font’s glyph order. If
value
is None or an empty list, the glyph order key will be deleted from the lib if it exists.
- groups: Dict[str, List[str]]
A mapping of group names to a list of glyph names.
- Type:
Dict[str, List[str]]
- property guidelines: list[Guideline]
The font’s global guidelines.
- Getter:
Returns the font’s global guidelines or an empty list.
- Setter:
- Appends the list of Guidelines to the global Guidelines.
XXX Should it replace them?
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- property kerning: Kerning
- property lib: Lib
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- newGlyph(name: str) Glyph [source]
Creates and returns new
Glyph
object in default layer with name.
- newLayer(name: str, **kwargs: Any) Layer [source]
Creates and returns a new
Layer
.- Parameters:
name – The name of the new layer.
kwargs – The arguments passed to the Layer object constructor.
- objectLib(object: HasIdentifier) dict[str, Any] [source]
Return the lib for an object with an identifier, as stored in a font’s lib.
If the object does not yet have an identifier, a new one is assigned to it. If the font lib does not yet contain the object’s lib, a new one is inserted and returned.
>>> from ufoLib2.objects import Font, Guideline >>> font = Font() >>> font.guidelines = [Guideline(x=100)] >>> guideline_lib = font.objectLib(font.guidelines[0]) >>> guideline_lib["com.test.foo"] = 1234 >>> guideline_id = font.guidelines[0].identifier >>> assert guideline_id is not None >>> assert font.lib["public.objectLibs"][guideline_id] is guideline_lib
- classmethod open(path: str | bytes | PathLike[str] | PathLike[bytes], lazy: bool = True, validate: bool = True) Font [source]
Instantiates a new Font object from a path to a UFO.
- Parameters:
path – The path to the UFO to load.
lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.
validate – If True, enable UFO data model validation during loading. If False, load whatever is deserializable.
- property path: str | bytes | PathLike[str] | PathLike[bytes] | None
Return the path of the UFO, if it was set, or None.
- classmethod read(reader: UFOReader, lazy: bool = True) Font [source]
Instantiates a Font object from a
fontTools.ufoLib.UFOReader
.- Parameters:
path – The path to the UFO to load.
lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.
- property reader: UFOReader | None
Returns the underlying
fontTools.ufoLib.UFOReader
.
- renameGlyph(name: str, newName: str, overwrite: bool = False) None [source]
Renames a
Glyph
object in the default layer.- Parameters:
name – The old name.
newName – The new name.
overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old
Glyph
object.
- renameLayer(name: str, newName: str, overwrite: bool = False) None [source]
Renames a
Layer
.- Parameters:
name – The old name.
newName – The new name.
overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old
Layer
object.
- save(path: str | bytes | PathLike[str] | PathLike[bytes] | FS | None = None, formatVersion: int = 3, structure: UFOFileStructure | None = None, overwrite: bool = False, validate: bool = True) None [source]
Saves the font to
path
.- Parameters:
path – The target path. If it is None, the path from the last save (except when that was a
fs.base.FS
) or when the font was first opened will be used.formatVersion – The version to save the UFO as. Only version 3 is supported currently.
structure (fontTools.ufoLib.UFOFileStructure) – How to store the UFO. Can be either None, “zip” or “package”. If None, it tries to use the same structure as the original UFO at the output path. If “zip”, the UFO will be saved as compressed archive. If “package”, it is saved as a regular folder or “package”.
overwrite – If False, raises OSError when the target path exists. If True, overwrites the target path.
validate – If True, will validate the data in Font before writing it out. If False, will write out whatever is serializable.
- property tempLib: Lib
- unlazify() None [source]
Load all glyphs, data files and images if the Font object loaded them lazily previously.
- write(writer: UFOWriter, saveAs: bool | None = None) None [source]
Writes this Font to a
fontTools.ufoLib.UFOWriter
.- Parameters:
writer – The
fontTools.ufoLib.UFOWriter
to write to.saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.
Info
- class ufoLib2.objects.Info(familyName: str | None = None, styleName: str | None = None, styleMapFamilyName: str | None = None, styleMapStyleName: str | None = None, versionMajor: int | None = None, versionMinor: int | None = None, copyright: str | None = None, trademark: str | None = None, unitsPerEm: float | None = None, descender: float | None = None, xHeight: float | None = None, capHeight: float | None = None, ascender: float | None = None, italicAngle: float | None = None, note: str | None = None, guidelines: Sequence[Guideline | Mapping[str, Any]] | None = None, openTypeGaspRangeRecords: Sequence[GaspRangeRecord | Mapping[str, Any]] | None = None, openTypeHeadCreated: str | None = None, openTypeHeadLowestRecPPEM: int | None = None, openTypeHeadFlags: List[int] | None = None, openTypeHheaAscender: int | None = None, openTypeHheaDescender: int | None = None, openTypeHheaLineGap: int | None = None, openTypeHheaCaretSlopeRise: int | None = None, openTypeHheaCaretSlopeRun: int | None = None, openTypeHheaCaretOffset: int | None = None, openTypeNameDesigner: str | None = None, openTypeNameDesignerURL: str | None = None, openTypeNameManufacturer: str | None = None, openTypeNameManufacturerURL: str | None = None, openTypeNameLicense: str | None = None, openTypeNameLicenseURL: str | None = None, openTypeNameVersion: str | None = None, openTypeNameUniqueID: str | None = None, openTypeNameDescription: str | None = None, openTypeNamePreferredFamilyName: str | None = None, openTypeNamePreferredSubfamilyName: str | None = None, openTypeNameCompatibleFullName: str | None = None, openTypeNameSampleText: str | None = None, openTypeNameWWSFamilyName: str | None = None, openTypeNameWWSSubfamilyName: str | None = None, openTypeNameRecords: Sequence[NameRecord | Mapping[str, Any]] | None = None, openTypeOS2WidthClass: int | None = None, openTypeOS2WeightClass: int | None = None, openTypeOS2Selection: List[int] | None = None, openTypeOS2VendorID: str | None = None, openTypeOS2Panose: List[int] | None = None, openTypeOS2FamilyClass: List[int] | None = None, openTypeOS2UnicodeRanges: List[int] | None = None, openTypeOS2CodePageRanges: List[int] | None = None, openTypeOS2TypoAscender: int | None = None, openTypeOS2TypoDescender: int | None = None, openTypeOS2TypoLineGap: int | None = None, openTypeOS2WinAscent: int | None = None, openTypeOS2WinDescent: int | None = None, openTypeOS2Type: List[int] | None = None, openTypeOS2SubscriptXSize: int | None = None, openTypeOS2SubscriptYSize: int | None = None, openTypeOS2SubscriptXOffset: int | None = None, openTypeOS2SubscriptYOffset: int | None = None, openTypeOS2SuperscriptXSize: int | None = None, openTypeOS2SuperscriptYSize: int | None = None, openTypeOS2SuperscriptXOffset: int | None = None, openTypeOS2SuperscriptYOffset: int | None = None, openTypeOS2StrikeoutSize: int | None = None, openTypeOS2StrikeoutPosition: int | None = None, openTypeVheaVertTypoAscender: int | None = None, openTypeVheaVertTypoDescender: int | None = None, openTypeVheaVertTypoLineGap: int | None = None, openTypeVheaCaretSlopeRise: int | None = None, openTypeVheaCaretSlopeRun: int | None = None, openTypeVheaCaretOffset: int | None = None, postscriptFontName: str | None = None, postscriptFullName: str | None = None, postscriptSlantAngle: float | None = None, postscriptUniqueID: int | None = None, postscriptUnderlineThickness: float | None = None, postscriptUnderlinePosition: float | None = None, postscriptIsFixedPitch: bool | None = None, postscriptBlueValues: List[float] | None = None, postscriptOtherBlues: List[float] | None = None, postscriptFamilyBlues: List[float] | None = None, postscriptFamilyOtherBlues: List[float] | None = None, postscriptStemSnapH: List[float] | None = None, postscriptStemSnapV: List[float] | None = None, postscriptBlueFuzz: float | None = None, postscriptBlueShift: float | None = None, postscriptBlueScale: float | None = None, postscriptForceBold: bool | None = None, postscriptDefaultWidthX: float | None = None, postscriptNominalWidthX: float | None = None, postscriptWeightName: str | None = None, postscriptDefaultCharacter: str | None = None, postscriptWindowsCharacterSet: int | None = None, macintoshFONDName: str | None = None, macintoshFONDFamilyID: int | None = None, year: int | None = None, woffMajorVersion: int | None = None, woffMinorVersion: int | None = None, woffMetadataUniqueID: _T | Mapping[str, Any] | None = None, woffMetadataVendor: _T | Mapping[str, Any] | None = None, woffMetadataCredits: _T | Mapping[str, Any] | None = None, woffMetadataDescription: _T | Mapping[str, Any] | None = None, woffMetadataLicense: _T | Mapping[str, Any] | None = None, woffMetadataCopyright: _T | Mapping[str, Any] | None = None, woffMetadataTrademark: _T | Mapping[str, Any] | None = None, woffMetadataLicensee: _T | Mapping[str, Any] | None = None, woffMetadataExtensions: Sequence[WoffMetadataExtension | Mapping[str, Any]] | None = None)[source]
A data class representing the contents of fontinfo.plist.
The attributes are formally specified at http://unifiedfontobject.org/versions/ufo3/fontinfo.plist/. Value validation is mostly done during saving and loading.
- ascender: float | None
- capHeight: float | None
- copyright: str | None
- descender: float | None
- familyName: str | None
- italicAngle: float | None
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- macintoshFONDFamilyID: int | None
- macintoshFONDName: str | None
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- note: str | None
- property openTypeGaspRangeRecords: list[GaspRangeRecord] | None
- openTypeHeadCreated: str | None
- openTypeHeadFlags: List[int] | None
- openTypeHeadLowestRecPPEM: int | None
- openTypeHheaAscender: int | None
- openTypeHheaCaretOffset: int | None
- openTypeHheaCaretSlopeRise: int | None
- openTypeHheaCaretSlopeRun: int | None
- openTypeHheaDescender: int | None
- openTypeHheaLineGap: int | None
- openTypeNameCompatibleFullName: str | None
- openTypeNameDescription: str | None
- openTypeNameDesigner: str | None
- openTypeNameDesignerURL: str | None
- openTypeNameLicense: str | None
- openTypeNameLicenseURL: str | None
- openTypeNameManufacturer: str | None
- openTypeNameManufacturerURL: str | None
- openTypeNamePreferredFamilyName: str | None
- openTypeNamePreferredSubfamilyName: str | None
- property openTypeNameRecords: list[NameRecord] | None
- openTypeNameSampleText: str | None
- openTypeNameUniqueID: str | None
- openTypeNameVersion: str | None
- openTypeNameWWSFamilyName: str | None
- openTypeNameWWSSubfamilyName: str | None
- openTypeOS2CodePageRanges: List[int] | None
- openTypeOS2FamilyClass: List[int] | None
- openTypeOS2Panose: List[int] | None
- openTypeOS2Selection: List[int] | None
- openTypeOS2StrikeoutPosition: int | None
- openTypeOS2StrikeoutSize: int | None
- openTypeOS2SubscriptXOffset: int | None
- openTypeOS2SubscriptXSize: int | None
- openTypeOS2SubscriptYOffset: int | None
- openTypeOS2SubscriptYSize: int | None
- openTypeOS2SuperscriptXOffset: int | None
- openTypeOS2SuperscriptXSize: int | None
- openTypeOS2SuperscriptYOffset: int | None
- openTypeOS2SuperscriptYSize: int | None
- openTypeOS2Type: List[int] | None
- openTypeOS2TypoAscender: int | None
- openTypeOS2TypoDescender: int | None
- openTypeOS2TypoLineGap: int | None
- openTypeOS2UnicodeRanges: List[int] | None
- openTypeOS2VendorID: str | None
- openTypeOS2WeightClass: int | None
- property openTypeOS2WidthClass: WidthClass | None
- openTypeOS2WinAscent: int | None
- openTypeOS2WinDescent: int | None
- openTypeVheaCaretOffset: int | None
- openTypeVheaCaretSlopeRise: int | None
- openTypeVheaCaretSlopeRun: int | None
- openTypeVheaVertTypoAscender: int | None
- openTypeVheaVertTypoDescender: int | None
- openTypeVheaVertTypoLineGap: int | None
- postscriptBlueFuzz: float | None
- postscriptBlueScale: float | None
- postscriptBlueShift: float | None
- postscriptBlueValues: List[float] | None
- postscriptDefaultCharacter: str | None
- postscriptDefaultWidthX: float | None
- postscriptFamilyBlues: List[float] | None
- postscriptFamilyOtherBlues: List[float] | None
- postscriptFontName: str | None
- postscriptForceBold: bool | None
- postscriptFullName: str | None
- postscriptIsFixedPitch: bool | None
- postscriptNominalWidthX: float | None
- postscriptOtherBlues: List[float] | None
- postscriptSlantAngle: float | None
- postscriptStemSnapH: List[float] | None
- postscriptStemSnapV: List[float] | None
- postscriptUnderlinePosition: float | None
- postscriptUnderlineThickness: float | None
- postscriptUniqueID: int | None
- postscriptWeightName: str | None
- postscriptWindowsCharacterSet: int | None
- classmethod read(reader: UFOReader) Info [source]
Instantiates a Info object from a
fontTools.ufoLib.UFOReader
.
- styleMapFamilyName: str | None
- styleMapStyleName: str | None
- styleName: str | None
- trademark: str | None
- unitsPerEm: float | None
- versionMajor: int | None
- versionMinor: int | None
- woffMajorVersion: int | None
- property woffMetadataCopyright: Any
- property woffMetadataCredits: Any
- property woffMetadataDescription: Any
- property woffMetadataExtensions: Any
- property woffMetadataLicense: Any
- property woffMetadataLicensee: Any
- property woffMetadataTrademark: Any
- property woffMetadataUniqueID: Any
- property woffMetadataVendor: Any
- woffMinorVersion: int | None
- xHeight: float | None
- year: int | None
Features
- class ufoLib2.objects.features.Features(text: str = '')[source]
A data class representing UFO features.
See http://unifiedfontobject.org/versions/ufo3/features.fea/.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- text: str
Holds the content of the features.fea file.
DataSet
- class ufoLib2.objects.dataSet.DataSet(data: Dict[str, bytes] = NOTHING)[source]
Represents a mapping of POSIX filename strings to arbitrary data bytes.
Always use forward slahes (/) as directory separators, even on Windows.
- Behavior:
DataSet behaves like a dictionary of type
Dict[str, bytes]
.>>> from ufoLib2 import Font >>> font = Font() >>> font.data["test.txt"] = b"123" >>> font.data["directory/my_binary_blob.bin"] = b"456" >>> font.data["test.txt"] b'123' >>> del font.data["test.txt"] >>> list(font.data.items()) [('directory/my_binary_blob.bin', b'456')]
- clear() None. Remove all items from D.
- property fileNames: list[str]
Returns a list of filenames in the data store.
- get(k[, d]) D[k] if k in D, else d. d defaults to None.
- items() a set-like object providing a view on D's items
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- keys() a set-like object providing a view on D's keys
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- pop(k[, d]) v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty.
- classmethod read(reader: UFOReader, lazy: bool = True) Tds
Instantiate the data store from a
fontTools.ufoLib.UFOReader
.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
- unlazify() None
Load all data into memory.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values
- write(writer: UFOWriter, saveAs: bool | None = None) None
Write the data store to a
fontTools.ufoLib.UFOWriter
.
LayerSet
- class ufoLib2.objects.LayerSet(layers: ~typing.Dict[str, ~ufoLib2.objects.layer.Layer], defaultLayer: ~ufoLib2.objects.layer.Layer = <ufoLib2.objects.layer.Layer '___UFOLIB2_LAZY_LAYER___' (empty)>)[source]
Represents a mapping of layer names to Layer objects.
See http://unifiedfontobject.org/versions/ufo3/layercontents.plist/ for layer semantics.
- Behavior:
LayerSet behaves partly like a dictionary of type
Dict[str, Layer]
, but creating and loading layers is done through their own methods. Unless the font is loaded eagerly (withlazy=False
), the layer objects and their glyphs are by default only loaded into memory when accessed.To get the number of layers in the font:
layerCount = len(font.layers)
To iterate over all layers:
for layer in font.layers: ...
To check if a specific layer exists:
exists = "myLayerName" in font.layers
To get a specific layer:
font.layers["myLayerName"]
To delete a specific layer:
del font.layers["myLayerName"]
- classmethod from_iterable(value: Iterable[Layer], defaultLayerName: str = 'public.default') LayerSet [source]
Instantiates a LayerSet from an iterable of
Layer
objects.- Parameters:
value – an iterable of
Layer
objects.defaultLayerName – the name of the default layer of the ones in
value
.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- property layerOrder: list[str]
The font’s layer order.
- Getter:
Returns the font’s layer order.
Note
The getter always returns a new list, modifications to it do not change the LayerSet.
- Setter:
Sets the font’s layer order. The set order value must contain all layers that are present in the LayerSet.
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- newLayer(name: str, **kwargs: Any) Layer [source]
Creates and returns a named layer.
- Parameters:
name – The layer name.
kwargs – Arguments passed to the constructor of Layer.
- classmethod read(reader: UFOReader, lazy: bool = True) LayerSet [source]
Instantiates a LayerSet object from a
fontTools.ufoLib.UFOReader
.- Parameters:
path – The path to the UFO to load.
lazy – If True, load glyphs, data files and images as they are accessed. If False, load everything up front.
- renameGlyph(name: str, newName: str, overwrite: bool = False) None [source]
Renames a glyph across all layers.
- Parameters:
name – The old name.
newName – The new name.
overwrite – If False, raises exception if newName is already taken in any layer. If True, overwrites (read: deletes) the old Glyph object.
- renameLayer(name: str, newName: str, overwrite: bool = False) None [source]
Renames a layer.
- Parameters:
name – The old name.
newName – The new name.
overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Layer object.
- write(writer: UFOWriter, saveAs: bool | None = None) None [source]
Writes this LayerSet to a
fontTools.ufoLib.UFOWriter
.- Parameters:
writer (fontTools.ufoLib.UFOWriter) – The writer to write to.
saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.
Layer
- class ufoLib2.objects.Layer(name: str = 'public.default', glyphs: dict[str, Glyph] | Sequence[Glyph] = NOTHING, color: str | None = None, lib: Mapping[str, Any] = NOTHING, default: bool = False, tempLib: Mapping[str, Any] = NOTHING)[source]
Represents a Layer that holds Glyph objects.
See http://unifiedfontobject.org/versions/ufo3/glyphs/layerinfo.plist/.
Note
Various methods that work on Glyph objects take a
layer
attribute, because the UFO data model prescribes that Components within a Glyph object refer to glyphs within the same layer.- Behavior:
Layer behaves partly like a dictionary of type
Dict[str, Glyph]
. Unless the font is loaded eagerly (withlazy=False
), the Glyph objects by default are only loaded into memory when accessed.To get the number of glyphs in the layer:
glyphCount = len(layer)
To iterate over all glyphs:
for glyph in layer: ...
To check if a specific glyph exists:
exists = "myGlyphName" in layer
To get a specific glyph:
layer["myGlyphName"]
To delete a specific glyph:
del layer["myGlyphName"]
- addGlyph(glyph: Glyph) None [source]
Appends glyph object to the this layer unless its name is already taken.
- property bounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking the actual contours into account.
For defcon API compatibility only.
- color: str | None
The color assigned to the layer.
- property controlPointBounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the layer, taking only the control points into account.
For defcon API compatibility only.
- property default: bool
Read-only property. To change the font’s default layer use the LayerSet.defaultLayer property setter.
- get(name: str, default: T | None = None) T | Glyph | None [source]
Return the Glyph object for name if it is present in this layer, otherwise return
default
.
- insertGlyph(glyph: Glyph, name: str | None = None, overwrite: bool = True, copy: bool = True) None [source]
Inserts Glyph object into this layer.
- Parameters:
glyph – The Glyph object.
name – The name of the glyph.
overwrite – If True, overwrites (read: deletes) glyph with the same name if it exists. If False, raises KeyError.
copy – If True, copies the Glyph object before insertion. If False, inserts as is.
- instantiateGlyphObject() Glyph [source]
Returns a new Glyph instance.
For defcon API compatibility only.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- property lib: Lib
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- property name: str
The name of the layer.
- pop(key: str) Glyph [source]
- pop(key: str, default: ~ufoLib2.objects.glyph.Glyph | ~ufoLib2.typing.T = <class 'KeyError'>) Glyph | T
Remove and return glyph from layer.
- Parameters:
key – The name of the glyph.
default – What to return if there is no glyph with the given name.
- classmethod read(name: str, glyphSet: GlyphSet, lazy: bool = True, default: bool = False) Layer [source]
Instantiates a Layer object from a
fontTools.ufoLib.glifLib.GlyphSet
.- Parameters:
name – The name of the layer.
glyphSet – The GlyphSet object to read from.
lazy – If True, load glyphs as they are accessed. If False, load everything up front.
- renameGlyph(name: str, newName: str, overwrite: bool = False) None [source]
Renames a Glyph object in this layer.
- Parameters:
name – The old name.
newName – The new name.
overwrite – If False, raises exception if newName is already taken. If True, overwrites (read: deletes) the old Glyph object.
- property tempLib: Lib
- write(glyphSet: GlyphSet, saveAs: bool = True) None [source]
Write Layer to a
fontTools.ufoLib.glifLib.GlyphSet
.- Parameters:
glyphSet – The GlyphSet object to write to.
saveAs – If True, tells the writer to save out-of-place. If False, tells the writer to save in-place. This affects how resources are cleaned before writing.
Glyph
- class ufoLib2.objects.Glyph(name: str | None = None, width: float = 0, height: float = 0, unicodes: List[int] = NOTHING, image: Image = NOTHING, lib: Mapping[str, Any] = NOTHING, note: str | None = None, anchors: List[Anchor] = NOTHING, components: List[Component] = NOTHING, contours: List[Contour] = NOTHING, guidelines: List[Guideline] = NOTHING, tempLib: Mapping[str, Any] = NOTHING)[source]
Represents a glyph, containing contours, components, anchors and various other bits of data concerning it.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/.
- Behavior:
The Glyph object has list-like behavior. This behavior allows you to interact with contour data directly. For example, to get a particular contour:
contour = glyph[0]
To iterate over all contours:
for contour in glyph: ...
To get the number of contours:
contourCount = len(glyph)
To check if a
Contour
object is in glyph:exists = contour in glyph
To interact with components or anchors in a similar way, use the
Glyph.components
andGlyph.anchors
attributes.
- property anchors: list[Anchor]
The list of anchors the glyph contains.
- Getter:
Returns a list of anchors the glyph contains. Modifications of the list modify the Glyph object.
- Setter:
Clears current anchors and sets the new ones.
- appendAnchor(anchor: Anchor | Mapping[str, Any]) None [source]
Appends an
Anchor
object to glyph’s list of anchors.- Parameters:
anchor – An
Anchor
object or mapping for the Anchor constructor.
- appendContour(contour: Contour) None [source]
Appends a
Contour
object to glyph’s list of contours.
- appendGuideline(guideline: Guideline | Mapping[str, Any]) None [source]
Appends a
Guideline
object to glyph’s list of guidelines.- Parameters:
guideline – A
Guideline
object or a mapping for the Guideline constructor.
- copy(name: str | None = None) Glyph [source]
Returns a new Glyph (deep) copy, optionally override the new glyph name.
- copyDataFromGlyph(glyph: Glyph) None [source]
Deep-copies everything from the other glyph into self, except for the name.
Existing glyph data is overwritten.
For defcon API compatibility only.
- draw(pen: AbstractPen, outputImpliedClosingLine: bool = False) None [source]
Draws glyph into given pen.
- drawPoints(pointPen: AbstractPointPen) None [source]
Draws points of glyph into given point pen.
- getBottomMargin(layer: GlyphSet | None = None) float | None [source]
Returns the the space in font units from the bottom of the canvas to the bottom of the glyph.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- getBounds(layer: GlyphSet | None = None) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- getControlBounds(layer: GlyphSet | None = None) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- getLeftMargin(layer: GlyphSet | None = None) float | None [source]
Returns the the space in font units from the point of origin to the left side of the glyph.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- getPen() AbstractPen [source]
Returns a pen for others to draw into self.
- getPointPen() AbstractPointPen [source]
Returns a point pen for others to draw points into self.
- getRightMargin(layer: GlyphSet | None = None) float | None [source]
Returns the the space in font units from the glyph’s advance width to the right side of the glyph.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- getTopMargin(layer: GlyphSet | None = None) float | None [source]
Returns the the space in font units from the top of the canvas to the top of the glyph.
- Parameters:
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- property guidelines: list[Guideline]
The list of guidelines the glyph contains.
- Getter:
Returns a list of guidelines the glyph contains. Modifications of the list modify the Glyph object.
- Setter:
Clears current guidelines and sets the new ones.
- height: float
The height of the glyph.
- property image: Image
The background image reference associated with the glyph.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#image.
- Setter:
Sets the background image reference. Clears it if value is None.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- property lib: Lib
- property markColor: str | None
The color assigned to the glyph.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#publicmarkcolor.
- Getter:
Returns the mark color or None.
- Setter:
Sets the mark color. If value is None, deletes the key from the lib if present.
- move(delta: tuple[float, float]) None [source]
Moves all contours, components and anchors by (x, y) font units.
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- property name: str | None
The name of the glyph.
- note: str | None
A free form text note about the glyph.
- objectLib(object: HasIdentifier) dict[str, Any] [source]
Return the lib for an object with an identifier, as stored in a glyph’s lib.
If the object does not yet have an identifier, a new one is assigned to it. If the font lib does not yet contain the object’s lib, a new one is inserted and returned.
>>> from ufoLib2.objects import Font, Guideline >>> font = Font() >>> glyph = font.newGlyph("a") >>> glyph.guidelines = [Guideline(x=100)] >>> guideline_lib = glyph.objectLib(glyph.guidelines[0]) >>> guideline_lib["com.test.foo"] = 1234 >>> guideline_id = glyph.guidelines[0].identifier >>> assert guideline_id is not None >>> assert glyph.lib["public.objectLibs"][guideline_id] is guideline_lib
- removeComponent(component: Component) None [source]
Removes
Component
object from the glyph’s list of components.
- setBottomMargin(value: float, layer: GlyphSet | None = None) None [source]
Sets the the space in font units from the bottom of the canvas to the bottom of the glyph.
- Parameters:
value – The desired bottom margin in font units.
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- setLeftMargin(value: float, layer: GlyphSet | None = None) None [source]
Sets the the space in font units from the point of origin to the left side of the glyph.
- Parameters:
value – The desired left margin in font units.
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- setRightMargin(value: float, layer: GlyphSet | None = None) None [source]
Sets the the space in font units from the glyph’s advance width to the right side of the glyph.
- Parameters:
value – The desired right margin in font units.
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- setTopMargin(value: float, layer: GlyphSet | None = None) None [source]
Sets the the space in font units from the top of the canvas to the top of the glyph.
- Parameters:
value – The desired top margin in font units.
layer – The layer of the glyph to look up components, if any. Not needed for pure-contour glyphs.
- property tempLib: Lib
- property unicode: int | None
The first assigned Unicode code point or None.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#unicode.
- Setter:
Sets the value to be the first of the assigned Unicode code points. Will remove a duplicate if exists. Will clear the list of Unicode points if value is None.
- unicodes: List[int]
The Unicode code points assigned to the glyph. Note that a glyph can have multiple.
- property verticalOrigin: float | None
The vertical origin of the glyph.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#publicverticalorigin.
- Getter:
Returns the vertical origin or None.
- Setter:
Sets the vertical origin. If value is None, deletes the key from the lib if present.
- width: float
The width of the glyph.
Component
- class ufoLib2.objects.Component(baseGlyph: str, transformation: Transform | Sequence[float] = (1, 0, 0, 1, 0, 0), identifier: str | None = None)[source]
Represents a reference to another glyph in the same layer.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#component.
Note
Components always refer to glyphs in the same layer. Referencing different layers is currently not possible in the UFO data model.
- baseGlyph: str
The name of the glyph in the same layer to insert.
- draw(pen: AbstractPen) None [source]
Draws component with given pen.
- drawPoints(pointPen: AbstractPointPen) None [source]
Draws points of component with given point pen.
- getBounds(layer: GlyphSet) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the component, taking the actual contours into account.
- Parameters:
layer – The layer of the containing glyph to look up components.
- getControlBounds(layer: GlyphSet) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the component, taking only the control points into account.
- Parameters:
layer – The layer of the containing glyph to look up components.
- identifier: str | None
The globally unique identifier of the component.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- move(delta: tuple[float, float]) None [source]
Moves this component by (x, y) font units.
NOTE: This interprets the delta to be the visual delta, as in, it replaces the x and y offsets of the component’s transformation directly, rather than going through
fontTools.misc.transform.Transform.translate()
. Otherwise, composites that use flipped components (imagine aquotedblleft
composite using two x- and y-invertedcomma
components) would move in the opposite direction of the delta.
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- transformation: Transform
The affine transformation to apply to the
Component.baseGlyph
.
Contour
- class ufoLib2.objects.Contour(points: List[Point] = NOTHING, identifier: str | None = None)[source]
Represents a contour as a list of points.
- Behavior:
The Contour object has list-like behavior. This behavior allows you to interact with point data directly. For example, to get a particular point:
point = contour[0]
To iterate over all points:
for point in contour: ...
To get the number of points:
pointCount = len(contour)
To delete a particular point:
del contour[0]
To set a particular point to another Point object:
contour[0] = anotherPoint
- property bounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.
For defcon API compatibility only.
- property controlPointBounds: BoundingBox | None
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.
For defcon API compatibility only.
- draw(pen: AbstractPen) None [source]
Draws contour into given pen.
- drawPoints(pointPen: AbstractPointPen) None [source]
Draws points of contour into given point pen.
- getBounds(layer: GlyphSet | None = None) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking the actual contours into account.
- Parameters:
layer – Not applicable to contours, here for API symmetry.
- getControlBounds(layer: GlyphSet | None = None) BoundingBox | None [source]
Returns the (xMin, yMin, xMax, yMax) bounding box of the glyph, taking only the control points into account.
- Parameters:
layer – Not applicable to contours, here for API symmetry.
- identifier: str | None
The globally unique identifier of the contour.
- insert(index: int, value: Point) None [source]
Insert Point object
value
into the contour atindex
.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- property open: bool
Returns whether the contour is open or closed.
Point
- class ufoLib2.objects.Point(x: float, y: float, type: str | None = None, smooth: bool = False, name: str | None = None, identifier: str | None = None)[source]
Represents a single point.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#point.
- identifier: str | None
The globally unique identifier of the point.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- name: str | None
The name of the point, no uniqueness required.
- property segmentType: str | None
Returns the type of the point.
For defcon API compatibility only.
- smooth: bool
Whether a smooth curvature should be maintained at this point.
- type: str | None
The type of the point.
None
means “offcurve”.See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#point-types.
- x: float
The x coordinate of the point.
- y: float
The y coordinate of the point.
Anchor
- class ufoLib2.objects.Anchor(x: float, y: float, name: str | None = None, color: str | None = None, identifier: str | None = None)[source]
Represents a single anchor.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#anchor.
- color: str | None
The color of the anchor.
- identifier: str | None
The globally unique identifier of the anchor.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- name: str | None
The name of the anchor.
- x: float
The x coordinate of the anchor.
- y: float
The y coordinate of the anchor.
Guideline
- class ufoLib2.objects.Guideline(x: float | None = None, y: float | None = None, angle: float | None = None, name: str | None = None, color: str | None = None, identifier: str | None = None)[source]
Represents a single guideline.
See http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#guideline. Has some data composition restrictions.
- angle: float | None
The angle of the guideline.
- color: str | None
The color of the guideline.
- identifier: str | None
The globally unique identifier of the guideline.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- name: str | None
The name of the guideline, no uniqueness required.
- x: float | None
The origin x coordinate of the guideline.
- y: float | None
The origin y coordinate of the guideline.
ImageSet
- class ufoLib2.objects.imageSet.ImageSet(data: Dict[str, bytes] = NOTHING)[source]
Represents a mapping of POSIX filename strings to arbitrary image data.
Note
Images cannot be put into subdirectories of the images folder.
- Behavior:
ImageSet behaves like a dictionary of type
Dict[str, bytes]
.>>> from ufoLib2 import Font >>> font = Font() >>> # Note: invalid PNG data for demonstration. Use the actual PNG bytes. >>> font.images["test.png"] = b"123" >>> font.images["test2.png"] = b"456" >>> font.images["test.png"] b'123' >>> del font.images["test.png"] >>> list(font.images.items()) [('test2.png', b'456')]
- clear() None. Remove all items from D.
- property fileNames: list[str]
Returns a list of filenames in the data store.
- get(k[, d]) D[k] if k in D, else d. d defaults to None.
- items() a set-like object providing a view on D's items
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- keys() a set-like object providing a view on D's keys
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
- pop(k[, d]) v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty.
- classmethod read(reader: UFOReader, lazy: bool = True) Tds
Instantiate the data store from a
fontTools.ufoLib.UFOReader
.
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
- unlazify() None
Load all data into memory.
- update([E, ]**F) None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v
- values() an object providing a view on D's values
- write(writer: UFOWriter, saveAs: bool | None = None) None
Write the data store to a
fontTools.ufoLib.UFOWriter
.
Image
- class ufoLib2.objects.Image(fileName: str | None = None, transformation: Transform | Sequence[float] = (1, 0, 0, 1, 0, 0), color: str | None = None)[source]
Represents a background image reference.
See http://unifiedfontobject.org/versions/ufo3/images/ and http://unifiedfontobject.org/versions/ufo3/glyphs/glif/#image.
- color: str | None
The color applied to the image.
- fileName: str | None
The filename of the image.
- json_dump(fp: PathLike | BinaryIO, indent: int | None = None, sort_keys: bool = False, **kwargs: Any) None
- json_dumps(indent: int | None = None, sort_keys: bool = False, **kwargs: Any) bytes
- msgpack_dump(fp: PathLike | BinaryIO, **kwargs: Any) None
- msgpack_dumps(**kwargs: Any) bytes
Miscellaneous objects
- class ufoLib2.objects.misc.BoundingBox(xMin: float, yMin: float, xMax: float, yMax: float)[source]
Represents a bounding box as a tuple of (xMin, yMin, xMax, yMax).
- xMax: float
Alias for field number 2
- xMin: float
Alias for field number 0
- yMax: float
Alias for field number 3
- yMin: float
Alias for field number 1
Types
- class ufoLib2.typing.Drawable(*args, **kwargs)[source]
Stand-in for an object that can draw itself with a given pen.
See
fontTools.pens.basePen
for an introduction to pens.- draw(pen: AbstractPen) None [source]
- class ufoLib2.typing.DrawablePoints(*args, **kwargs)[source]
Stand-in for an object that can draw its points with a given pen.
See
fontTools.pens.pointPen
for an introduction to point pens.- drawPoints(pen: AbstractPointPen) None [source]
- class ufoLib2.typing.GlyphSet(*args, **kwargs)[source]
Any container that holds drawable objects.
In ufoLib2, this usually refers to
Font
(referencing glyphs in the default layer) andLayer
(referencing glyphs in that particular layer). Ideally, this would be a simple subclass ofMapping[str, Union[Drawable, DrawablePoints]]
, but due to historic reasons, the established objects don’t conform toMapping
exactly.The protocol contains what is used in
fontTools.pens
at v4.18.2 (grep for.glyphSet
).
- class ufoLib2.typing.HasIdentifier(*args, **kwargs)[source]
Any object that has a unique identifier in some context that can be used as a key in a public.objectLibs dictionary.
- identifier: str | None
- ufoLib2.typing.PathLike
Represents a path in various possible forms.
alias of
str
|bytes
|os.PathLike[str]
|os.PathLike[bytes]
- class ufoLib2.typing.T
Generic variable for mypy for trivial generic function signatures.
alias of TypeVar(‘T’)
Pens
- class ufoLib2.pointPens.glyphPointPen.GlyphPointPen(glyph: Glyph)[source]
A point pen.
See
fontTools.pens.basePen
andfontTools.pens.pointPen
for an introduction to pens.- addComponent(baseGlyph: str, transformation: Transform, identifier: str | None = None, **kwargs: Any) None [source]
Add a sub glyph.
Constants
- ufoLib2.constants.DATA_LIB_KEY = 'com.github.fonttools.ufoLib2.lib.plist.data'
Lib key used for serializing binary data as JSON-encodable string.
- ufoLib2.constants.DEFAULT_LAYER_NAME: str = 'public.default'
The name of the default layer.
- ufoLib2.constants.OBJECT_LIBS_KEY: str = 'public.objectLibs'
The lib key for object libs.
See: