# 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()`

### Submodules:

ufoLib provides the following submodules:

> - 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 helper functions
> - validators: Data-validation functions

Two deprecated submodules are also currently included:

> - plistlib: Support for reading and writing .plist files [deprecated]
> - pointPen: A pen for accessing points in a glyph contour [deprecated]

### Module members:

fontTools.ufoLib.makeUFOPath(path)

  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, validate=True)

  Bases: `_UFOBaseIO`

  Read the various components of a .ufo.

  path

    An os.PathLike object pointing to the .ufo.

  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

    The path of the UFO (DEPRECATED).

  property formatVersion

    Use formatVersionTuple

    Type:

      The (major) format version of the UFO. DEPRECATED

  property formatVersionTuple

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

  property fileStructure

    either UFOFileStructure.ZIP or UFOFileStructure.PACKAGE

    Type:

      The file structure of the UFO

  readBytesFromPath(path)

    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, encoding=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=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=None)

    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=None)

    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, validate=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=None)

    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=None)

    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()

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

  getLayerNames(validate=None)

    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=None)

    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=None, validateRead=None, validateWrite=None)

    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=None, validate=None)

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

  getDataDirectoryListing()

    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=None)

    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)

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

  readImage(fileName, validate=None)

    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()

class fontTools.ufoLib.UFOWriter(path, formatVersion=None, fileCreator='com.github.fonttools.ufoLib', structure=None, validate=True)

  Bases: `UFOReader`

  Write the various components of a .ufo.

  path

    An os.PathLike object pointing to the .ufo.

  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.

  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

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

  copyFromReader(reader, sourcePath, destPath)

    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, data)

    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, mode='w', encoding=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, force=False, removeEmptyParents=True)

    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, force=False, removeEmptyParents=True)

    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()

    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)

    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, validate=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, validate=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, validate=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, validate=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, validate=None)

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

  writeLayerContents(layerOrder=None, validate=None)

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

  getGlyphSet(layerName=None, defaultLayer=True, glyphNameToFileNameFunc=None, validateRead=None, validateWrite=None, expectContentsFile=False)

    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, newLayerName, defaultLayer=False)

    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)

    Remove the glyph set matching layerName.

  writeData(fileName, data)

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

  removeData(fileName)

    Remove the file named fileName from the data directory.

  writeImage(fileName, data, validate=None)

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

  removeImage(fileName, validate=None)

    Remove the file named fileName from the images directory.

  copyImageFromReader(reader, sourceFileName, destFileName, validate=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()

fontTools.ufoLib.UFOReaderWriter

  alias of `UFOWriter`

class fontTools.ufoLib.UFOFileStructure(*values)

  Bases: `Enum`

  ZIP = 'zip'
  PACKAGE = 'package'

fontTools.ufoLib.validateFontInfoVersion2ValueForAttribute(attr, value)

  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, value)

  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, value)

  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, value)

  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 = {'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 = {'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 = {'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.