# ufoLib: Read and write Unified Font Object files

## Overview:

> A library for importing .ufo files and their descendants. Refer to http://unifiedfontobject.org for the UFO specification.

> The main interfaces are the `UFOReader` and `UFOWriter` classes, which support versions 1, 2, and 3 of the UFO specification.

> Set variables are available for external use that list the font info attribute names for the fontinfo.plist formats. These are:

> - `fontInfoAttributesVersion1`

> - `fontInfoAttributesVersion2`

> - `fontInfoAttributesVersion3`

> A set listing the fontinfo.plist attributes that were deprecated in version 2 is available for external use:

> - `deprecatedFontInfoAttributesVersion2`

> Functions that do basic validation on values for fontinfo.plist are available for external use. These are

> - `validateFontInfoVersion2ValueForAttribute()`

> - `validateFontInfoVersion3ValueForAttribute()`

> Value conversion functions are available for converting fontinfo.plist values between the possible format versions.

> - `convertFontInfoValueForAttributeFromVersion1ToVersion2()`

> - `convertFontInfoValueForAttributeFromVersion2ToVersion1()`

> - `convertFontInfoValueForAttributeFromVersion2ToVersion3()`

> - `convertFontInfoValueForAttributeFromVersion3ToVersion2()`

## Modules:

ufoLib provides the following modules:

> - converters: Conversion functions for kerning and groups
> - errors: Exceptions for handling UFO-specific errors
> - filenames: Functions to convert between file names and user-facing strings
> - glifLib: Read and write UFO .glif files
> - kerning: Support for accessing kerning data
> - utils: Miscellaneous UFO helper functions
> - validators: Data-validation functions

Three deprecated modules are also currently included:

> - etree: Shim module for the ElementTree XML API [deprecated]
> - plistlib: Support for reading and writing .plist files [deprecated]
> - pointPen: A pen for accessing points in a glyph contour [deprecated]

Note also that `ufoLib` supports some optional external libraries.

## Module members:

fontTools.ufoLib.makeUFOPath(path: PathStr) → str

  Return a .ufo pathname.

      >>> makeUFOPath("directory/something.ext") == (
      ...         os.path.join('directory', 'something.ufo'))
      True
      >>> makeUFOPath("directory/something.another.thing.ext") == (
      ...         os.path.join('directory', 'something.another.thing.ufo'))
      True

exception fontTools.ufoLib.UFOLibError

  Bases: `Exception`

class fontTools.ufoLib.UFOReader(path: PathOrFS, validate: bool = True)

  Bases: `_UFOBaseIO`

  Read the various components of a .ufo.

  path

    An `os.PathLike` object pointing to the .ufo.

    Type:

      property

  validate

    A boolean indicating if the data read should be validated. Defaults to True.

  By default read data is validated. Set `validate` to `False` to not validate the data.

  property path: str

    The path of the UFO (DEPRECATED).

  property formatVersion: int

    Use formatVersionTuple

    Type:

      The (major) format version of the UFO. DEPRECATED

  property formatVersionTuple: tuple[int, int]

    The (major, minor) format version of the UFO. This is determined by reading metainfo.plist during __init__.

  property fileStructure: Any

    either UFOFileStructure.ZIP or UFOFileStructure.PACKAGE

    Type:

      The file structure of the UFO

  readBytesFromPath(path: PathStr) → bytes | None

    Returns the bytes in the file at the given path. The path must be relative to the UFO’s filesystem root. Returns None if the file does not exist.

  getReadFileForPath(path: PathStr, encoding: str | None = None) → IO[bytes] | IO[str] | None

    Returns a file (or file-like) object for the file at the given path. The path must be relative to the UFO path. Returns None if the file does not exist. By default the file is opened in binary mode (reads bytes). If encoding is passed, the file is opened in text mode (reads str).

    Note: The caller is responsible for closing the open file.

  readMetaInfo(validate: bool | None = None) → None

    Read metainfo.plist and set formatVersion. Only used for internal operations.

    `validate` will validate the read data, by default it is set to the class’s validate value, can be overridden.

  readGroups(validate: bool | None = None) → dict[str, list[str]]

    Read groups.plist. Returns a dict. `validate` will validate the read data, by default it is set to the class’s validate value, can be overridden.

  getKerningGroupConversionRenameMaps(validate: bool | None = None) → dict[str, dict[str, str]]

    Get maps defining the renaming that was done during any needed kerning group conversion. This method returns a dictionary of this form:

        {
                "side1" : {"old group name" : "new group name"},
                "side2" : {"old group name" : "new group name"}
        }

    When no conversion has been performed, the side1 and side2 dictionaries will be empty.

    `validate` will validate the groups, by default it is set to the class’s validate value, can be overridden.

  readInfo(info: Any, validate: bool | None = None) → None

    Read fontinfo.plist. It requires an object that allows setting attributes with names that follow the fontinfo.plist version 3 specification. This will write the attributes defined in the file into the object.

    `validate` will validate the read data, by default it is set to the class’s validate value, can be overridden.

  readKerning(validate: bool | None = None) → KerningDict

    Read kerning.plist. Returns a dict.

    `validate` will validate the kerning data, by default it is set to the class’s validate value, can be overridden.

  readLib(validate: bool | None = None) → dict[str, Any]

    Read lib.plist. Returns a dict.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  readFeatures() → str

    Read features.fea. Return a string. The returned string is empty if the file is missing.

  getLayerNames(validate: bool | None = None) → list[str]

    Get the ordered layer names from layercontents.plist.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  getDefaultLayerName(validate: bool | None = None) → str

    Get the default layer name from layercontents.plist.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  getGlyphSet(layerName: str | None = None, validateRead: bool | None = None, validateWrite: bool | None = None) → GlyphSet

    Return the GlyphSet associated with the glyphs directory mapped to layerName in the UFO. If layerName is not provided, the name retrieved with getDefaultLayerName will be used.

    `validateRead` will validate the read data, by default it is set to the class’s validate value, can be overridden. `validateWrite` will validate the written data, by default it is set to the class’s validate value, can be overridden.

  getCharacterMapping(layerName: str | None = None, validate: bool | None = None) → dict[int, list[str]]

    Return a dictionary that maps unicode values (ints) to lists of glyph names.

  getDataDirectoryListing() → list[str]

    Returns a list of all files in the data directory. The returned paths will be relative to the UFO. This will not list directory names, only file names. Thus, empty directories will be skipped.

  getImageDirectoryListing(validate: bool | None = None) → list[str]

    Returns a list of all image file names in the images directory. Each of the images will have been verified to have the PNG signature.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  readData(fileName: PathStr) → bytes

    Return bytes for the file named ‘fileName’ inside the ‘data/’ directory.

  readImage(fileName: PathStr, validate: bool | None = None) → bytes

    Return image data for the file named fileName.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  close() → None

class fontTools.ufoLib.UFOWriter(path: PathOrFS, formatVersion: UFOFormatVersionInput = None, fileCreator: str = 'com.github.fonttools.ufoLib', structure: UFOFileStructure | None = None, validate: bool = True)

  Bases: `UFOReader`

  Write the various components of a .ufo.

  path

    An `os.PathLike` object pointing to the .ufo.

    Type:

      property

  formatVersion

    the UFO format version as a tuple of integers (major, minor), or as a single integer for the major digit only (minor is implied to be 0). By default, the latest formatVersion will be used; currently it is 3.0, which is equivalent to formatVersion=(3, 0).

  fileCreator

    The creator of the .ufo file. Defaults to com.github.fonttools.ufoLib.

    Type:

      property

  structure

    The internal structure of the .ufo file: either ZIP or PACKAGE.

  validate

    A boolean indicating if the data read should be validated. Defaults to True.

  By default, the written data will be validated before writing. Set `validate` to `False` if you do not want to validate the data. Validation can also be overriden on a per-method level if desired.

  Raises:

    UnsupportedUFOFormat – An exception indicating that the requested UFO formatVersion is not supported.

  property fileCreator: str

    The file creator of the UFO. This is set into metainfo.plist during __init__.

  copyFromReader(reader: UFOReader, sourcePath: PathStr, destPath: PathStr) → None

    Copy the sourcePath in the provided UFOReader to destPath in this writer. The paths must be relative. This works with both individual files and directories.

  writeBytesToPath(path: PathStr, data: bytes) → None

    Write bytes to a path relative to the UFO filesystem’s root. If writing to an existing UFO, check to see if data matches the data that is already in the file at path; if so, the file is not rewritten so that the modification date is preserved. If needed, the directory tree for the given path will be built.

  getFileObjectForPath(path: PathStr, mode: str = 'w', encoding: str | None = None) → IO[Any] | None

    Returns a file (or file-like) object for the file at the given path. The path must be relative to the UFO path. Returns None if the file does not exist and the mode is “r” or “rb. An encoding may be passed if the file is opened in text mode.

    Note: The caller is responsible for closing the open file.

  removePath(path: PathStr, force: bool = False, removeEmptyParents: bool = True) → None

    Remove the file (or directory) at path. The path must be relative to the UFO. Raises UFOLibError if the path doesn’t exist. If force=True, ignore non-existent paths. If the directory where ‘path’ is located becomes empty, it will be automatically removed, unless ‘removeEmptyParents’ is False.

  removeFileForPath(path: PathStr, force: bool = False, removeEmptyParents: bool = True) → None

    Remove the file (or directory) at path. The path must be relative to the UFO. Raises UFOLibError if the path doesn’t exist. If force=True, ignore non-existent paths. If the directory where ‘path’ is located becomes empty, it will be automatically removed, unless ‘removeEmptyParents’ is False.

  setModificationTime() → None

    Set the UFO modification time to the current time. This is never called automatically. It is up to the caller to call this when finished working on the UFO.

  setKerningGroupConversionRenameMaps(maps: dict[str, dict[str, str]]) → None

    Set maps defining the renaming that should be done when writing groups and kerning in UFO 1 and UFO 2. This will effectively undo the conversion done when UFOReader reads this data. The dictionary should have this form:

        {
                "side1" : {"group name to use when writing" : "group name in data"},
                "side2" : {"group name to use when writing" : "group name in data"}
        }

    This is the same form returned by UFOReader’s getKerningGroupConversionRenameMaps method.

  writeGroups(groups: KerningGroups, validate: bool | None = None) → None

    Write groups.plist. This method requires a dict of glyph groups as an argument.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  writeInfo(info: Any, validate: bool | None = None) → None

    Write info.plist. This method requires an object that supports getting attributes that follow the fontinfo.plist version 2 specification. Attributes will be taken from the given object and written into the file.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  writeKerning(kerning: KerningDict, validate: bool | None = None) → None

    Write kerning.plist. This method requires a dict of kerning pairs as an argument.

    This performs basic structural validation of the kerning, but it does not check for compliance with the spec in regards to conflicting pairs. The assumption is that the kerning data being passed is standards compliant.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  writeLib(libDict: dict[str, Any], validate: bool | None = None) → None

    Write lib.plist. This method requires a lib dict as an argument.

    `validate` will validate the data, by default it is set to the class’s validate value, can be overridden.

  writeFeatures(features: str, validate: bool | None = None) → None

    Write features.fea. This method requires a features string as an argument.

  writeLayerContents(layerOrder: list[str | None] | None = None, validate: bool | None = None) → None

    Write the layercontents.plist file. This method must be called after all glyph sets have been written.

  getGlyphSet(layerName: str | None = None, defaultLayer: bool = True, glyphNameToFileNameFunc: GlyphNameToFileNameFunc = None, validateRead: bool | None = None, validateWrite: bool | None = None, expectContentsFile: bool = False) → GlyphSet

    Return the GlyphSet object associated with the appropriate glyph directory in the .ufo. If layerName is None, the default glyph set will be used. The defaultLayer flag indictes that the layer should be saved into the default glyphs directory.

    `validateRead` will validate the read data, by default it is set to the class’s validate value, can be overridden. `validateWrte` will validate the written data, by default it is set to the class’s validate value, can be overridden. `expectContentsFile` will raise a GlifLibError if a contents.plist file is not found on the glyph set file system. This should be set to `True` if you are reading an existing UFO and `False` if you use `getGlyphSet` to create a fresh glyph set.

  renameGlyphSet(layerName: str | None, newLayerName: str | None, defaultLayer: bool = False) → None

    Rename a glyph set.

    Note: if a GlyphSet object has already been retrieved for layerName, it is up to the caller to inform that object that the directory it represents has changed.

  deleteGlyphSet(layerName: str | None) → None

    Remove the glyph set matching layerName.

  writeData(fileName: PathStr, data: bytes) → None

    Write data to fileName in the ‘data’ directory. The data must be a bytes string.

  removeData(fileName: PathStr) → None

    Remove the file named fileName from the data directory.

  writeImage(fileName: PathStr, data: bytes, validate: bool | None = None) → None

    Write data to fileName in the images directory. The data must be a valid PNG.

  removeImage(fileName: PathStr, validate: bool | None = None) → None

    Remove the file named fileName from the images directory.

  copyImageFromReader(reader: UFOReader, sourceFileName: PathStr, destFileName: PathStr, validate: bool | None = None) → None

    Copy the sourceFileName in the provided UFOReader to destFileName in this writer. This uses the most memory efficient method possible for copying the data possible.

  close() → None

fontTools.ufoLib.UFOReaderWriter

  alias of `UFOWriter`

class fontTools.ufoLib.UFOFileStructure(*values)

  Bases: `Enum`

  ZIP = 'zip'
  PACKAGE = 'package'

fontTools.ufoLib.validateFontInfoVersion2ValueForAttribute(attr: str, value: Any) → bool

  This performs very basic validation of the value for attribute following the UFO 2 fontinfo.plist specification. The results of this should not be interpretted as correct for the font that they are part of. This merely indicates that the value is of the proper type and, where the specification defines a set range of possible values for an attribute, that the value is in the accepted range.

fontTools.ufoLib.validateFontInfoVersion3ValueForAttribute(attr: str, value: Any) → bool

  This performs very basic validation of the value for attribute following the UFO 3 fontinfo.plist specification. The results of this should not be interpretted as correct for the font that they are part of. This merely indicates that the value is of the proper type and, where the specification defines a set range of possible values for an attribute, that the value is in the accepted range.

fontTools.ufoLib.convertFontInfoValueForAttributeFromVersion1ToVersion2(attr: str, value: Any) → tuple[str, Any]

  Convert value from version 1 to version 2 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value.

fontTools.ufoLib.convertFontInfoValueForAttributeFromVersion2ToVersion1(attr: str, value: Any) → tuple[str, Any]

  Convert value from version 2 to version 1 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value.

fontTools.ufoLib.fontInfoAttributesVersion1: set[str] = {'ascender', 'capHeight', 'copyright', 'createdBy', 'defaultWidth', 'descender', 'designer', 'designerURL', 'familyName', 'fondID', 'fondName', 'fontName', 'fontStyle', 'fullName', 'italicAngle', 'license', 'licenseURL', 'menuName', 'msCharSet', 'note', 'notice', 'otFamilyName', 'otMacName', 'otStyleName', 'slantAngle', 'styleName', 'trademark', 'ttUniqueID', 'ttVendor', 'ttVersion', 'uniqueID', 'unitsPerEm', 'vendorURL', 'versionMajor', 'versionMinor', 'weightName', 'weightValue', 'widthName', 'xHeight', 'year'}

  Build an unordered collection of unique elements.

fontTools.ufoLib.fontInfoAttributesVersion2: set[str] = {'ascender', 'capHeight', 'copyright', 'descender', 'familyName', 'italicAngle', 'macintoshFONDFamilyID', 'macintoshFONDName', 'note', 'openTypeHeadCreated', 'openTypeHeadFlags', 'openTypeHeadLowestRecPPEM', 'openTypeHheaAscender', 'openTypeHheaCaretOffset', 'openTypeHheaCaretSlopeRise', 'openTypeHheaCaretSlopeRun', 'openTypeHheaDescender', 'openTypeHheaLineGap', 'openTypeNameCompatibleFullName', 'openTypeNameDescription', 'openTypeNameDesigner', 'openTypeNameDesignerURL', 'openTypeNameLicense', 'openTypeNameLicenseURL', 'openTypeNameManufacturer', 'openTypeNameManufacturerURL', 'openTypeNamePreferredFamilyName', 'openTypeNamePreferredSubfamilyName', 'openTypeNameSampleText', 'openTypeNameUniqueID', 'openTypeNameVersion', 'openTypeNameWWSFamilyName', 'openTypeNameWWSSubfamilyName', 'openTypeOS2CodePageRanges', 'openTypeOS2FamilyClass', 'openTypeOS2Panose', 'openTypeOS2Selection', 'openTypeOS2StrikeoutPosition', 'openTypeOS2StrikeoutSize', 'openTypeOS2SubscriptXOffset', 'openTypeOS2SubscriptXSize', 'openTypeOS2SubscriptYOffset', 'openTypeOS2SubscriptYSize', 'openTypeOS2SuperscriptXOffset', 'openTypeOS2SuperscriptXSize', 'openTypeOS2SuperscriptYOffset', 'openTypeOS2SuperscriptYSize', 'openTypeOS2Type', 'openTypeOS2TypoAscender', 'openTypeOS2TypoDescender', 'openTypeOS2TypoLineGap', 'openTypeOS2UnicodeRanges', 'openTypeOS2VendorID', 'openTypeOS2WeightClass', 'openTypeOS2WidthClass', 'openTypeOS2WinAscent', 'openTypeOS2WinDescent', 'openTypeVheaCaretOffset', 'openTypeVheaCaretSlopeRise', 'openTypeVheaCaretSlopeRun', 'openTypeVheaVertTypoAscender', 'openTypeVheaVertTypoDescender', 'openTypeVheaVertTypoLineGap', 'postscriptBlueFuzz', 'postscriptBlueScale', 'postscriptBlueShift', 'postscriptBlueValues', 'postscriptDefaultCharacter', 'postscriptDefaultWidthX', 'postscriptFamilyBlues', 'postscriptFamilyOtherBlues', 'postscriptFontName', 'postscriptForceBold', 'postscriptFullName', 'postscriptIsFixedPitch', 'postscriptNominalWidthX', 'postscriptOtherBlues', 'postscriptSlantAngle', 'postscriptStemSnapH', 'postscriptStemSnapV', 'postscriptUnderlinePosition', 'postscriptUnderlineThickness', 'postscriptUniqueID', 'postscriptWeightName', 'postscriptWindowsCharacterSet', 'styleMapFamilyName', 'styleMapStyleName', 'styleName', 'trademark', 'unitsPerEm', 'versionMajor', 'versionMinor', 'xHeight', 'year'}

  Build an unordered collection of unique elements.

fontTools.ufoLib.fontInfoAttributesVersion3: set[str] = {'ascender', 'capHeight', 'copyright', 'descender', 'familyName', 'guidelines', 'italicAngle', 'macintoshFONDFamilyID', 'macintoshFONDName', 'note', 'openTypeGaspRangeRecords', 'openTypeHeadCreated', 'openTypeHeadFlags', 'openTypeHeadLowestRecPPEM', 'openTypeHheaAscender', 'openTypeHheaCaretOffset', 'openTypeHheaCaretSlopeRise', 'openTypeHheaCaretSlopeRun', 'openTypeHheaDescender', 'openTypeHheaLineGap', 'openTypeNameCompatibleFullName', 'openTypeNameDescription', 'openTypeNameDesigner', 'openTypeNameDesignerURL', 'openTypeNameLicense', 'openTypeNameLicenseURL', 'openTypeNameManufacturer', 'openTypeNameManufacturerURL', 'openTypeNamePreferredFamilyName', 'openTypeNamePreferredSubfamilyName', 'openTypeNameRecords', 'openTypeNameSampleText', 'openTypeNameUniqueID', 'openTypeNameVersion', 'openTypeNameWWSFamilyName', 'openTypeNameWWSSubfamilyName', 'openTypeOS2CodePageRanges', 'openTypeOS2FamilyClass', 'openTypeOS2Panose', 'openTypeOS2Selection', 'openTypeOS2StrikeoutPosition', 'openTypeOS2StrikeoutSize', 'openTypeOS2SubscriptXOffset', 'openTypeOS2SubscriptXSize', 'openTypeOS2SubscriptYOffset', 'openTypeOS2SubscriptYSize', 'openTypeOS2SuperscriptXOffset', 'openTypeOS2SuperscriptXSize', 'openTypeOS2SuperscriptYOffset', 'openTypeOS2SuperscriptYSize', 'openTypeOS2Type', 'openTypeOS2TypoAscender', 'openTypeOS2TypoDescender', 'openTypeOS2TypoLineGap', 'openTypeOS2UnicodeRanges', 'openTypeOS2VendorID', 'openTypeOS2WeightClass', 'openTypeOS2WidthClass', 'openTypeOS2WinAscent', 'openTypeOS2WinDescent', 'openTypeVheaCaretOffset', 'openTypeVheaCaretSlopeRise', 'openTypeVheaCaretSlopeRun', 'openTypeVheaVertTypoAscender', 'openTypeVheaVertTypoDescender', 'openTypeVheaVertTypoLineGap', 'postscriptBlueFuzz', 'postscriptBlueScale', 'postscriptBlueShift', 'postscriptBlueValues', 'postscriptDefaultCharacter', 'postscriptDefaultWidthX', 'postscriptFamilyBlues', 'postscriptFamilyOtherBlues', 'postscriptFontName', 'postscriptForceBold', 'postscriptFullName', 'postscriptIsFixedPitch', 'postscriptNominalWidthX', 'postscriptOtherBlues', 'postscriptSlantAngle', 'postscriptStemSnapH', 'postscriptStemSnapV', 'postscriptUnderlinePosition', 'postscriptUnderlineThickness', 'postscriptUniqueID', 'postscriptWeightName', 'postscriptWindowsCharacterSet', 'styleMapFamilyName', 'styleMapStyleName', 'styleName', 'trademark', 'unitsPerEm', 'versionMajor', 'versionMinor', 'woffMajorVersion', 'woffMetadataCopyright', 'woffMetadataCredits', 'woffMetadataDescription', 'woffMetadataExtensions', 'woffMetadataLicense', 'woffMetadataLicensee', 'woffMetadataTrademark', 'woffMetadataUniqueID', 'woffMetadataVendor', 'woffMinorVersion', 'xHeight', 'year'}

  Build an unordered collection of unique elements.

fontTools.ufoLib.deprecatedFontInfoAttributesVersion2 = {'createdBy', 'defaultWidth', 'designer', 'designerURL', 'fondID', 'fondName', 'fontName', 'fontStyle', 'fullName', 'license', 'licenseURL', 'menuName', 'msCharSet', 'notice', 'otFamilyName', 'otMacName', 'otStyleName', 'slantAngle', 'ttUniqueID', 'ttVendor', 'ttVersion', 'uniqueID', 'vendorURL', 'weightName', 'weightValue', 'widthName'}

  Build an unordered collection of unique elements.