o
    hp                    @   s  d Z ddlZddlmZ ddlmZ ddlZddlZddlZddlm	Z	 ddl
Z
ddlZ
ddlZ
ddlZ
ddlZ
ddlZ
ddlZ
ddlZ
ddlZ
ddlmZ ddlT ddlmZ dd	lmZ dd
lmZ ddlmZmZ g dZdZ e!e"Z#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.dZ/G dd de0eej1Z2ej3e2_3G dd dej1Z4G dd dZ5G d d! d!e5Z6G d"d# d#e6Z7e7Z8d$d% Z9d&d' Z:d(d) Z;d*d+ Z<d,d- Z=d.d/ Z>e?e@dd0ZAg d1ZBe?e@dd2ZCe?e@dd3ZDg d4ZEh d5ZFi d6eGeHd7d8eGeHd7d9eGeHd7d:eGeHeId;d<eGeJd7d=eGeJd7d>eGeJd7d?eGeHd7d@eGeHd7dAeGeJeKfd7dBeGeJeKfd7dCeGeJeKfd7dDeGeJeKfd7dEeGeJeKfd7dFeGeKeJfd7dGeGeHd7dHeGeHeLd;i dIeGeJeKfd7dJeGdKeMeAdLdMeGeJeKfd7dNeGeJeKfd7dOeGeJeKfd7dPeGeJd7dQeGeJd7dReGeJeKfd7dSeGeHd7dTeGeHd7dUeGeHd7dVeGeHd7dWeGeHd7dXeGeHd7dYeGeHd7dZeGeHd7d[eGeHd7i d\eGeHd7d]eGeHd7d^eGeHd7d_eGeHd7d`eGeHd7daeGeHd7dbeGeJeNd;dceGeJeOd;ddeGdKeMeBdLdeeGeHd7dfeGdKePd;dgeGdKeQd;dheGdKeMeCdLdieGdKeMeDdLdjeGeJeKfd7dkeGeJeKfd7dleGeJeKfd7i dmeGeJeKfd7dneGeJeKfd7doeGdKeMeEdLdpeGeJeKfd7dqeGeJeKfd7dreGeJeKfd7dseGeJeKfd7dteGeJeKfd7dueGeJeKfd7dveGeJeKfd7dweGeJeKfd7dxeGeJeKfd7dyeGeJeKfd7dzeGeJeKfd7d{eGeJeKfd7d|eGeJeKfd7d}eGeJd7i d~eGeJd7deGeJeKfd7deGeHd7deGeHd7deGeKeJfd7deGeJd7deGeJeKfd7deGeJeKfd7deGeRd7deGdKeSd;deGdKeTd;deGdKeSd;deGdKeTd;deGdKeUd;deGdKeUd;deGeJeKfd7deGeJeKfd7eGeKeJfd7eGeRd7eGeJeKfd7eGeJeKfd7eGeHd7eGeHd7eGeJeVd;eGeJd7eGeHd7d	ZWeXeWY ZZeeWZ[e[\i d=eGeJe]d;dAeGeJeKfe^d;dIeGeJe^d;dMeGeJd7dNeGeJd7dOeGeJd7dReGeJd7dfeGdKe_d;djeGeJd7dkeGeJd7dleGeJd7dmeGeJe^d;dneGeJe^d;dpeGeJd7dqeGeJd7dreGeJd7dseGeJd7i dteGeJd7dueGeJd7dveGeJd7dweGeJd7dxeGeJd7dyeGeJd7deGde`d;deGdead;dzeGeJd7d{eGeJd7d|eGeJd7deGeJd7deGeJe]d;deGeJe]d;deGeGebd;deGeGecd;deGeGedd;eGeGeed;eGeGefd;eGeGegd;eGeGehd;eGeGeid;eGe?ejd;eGe?ekd;d eXe[Y Zle?eWm D ]\ZnZodeovrepeod< qe?e[m D ]\ZnZodeovrepeod< qdd Zqi dd9ddSddTddUddVddWddXddYddZdd[dd\dd]dd^ddddcddeddddddddd:dbdd	ZreqerZseXerY ZtdddddZueqeuZvdeud< dddddddddd	ZweqewZxdewd< dewd< dewd< dewd< i ddddddddd2ddddddddddd̓ddΓddГddғddԓdd0ddדddٓddddݜZyeqeyZzdd߄ Z{dd Z|dd Z}dd Z~h dZdAhZh dZdd Zdd Zdd Zdd Ze"dkrddlZe  dS dS )a  
A library for importing .ufo files and their descendants.
Refer to http://unifiedfontobject.org for the UFO specification.

The main interfaces are the :class:`.UFOReader` and :class:`.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:

- :obj:`.fontInfoAttributesVersion1`
- :obj:`.fontInfoAttributesVersion2`
- :obj:`.fontInfoAttributesVersion3`

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

- :obj:`.deprecatedFontInfoAttributesVersion2`

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

- :func:`.validateFontInfoVersion2ValueForAttribute`
- :func:`.validateFontInfoVersion3ValueForAttribute`

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

- :func:`.convertFontInfoValueForAttributeFromVersion1ToVersion2`
- :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion1`
- :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion3`
- :func:`.convertFontInfoValueForAttributeFromVersion3ToVersion2`
    N)deepcopy)fsdecode)OrderedDict)plistlib)*)userNameToFileName)%convertUFO1OrUFO2KerningToUFO3Kerning)UFOLibError)numberTypes_VersionTupleEnumMixin)makeUFOPathr	   	UFOReader	UFOWriterUFOReaderWriterUFOFileStructurefontInfoAttributesVersion1fontInfoAttributesVersion2fontInfoAttributesVersion3$deprecatedFontInfoAttributesVersion2)validateFontInfoVersion2ValueForAttribute)validateFontInfoVersion3ValueForAttribute6convertFontInfoValueForAttributeFromVersion1ToVersion26convertFontInfoValueForAttributeFromVersion2ToVersion1z3.0.0glyphsdataimageszmetainfo.plistzfontinfo.plistz	lib.plistzgroups.plistzkerning.plistzfeatures.feazlayercontents.plistzlayerinfo.plistzpublic.defaultc                   @   s   e Zd ZdZdZdZdS )UFOFormatVersion)   r   )   r   )   r   N)__name__
__module____qualname__
FORMAT_1_0
FORMAT_2_0
FORMAT_3_0 r&   r&   m/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fontTools/ufoLib/__init__.pyr   d   s    r   c                   @   s   e Zd ZdZdZdS )r   zippackageN)r    r!   r"   ZIPPACKAGEr&   r&   r&   r'   r   p   s    r   c                   @   s&   e Zd Zdd ZdddZdd ZdS )	
_UFOBaseIOc              	   C   sD   z| j jt|dgdj}W | S  t jjt jjfy!   Y dS w )a  
        Returns the modification time for the file at the given path, as a
        floating point number giving the number of seconds since the epoch.
        The path must be relative to the UFO path.
        Returns None if the file does not exist.
        details)
namespacesN)fsgetinfor   modifiederrorsMissingInfoNamespaceResourceNotFound	timestamp)selfpathdtr&   r&   r'   getFileModificationTime{   s   z"_UFOBaseIO.getFileModificationTimeNc              
   C   s   z | j |d}t|W  d   W S 1 sw   Y  W dS  t jjy:   |du r6td|| j f | Y S  tyS } ztd| d| j  d| d}~ww )a  
        Read a property list relative to the UFO filesystem's root.
        Raises UFOLibError if the file is missing and default is None,
        otherwise default is returned.

        The errors that could be raised during the reading of a plist are
        unpredictable and/or too large to list, so, a blind try: except:
        is done. If an exception occurs, a UFOLibError will be raised.
        rbNz,'%s' is missing on %s. This file is required'z' could not be read on : )r/   openr   loadr2   r4   r	   	Exception)r6   fileNamedefaultfer&   r&   r'   	_getPlist   s   
(z_UFOBaseIO._getPlistc                 C   s   | j r:zt|}W n ty  } z
td|| j|f d}~ww | j|r1|| j|kr1dS | j|| dS | jj	|dd(}zt
|| W n tya } z
td|| j|f d}~ww W d   dS 1 smw   Y  dS )a  
        Write a property list to a file relative to the UFO filesystem's root.

        Do this sort of atomically, making it harder to corrupt existing files,
        for example when plistlib encounters an error halfway during write.
        This also checks to see if text matches the text that is already in the
        file at path. If so, the file is not rewritten so that the modification
        date is preserved.

        The errors that could be raised during the writing of a plist are
        unpredictable and/or too large to list, so, a blind try: except: is done.
        If an exception occurs, a UFOLibError will be raised.
        zN'%s' could not be written on %s because the data is not properly formatted: %sNw)mode)_havePreviousFiler   dumpsr?   r	   r/   exists	readbytes
writebytesopenbindump)r6   r@   objr   rC   fpr&   r&   r'   _writePlist   s6   

"z_UFOBaseIO._writePlistN)r    r!   r"   r9   rD   rP   r&   r&   r&   r'   r,   z   s    
r,   c                   @   sN  e Zd ZdZdFddZdd ZeeddZd	d
 ZeeddZ	edd Z
dd ZeeddZdd Zdd ZdGddZdGddZdGddZdd ZdGddZdGd d!Zd"d# ZdGd$d%Zd&d' ZdGd(d)ZdGd*d+Zd,d- Zd.d/ ZdGd0d1ZdGd2d3ZdHd4d5ZdId6d7Zd8d9 Z dGd:d;Z!d<d= Z"dGd>d?Z#d@dA Z$dBdC Z%dDdE Z&dS )Jr   aG  Read the various components of a .ufo.

    Attributes:
        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.
    Tc              
   C   s  t |dr	| }t|trvt|}z|tju r"tjj	|ddd}ntj
|}W n tjjyA } z
td| d| d }~ww |tju rldd |d	D }t|d
krd|j|d tjjd| _ntdt| || _d| _|| _nJt|tjjr|}z|  W n tjjy   td| w || _z|d	}W n tjjy   t|}Y nw d| _tj| _n	tdt|j t || _!|| _"d | _#z	| j$|d W d S  ty   | %   w )N
__fspath__Futf-8writeencodingunable to open 'z': c                 S   "   g | ]}|j r|jd kr|jqS __MACOSXis_dirname.0pr&   r&   r'   
<listcomp>       
z&UFOReader.__init__.<locals>.<listcomp>/r   r   factory+Expected exactly 1 root directory, found %dTthe filesystem '%s' is closedz7Expected a path string or fs.base.FS object, found '%s'validate)&hasattrrR   
isinstancestr_sniffFileStructurer   r*   r/   zipfsZipFSosfsOSFSr2   CreateFailedr	   scandirlenopendirsubfsClosingSubFS_shouldClose_fileStructurebaseFScheckFilesystemClosed
getsyspath	NoSysPathr+   	TypeErrortyper    r   _path	_validate_upConvertedKerningDatareadMetaInfoclose)r6   r7   ri   	structureparentFSrC   rootDirs
filesystemr&   r&   r'   __init__   sp   







zUFOReader.__init__c                 C   s   dd l }|jdtdd | jS )Nr   zBThe 'path' attribute is deprecated; use the 'fs' attribute insteadr   
stacklevel)warningswarnDeprecationWarningr   r6   r   r&   r&   r'   	_get_path"  s   zUFOReader._get_pathz!The path of the UFO (DEPRECATED).docc                 C   s    dd l }|jdtdd | jjS )Nr   zIThe 'formatVersion' attribute is deprecated; use the 'formatVersionTuple'r   r   )r   r   r   _formatVersionmajorr   r&   r&   r'   _get_formatVersion.  s   zUFOReader._get_formatVersionzIThe (major) format version of the UFO. DEPRECATED: Use formatVersionTuplec                 C      | j S )z|The (major, minor) format version of the UFO.
        This is determined by reading metainfo.plist during __init__.
        )r   r6   r&   r&   r'   formatVersionTuple=  s   zUFOReader.formatVersionTuplec                 C   r   rQ   )ry   r   r&   r&   r'   _get_fileStructureD     zUFOReader._get_fileStructurezVThe file structure of the UFO: either UFOFileStructure.ZIP or UFOFileStructure.PACKAGEc                 C   s  | j r#|  }|| j d krtd|  }|| j d kr!tdd
S |  }|r]d}t|ts4t|| D ]$\}}t|tsEt|t|tsNt||D ]}t|ts[t|qPq8ti |  i |d| _ t	| j d t
| j d |  \}	}}
|	| j d< || j d< |
| j d	< d
S )ap  
        Up convert kerning and groups in UFO 1 and 2.
        The data will be held internally until each bit of data
        has been retrieved. The conversion of both must be done
        at once, so the raw data is cached and an error is raised
        if one bit of data becomes obsolete before it is called.

        ``validate`` will validate the data.
        originalKerningzSThe data in kerning.plist has been modified since it was converted to UFO 3 format.originalGroupszRThe data in groups.plist has been modified since it was converted to UFO 3 format.z'groups.plist is not properly formatted.)kerningr   groupsr   r   r   groupRenameMapsN)r   _readKerningr	   _readGroupsrk   dictitemsrl   listr   r   getGlyphSet)r6   ri   testKerning
testGroupsr   invalidFormatMessage	groupName	glyphList	glyphNamer   conversionMapsr&   r&   r'   _upConvertKerningQ  sR   







zUFOReader._upConvertKerningc                 C   s,   z	| j t|W S  t jjy   Y dS w )z
        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.
        N)r/   rJ   r   r2   r4   )r6   r7   r&   r&   r'   readBytesFromPath  s
   zUFOReader.readBytesFromPathNc                 C   sL   t |}z|du r| j|W S | jj|d|dW S  tjjy%   Y dS w )a  
        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.
        NrrF   rV   )r   r/   rL   r=   r2   r4   )r6   r7   rV   r&   r&   r'   getReadFileForPath  s   
zUFOReader.getReadFileForPathc           	      C   s   |du r| j }| t}|rt|tstdz|d }W n ty/   tdt d| j w |dd}zt	||f}W n9 t
yw } z-d| d	| d
t d| j }|rbddlm} |||t	 }td|| W Y d}~nd}~ww ||d< |S )z
        Read metainfo.plist and return raw data. 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.
        Nz)metainfo.plist is not properly formatted.formatVersionz#Missing required formatVersion in '' on formatVersionMinorr   zUnsupported UFO format (.z) in 'UnsupportedUFOFormatz^%s. Assuming the latest supported version (%s). Some data may be skipped or parsed incorrectlyr   )r   rD   METAINFO_FILENAMErk   r   r	   KeyErrorr/   
setdefaultr   
ValueErrorfontTools.ufoLib.errorsr   rA   loggerwarning)	r6   ri   r   formatVersionMajorr   r   rC   unsupportedMsgr   r&   r&   r'   _readMetaInfo  sF   

zUFOReader._readMetaInfoc                 C   s   | j |d}|d | _dS )z
        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.
        rh   r   N)r   r   r6   ri   r   r&   r&   r'   r     s   zUFOReader.readMetaInfoc                 C   s>   |  ti }| D ]\}}|drtt|||< q
|S )N)zpublic.kern1.zpublic.kern2.)rD   GROUPS_FILENAMEr   
startswithr   r   fromkeys)r6   r   r   r   r&   r&   r'   r     s   
zUFOReader._readGroupsc                 C   sX   |du r| j }| jtjk r| | | jd }n|  }|r*t|\}}|s*t||S )z
        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.
        Nr   )	r   r   r   r%   r   r   r   groupsValidatorr	   )r6   ri   r   validmessager&   r&   r'   
readGroups  s   
zUFOReader.readGroupsc                 C   s<   |du r| j }| jtjkrti i dS | j|d | jd S )aG  
        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.
        Nside1side2rh   r   )r   r   r   r%   r   r   r   )r6   ri   r&   r&   r'   #getKerningGroupConversionRenameMaps  s   
z-UFOReader.getKerningGroupConversionRenameMapsc                 C   s&   |  ti }|rt|tstd|S )Nz)fontinfo.plist is not properly formatted.)rD   FONTINFO_FILENAMErk   r   r	   r   r&   r&   r'   	_readInfo  s   zUFOReader._readInfoc              	   C   sD  |du r| j }| |}i }| jtjkr/tD ]}||}|dur%|||< qt|}t|}nK| jtj	krSt
t D ]\}}||}|du rIq;|||< q;t|}n'| jjtjjkrut
t D ]\}}||}|du roqa|||< qant| j|rt|}t
| D ]\}}zt||| W q ty   td| w dS )a|  
        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.
        NzMThe supplied info object does not support setting a necessary attribute (%s).)r   r   r   r   r#   r   get&_convertFontInfoDataVersion1ToVersion2&_convertFontInfoDataVersion2ToVersion3r$   r   #fontInfoAttributesVersion2ValueDatar   r   r%   #fontInfoAttributesVersion3ValueDataNotImplementedErrorvalidateInfoVersion3DatasetattrAttributeErrorr	   )r6   infori   infoDictinfoDataToSetattrvaluedataValidationDictr&   r&   r'   readInfo  sX   









	zUFOReader.readInfoc                 C   s   |  ti }|S rQ   )rD   KERNING_FILENAME)r6   r   r&   r&   r'   r   W  s   zUFOReader._readKerningc           	      C   s   |du r| j }| jtjk r| | | jd }n|  }|r*t|\}}|s*t|i }|D ]}|| D ]}|| | }||||f< q4q.|S )z
        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.
        Nr   )	r   r   r   r%   r   r   r   kerningValidatorr	   )	r6   ri   kerningNestedr   r   r   leftrightr   r&   r&   r'   readKerning[  s"   
zUFOReader.readKerningc                 C   s:   |du r| j }| ti }|rt|\}}|st||S )z
        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.
        N)r   rD   LIB_FILENAMEfontLibValidatorr	   )r6   ri   r   r   r   r&   r&   r'   readLiby  s   zUFOReader.readLibc                 C   s\   z!| j jtddd}| W  d   W S 1 sw   Y  W dS  t jjy-   Y dS w )zr
        Read features.fea. Return a string.
        The returned string is empty if the file is missing.
        r   rS   rV   N )r/   r=   FEATURES_FILENAMEreadr2   r4   )r6   rB   r&   r&   r'   readFeatures  s   (zUFOReader.readFeaturesc                 C   sD   | j tjk rttfgS | t}|r t|| j\}}|s t	||S )z
        Rebuild the layer contents list by checking what glyphsets
        are available on disk.

        ``validate`` will validate the layer contents.
        )
r   r   r%   DEFAULT_LAYER_NAMEDEFAULT_GLYPHS_DIRNAMErD   LAYERCONTENTS_FILENAMElayerContentsValidatorr/   r	   )r6   ri   contentsr   errorr&   r&   r'   _readLayerContents  s   

zUFOReader._readLayerContentsc                 C   s*   |du r| j }| |}dd |D }|S )z
        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.
        Nc                 S   s   g | ]\}}|qS r&   r&   )r_   	layerNamedirectoryNamer&   r&   r'   ra         z+UFOReader.getLayerNames.<locals>.<listcomp>)r   r   )r6   ri   layerContents
layerNamesr&   r&   r'   getLayerNames  s
   
zUFOReader.getLayerNamesc                 C   s>   |du r| j }| |}|D ]\}}|tkr|  S qtd)z
        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.
        Nz8The default layer is not defined in layercontents.plist.)r   r   r   r	   )r6   ri   r   r   layerDirectoryr&   r&   r'   getDefaultLayerName  s   
zUFOReader.getDefaultLayerNamec           
   	   C   s   ddl m} |du r| j}|du r| j}|du r| j|d}d}| |}|D ]\}}||kr3|} nq'|du r>td| z| j|}	W n tjj	yZ   td| d| dw ||	| j
||d	d
S )a  
        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.
        r   GlyphSetNrh   z&No glyphs directory is mapped to "%s".zNo 'z' directory for layer 'r;   T)ufoFormatVersionvalidateReadvalidateWriteexpectContentsFile)fontTools.ufoLib.glifLibr   r   r   r   r	   r/   ru   r2   r4   r   )
r6   r   r  r  r   	directoryr   storedLayerNamestoredLayerDirectory
glyphSubFSr&   r&   r'   r     s8   
zUFOReader.getGlyphSetc           	      C   sl   |du r| j }| j||dd}| }i }| D ]\}}|D ]}||v r-|| | q|g||< qq|S )zf
        Return a dictionary that maps unicode values (ints) to
        lists of glyph names.
        NT)r  r  )r   r   getUnicodesr   append)	r6   r   ri   glyphSetallUnicodescmapr   unicodescoder&   r&   r'   getCharacterMapping  s   zUFOReader.getCharacterMappingc                 C   sz   z	| j t| _W n t jjy   g  Y S  t jjy"   tdw zdd | jj	 D W S  t jj
y<   g  Y S w )z
        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.
        z6The UFO contains a "data" file instead of a directory.c                 S   s   g | ]}| d qS )rc   )lstripr^   r&   r&   r'   ra     s    z5UFOReader.getDataDirectoryListing.<locals>.<listcomp>)r/   ru   DATA_DIRNAME_dataFSr2   r4   DirectoryExpectedr	   walkfilesResourceErrorr   r&   r&   r'   getDataDirectoryListing  s   z!UFOReader.getDataDirectoryListingc              	   C   s   | j tjk rg S |du r| j}z| jt | _}W n tjj	y'   g  Y S  tjj
y3   tdw g }|dD ]4}|jrAq;|ri||j}t|d\}}W d   n1 s[w   Y  |rh||j q;||j q;|S )a$  
        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.
        Nz9The UFO contains an "images" file instead of a directory.rc   )fileObj)r   r   r%   r   r/   ru   IMAGES_DIRNAME	_imagesFSr2   r4   r  r	   rs   r\   rL   r]   pngValidatorr  )r6   ri   imagesFSresultr7   rO   r   r   r&   r&   r'   getImageDirectoryListing  s4   	z"UFOReader.getImageDirectoryListingc                 C   sl   t |}zz| j}W n ty   | jt}Y nw ||}W |S  tjjy5   t	d| d| j w )zZ
        Return bytes for the file named 'fileName' inside the 'data/' directory.
        zNo data file named 'r   )
r   r  r   r/   ru   r  rJ   r2   r4   r	   )r6   r@   dataFSr   r&   r&   r'   readData=  s   
zUFOReader.readDatac                 C   s   |du r| j }| jtjk rtd| jj dt|}zz| j}W n ty0   | j	
t}Y nw ||}W n t	jjyK   td| d| j	 w |r[t|d\}}|s[t||S )z
        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.
        Nz%Reading images is not allowed in UFO r   zNo image file named 'r   r   )r   r   r   r%   r	   r   r   r  r   r/   ru   r  rJ   r2   r4   r  )r6   r@   ri   r  r   r   r   r&   r&   r'   	readImageM  s,   
zUFOReader.readImagec                 C   s   | j r
| j  d S d S rQ   )rx   r/   r   r   r&   r&   r'   r   j  s   zUFOReader.closec                 C   s   | S rQ   r&   r   r&   r&   r'   	__enter__n  s   zUFOReader.__enter__c                 C   s   |    d S rQ   )r   )r6   exc_type	exc_valueexc_tbr&   r&   r'   __exit__q  s   zUFOReader.__exit__)TrQ   )NNNNN)'r    r!   r"   __doc__r   r   propertyr7   r   r   r   r   fileStructurer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r"  r$  r   r%  r)  r&   r&   r&   r'   r      sV    
K



6


*


;





)
$
r   c                       s@  e Zd ZdZ				d?ddZdd Zeed	d
Zdd Zdd Z	d@ddZ
dAddZeZdd Zdd Zdd ZdBddZdBddZdBdd ZdBd!d"ZdBd#d$ZdCd%d&Zd'd( Z						dDd)d*Z		dEd+d,Z				dFd-d.ZdGd/d0Zd1d2 Zd3d4 Zd5d6 ZdBd7d8ZdBd9d:ZdBd;d<Z  fd=d>Z!  Z"S )Hr   a=  Write the various components of a .ufo.

    Attributes:
        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.
    Ncom.github.fonttools.ufoLibTc              
   C   s  zt |}W n ty  } zddlm} |d||d }~ww t|dr*| }t|trtj	
|}tj	|}|rjt|}	|d urgzt|}W n tyY   td| w ||	urftd|	|f n|	}n|d u rqtj}tj	|}
|
rtj	|
std| |tju r|rtj }tjj|dd	}tj|| W d    n1 sw   Y  d
d |dD }t|dkrtdt| |j|d tjjd| _n0tj	tj	 |d d }tjj|ddd}|!| |j|tjjd| _n	tj"j#|dd| _|| _$|| _%d| _&nht|tj'j(rn|}z|)  W n tj*j+y/   td| w || _z|,d}W n tj*j-yJ   t|}Y nw |r`|tjur`dd l.}|j/dt0dd tj| _$|t1| _%d| _&n	t2dt3|j4 t5|| _6|| _7|| _8d | _9|| _:d }| j%r| j;|d}|d }||krddlm} |d| d| di | _<|d ur|j=dkrt>| ?|| _<n| jt@rtAt@i| _<| B  d S ) Nr   r   zUnsupported UFO format: rR   z&Invalid or unsupported structure: '%s'zLA UFO with a different structure (%s) already exists at the given path: '%s'z.Cannot write to '%s': directory does not existrS   r   c                 S   rX   rY   r[   r^   r&   r&   r'   ra     rb   z&UFOWriter.__init__.<locals>.<listcomp>rc   r   rf   rd   .ufoTrT   createrg   z?The 'structure' argument is not used when input is an FS objectr   r   Fz-Expected a path string or fs object, found %srh   r   z2The UFO located at this path is a higher version (z) than the version (z6) that is trying to be written. This is not supported.r   )Cr   r   r   r   rj   rR   rk   rl   osr7   normpathrI   rm   r   r	   r+   dirnameisdirr*   r/   tempfsTempFSrn   ro   copycopy_fsrs   rt   ru   rv   rw   splitextbasenamemakedirrp   rq   ry   rG   rx   rz   r{   r|   r2   r}   r~   r   r   r   UserWarningr   r   r   r    r   r   r   _fileCreator_downConversionKerningDatar   r   r   r   r   r   r   r   _writeMetaInfo)r6   r7   r   fileCreatorr   ri   rC   r   havePreviousFileexistingStructuredirNamer   origFSr   rootDirr   r   previousFormatVersionmetaInfor&   r&   r'   r     s   







zUFOWriter.__init__c                 C   r   rQ   )r>  r   r&   r&   r'   _get_fileCreator0  r   zUFOWriter._get_fileCreatorzMThe file creator of the UFO. This is set into metainfo.plist during __init__.r   c                 C   s   t |ts	tdt|}t|}|j|std| | j|r)td| | jjtj|dd |j	|rHtj
|j|| j| dS tj
|j|| j| dS )z
        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.
        z,The reader must be an instance of UFOReader.z.The reader does not have data located at "%s".z!A file named "%s" already exists.TrecreateN)rk   r   r	   r   r/   rI   makedirsr7   r4  r5  r8  copy_dir	copy_file)r6   reader
sourcePathdestPathr&   r&   r'   copyFromReader:  s   
zUFOWriter.copyFromReaderc                 C   s   t |}| jr| j|r|| j|krdS z
| j|| W dS  tjjy0   td|  tjj	yN   | jj
tj|dd | j|| Y dS w )ae  
        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.
        NzA directory exists at '%s'TrJ  )r   rG   r/   isfilerJ   rK   r2   FileExpectedr	   r4   rL  r7   r4  )r6   r7   r   r&   r&   r'   writeBytesToPathQ  s   zUFOWriter.writeBytesToPathrE   c              
   C   s   t |}z
| jj|||dW S  tjjyY } z=|d }|dkr'W Y d}~dS |dks3|dks3|dkrN| jjtj|dd	 | jj|||dW  Y d}~S W Y d}~dS d}~w tjjyz } zt	d
| d| j d| W  Y d}~S d}~ww )ag  
        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.
        r   r   r   NrE   axTrJ  rW   r   r<   )
r   r/   r=   r2   r4   rL  r7   r4  r  r	   )r6   r7   rF   rV   rC   mr&   r&   r'   getFileObjectForPathe  s    
(zUFOWriter.getFileObjectForPathFc                 C   s   t |}z| j| W n( tjjy   | j| Y n tjjy4   |s2td| d| j Y nw |rItj	|}|rKtj
| j| dS dS dS )a_  
        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.
        r;   z' does not exist on N)r   r/   remover2   rT  
removetreer4   r	   r7   r4  toolsremove_empty)r6   r7   forceremoveEmptyParentsparentr&   r&   r'   
removePath~  s    	zUFOWriter.removePathc              
   C   sh   | j }|dur0tj|r2z	t|d W dS  ty/ } ztd| W Y d}~dS d}~ww dS dS )z
        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.
        NzFailed to set modified time: %s)r   r2  r7   rI   utimeOSErrorr   r   )r6   r7   rC   r&   r&   r'   setModificationTime  s   zUFOWriter.setModificationTimec                 C   s:   t | j| jjd}| jjdkr| jj|d< | t| d S )N)creatorr   r   r   )r   r>  r   r   minorrP   r   )r6   rH  r&   r&   r'   r@    s   zUFOWriter._writeMetaInfoc                 C   sP   | j tjkrdS i }dD ]}t||  D ]\}}|||< qqt|d| _dS )aW  
        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.
        Nr   )groupRenameMap)r   r   r%   r   r   r   r?  )r6   mapsremapside	writeNamedataNamer&   r&   r'   #setKerningGroupConversionRenameMaps  s   
z-UFOWriter.setKerningGroupConversionRenameMapsc                 C   s   |du r| j }|rt|\}}|st|| jtjk rU| jdurU| jd }i }t| D ]\}}||v r6q-|||< q-t| D ]\}}||vrJqA|| }|||< qA|}i }	| D ]
\}
}t||	|
< q[|	rp| 	t
|	 dS | jr}| jt
ddd dS dS )z
        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.
        Nrg  TFr^  r_  )r   r   r	   r   r   r%   r?  r   r   rP   r   rG   ra  )r6   r   ri   r   r   ri  remappedGroupsr]   r   	groupsNewkeyr   r&   r&   r'   writeGroups  s8   



zUFOWriter.writeGroupsc              	   C   s   |du r| j }i }tt D ]%}t||r4zt||}W n ty*   td| w |du r0q|||< q| jt	j
krB|rAt|}n%| jt	jkrSt|}|rRt|}n| jt	jkrgt|}|rct|}t|}|rq| t| dS dS )a  
        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.
        NzMThe supplied info object does not support getting a necessary attribute (%s).)r   r   r   keysrj   getattrr   r	   r   r   r%   r   r$   &_convertFontInfoDataVersion3ToVersion2validateInfoVersion2Datar#   &_convertFontInfoDataVersion2ToVersion1rP   r   )r6   r   ri   infoDatar   r   r&   r&   r'   	writeInfo  sF   
zUFOWriter.writeInfoc                 C   sz  |du r| j }|rRd}t|st|t| D ]8\}}t|ttfs(t|t|dks2t|t|d ts=t|t|d tsHt|t|t	sQt|q| j
tjk r| jdur| jd }i }t| D ]\\}}	}|||}||	|	}	||||	f< qj|}i }
| D ]\}}|||f }||
vri |
|< ||
| |< q|
r| t|
 dS | jr| jtddd	 dS dS )
a  
        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.
        Nz&The kerning is not properly formatted.r   r   r   rg  TFrn  )r   isDictEnoughr	   r   r   rk   tuplert   rl   r
   r   r   r%   r?  r   rs  rP   r   rG   ra  )r6   r   ri   r   pairr   ri  remappedKerningr   r   kerningDictr   r   r&   r&   r'   writeKerning2  sL   


zUFOWriter.writeKerningc                 C   s\   |du r| j }|rt|\}}|st||r| t| dS | jr,| jtddd dS dS )z
        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.
        NTFrn  )r   r   r	   rP   r   rG   ra  )r6   libDictri   r   r   r&   r&   r'   writeLibk  s   zUFOWriter.writeLibc                 C   sp   |du r| j }| jtjkrtd|rt|tstd|r)| t|	d dS | j
r6| jtddd dS dS )zd
        Write features.fea. This method requires a
        features string as an argument.
        Nz4features.fea is not allowed in UFO Format Version 1.zThe features are not text.utf8TFrn  )r   r   r   r#   r	   rk   rl   rU  r   encoderG   ra  )r6   featuresri   r&   r&   r'   writeFeatures  s   
zUFOWriter.writeFeaturesc                    s   |du r j } jtjk rdS |dur(g }|D ]}|du rt}|| q|}nt j }|r@t	|t	 j kr@t
d fdd|D } t| dS )z
        Write the layercontents.plist file. This method  *must* be called
        after all glyph sets have been written.
        NzMThe layer order content does not match the glyph sets that have been created.c                    s   g | ]	}| j | fqS r&   )r   )r_   r   r   r&   r'   ra     s    z0UFOWriter.writeLayerContents.<locals>.<listcomp>)r   r   r   r%   r   r  r   r   rs  setr	   rP   r   )r6   
layerOrderri   newOrderr   r   r&   r   r'   writeLayerContents  s(   
zUFOWriter.writeLayerContentsc                 C   sX   d }t | j D ]\}}|d u r|tkr|} n	||kr!|} nq	|s*td| |S )Nz>Could not locate a glyph set directory for the layer named %s.)r   r   r   r   r	   )r6   r   foundDirectoryexistingLayerNamer   r&   r&   r'   _findDirectoryForLayerName  s    z$UFOWriter._findDirectoryForLayerNamec           	      C   s   |du r| j }|du r| j }| jtjk r$|r|dur$td| jj d|du rA|rA| j D ]
\}}|tkr9|}q/|du r@t	}n
|du rK|sKtd| jtjk rZ| j
||||dS | jjtjjkrm| j||||||dS t| j)aW  
        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.
        Nz,Only the default layer can be writen in UFO r   z5A layer name must be provided for non-default layers.)glyphNameToFileNameFuncr  )r   defaultLayerr  r  )r   r   r   r%   r	   r   r   r   r   r   _getDefaultGlyphSet_getGlyphSetFormatVersion3r   )	r6   r   r  r  r  r  r  r  r  r&   r&   r'   r     sL   
	zUFOWriter.getGlyphSetc                 C   s2   ddl m} | jjtdd}|||| j|||dS )Nr   r   TrJ  r  r  r  r  r  )r  r   r/   r<  r   r   )r6   r  r  r  r  r   r	  r&   r&   r'   r     s   zUFOWriter._getDefaultGlyphSetc                 C   s   ddl m} |r)| j D ]\}}	|	tkr ||krtd| q||kr(tdq|| jv r4| j| }	n|r9t}	ndd | j D }
t||
dd}	| jj	|	d	d
}|	| j|< |||| j
|||dS )Nr   r   z@Another layer ('%s') is already mapped to the default directory.z8The layer name is already mapped to a non-default layer.c                 S      h | ]}|  qS r&   lower)r_   dr&   r&   r'   	<setcomp>7  r   z7UFOWriter._getGlyphSetFormatVersion3.<locals>.<setcomp>glyphs.existingprefixTrJ  r  )r  r   r   r   r   r	   valuesr   r/   r<  r   )r6   r  r  r   r  r  r  r   r  r  r  r	  r&   r&   r'   r    sD   	

z$UFOWriter._getGlyphSetFormatVersion3c                 C   s   | j tjk rdS ||kr#| j| tkr|sdS | j| tkr"|r"dS n|du r)t}|| jv r4td| |rAt| j v rAtd| |}|rKt}ndd | j D }t	||dd}| j|= || j|< | j
j||dd	 dS )
z
        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.
        Nz A layer named %s already exists.zA default layer already exists.c                 S   r  r&   r  )r_   r]   r&   r&   r'   r  o  r   z+UFOWriter.renameGlyphSet.<locals>.<setcomp>r  r  Tr0  )r   r   r%   r   r   r   r	   r  r  r   r/   movedir)r6   r   newLayerNamer  oldDirectorynewDirectoryr  r&   r&   r'   renameGlyphSetI  s4   


zUFOWriter.renameGlyphSetc                 C   s4   | j tjk rdS | |}| j|dd | j|= dS )z:
        Remove the glyph set matching layerName.
        NF)r_  )r   r   r%   r  ra  r   )r6   r   r  r&   r&   r'   deleteGlyphSety  s
   
zUFOWriter.deleteGlyphSetc                 C   s   |  t dt| | dS )zj
        Write data to fileName in the 'data' directory.
        The data must be a bytes string.
        rc   N)rU  r  r   )r6   r@   r   r&   r&   r'   	writeData  s   zUFOWriter.writeDatac                 C   s   |  t dt|  dS )zI
        Remove the file named fileName from the data directory.
        rc   N)ra  r  r   )r6   r@   r&   r&   r'   
removeData  s   zUFOWriter.removeDatac                 C   sn   |du r| j }| jtjk rtd| jj dt|}|r*t|d\}}|s*t|| t	 d| | dS )zg
        Write data to fileName in the images directory.
        The data must be a valid PNG.
        NImages are not allowed in UFO r   r#  rc   )
r   r   r   r%   r	   r   r   r  rU  r  )r6   r@   r   ri   r   r   r&   r&   r'   
writeImage  s   zUFOWriter.writeImagec                 C   s<   | j tjk rtd| j j d| t dt|  dS )zS
        Remove the file named fileName from the
        images directory.
        r  r   rc   N)r   r   r%   r	   r   ra  r  r   )r6   r@   ri   r&   r&   r'   removeImage  s
   zUFOWriter.removeImagec                 C   sd   |du r| j }| jtjk rtd| jj dt dt| }t dt| }| ||| dS )z
        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.
        Nr  r   rc   )	r   r   r   r%   r	   r   r  r   rR  )r6   rO  sourceFileNamedestFileNameri   rP  rQ  r&   r&   r'   copyImageFromReader  s   zUFOWriter.copyImageFromReaderc                    s   | j r=| jtju r=tjtj| jd d }t	j
j| jddd}t	j| j	|| W d    n1 s8w   Y  t   d S )Nr   r/  TrS   rT   )rG   ry   r   r*   r2  r7   r:  r;  r   r/   rn   ro   r8  r9  r<  superr   )r6   rF  destFS	__class__r&   r'   r     s   zUFOWriter.close)Nr.  NT)rE   N)FTrQ   r*  )NTNNNF)NF)NTNF)F)#r    r!   r"   r+  r   rI  r,  rA  rR  rU  rY  ra  removeFileForPathrd  r@  rm  rr  ry  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r   __classcell__r&   r&   r  r'   r   z  sf    
 



7
.
9


F


60


r   c                 C   sF   t | rtjS tj| rtjS tj| rt	d|  t	d|  )zReturn UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str)
    is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a
    directory.
    Raise UFOLibError if it is a file with unknown structure, or if the path
    does not exist.
    z7The specified UFO does not have a known structure: '%s'zNo such file or directory: '%s')
zipfile
is_zipfiler   r*   r2  r7   r5  r+   rS  r	   )ufo_pathr&   r&   r'   rm     s   
rm   c                 C   s@   t j| \}}dd|ddd dg}t j||S )a"  
    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
    r   Nufo)r2  r7   splitjoin)r7   dirr]   r&   r&   r'   r     s   "r   c                 C   ^   t |  }|d}|d}|d}|dur|||}|S |tkr)|||}|S ||}|S )a  
    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.
    r   valueValidatorvalueOptionsN)r   r   genericTypeValidatorr   r   r   	valueType	validatorr  isValidValuer&   r&   r'   r        





r   c                 C   J   i }t |  D ]\}}t||}|std| d|d|||< q|S )a  
    This performs very basic validation of the value for infoData
    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 values
    are 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.
    Invalid value for attribute  ().)r   r   r   r	   rx  validInfoDatar   r   r  r&   r&   r'   rv       


rv  c                 C   r  )a  
    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.
    r   r  r  N)r   r   r  r  r&   r&   r'   r   0  r  r   c                 C   r  )a  
    This performs very basic validation of the value for infoData
    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 values
    are 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.
    r  r  r  )r   r   r   r	   r  r&   r&   r'   r   J  r  r      )r   r   r            	      @   )r   r   r   r   r  r  >(   noteyearfondIDnoticelicensexHeightascenderdesignerfondNamefontNamefullNamemenuNamettVendoruniqueID	capHeight	copyright	createdBy	descender	fontStyle	msCharSet	otMacName	styleName	trademark	ttVersion	vendorURL	widthName
familyName
licenseURL
slantAngle
ttUniqueID
unitsPerEm
weightNamedesignerURLitalicAngleotStyleNameweightValuedefaultWidthotFamilyNameversionMajorversionMinorr  )r   r  styleMapFamilyNamestyleMapStyleName)r   r  r  r  r  r  r  r  r  r  r  r  r  r  openTypeHeadCreatedopenTypeHeadLowestRecPPEMopenTypeHeadFlagsintegerList)r   r  r  openTypeHheaAscenderopenTypeHheaDescenderopenTypeHheaLineGapopenTypeHheaCaretSlopeRiseopenTypeHheaCaretSlopeRunopenTypeHheaCaretOffsetopenTypeNameDesigneropenTypeNameDesignerURLopenTypeNameManufactureropenTypeNameManufacturerURLopenTypeNameLicenseopenTypeNameLicenseURLopenTypeNameVersionopenTypeNameUniqueIDopenTypeNameDescriptionopenTypeNamePreferredFamilyName"openTypeNamePreferredSubfamilyNameopenTypeNameCompatibleFullNameopenTypeNameSampleTextopenTypeNameWWSFamilyNameopenTypeNameWWSSubfamilyNameopenTypeOS2WidthClassopenTypeOS2WeightClassopenTypeOS2SelectionopenTypeOS2VendorIDopenTypeOS2PanoseopenTypeOS2FamilyClassopenTypeOS2UnicodeRangesopenTypeOS2CodePageRangesopenTypeOS2TypoAscenderopenTypeOS2TypoDescenderopenTypeOS2TypoLineGapopenTypeOS2WinAscentopenTypeOS2WinDescentopenTypeOS2TypeopenTypeOS2SubscriptXSizeopenTypeOS2SubscriptYSizeopenTypeOS2SubscriptXOffsetopenTypeOS2SubscriptYOffsetopenTypeOS2SuperscriptXSizeopenTypeOS2SuperscriptYSizeopenTypeOS2SuperscriptXOffsetopenTypeOS2SuperscriptYOffsetopenTypeOS2StrikeoutSizeopenTypeOS2StrikeoutPositionopenTypeVheaVertTypoAscenderopenTypeVheaVertTypoDescenderopenTypeVheaVertTypoLineGapopenTypeVheaCaretSlopeRiseopenTypeVheaCaretSlopeRunopenTypeVheaCaretOffsetpostscriptFontNamepostscriptFullNamepostscriptSlantAnglepostscriptUniqueIDpostscriptUnderlineThicknesspostscriptUnderlinePositionpostscriptIsFixedPitchpostscriptBlueValuespostscriptOtherBluespostscriptFamilyBluespostscriptFamilyOtherBluespostscriptStemSnapHpostscriptStemSnapVpostscriptBlueFuzzpostscriptBlueShift)	postscriptBlueScalepostscriptForceBoldpostscriptDefaultWidthXpostscriptNominalWidthXpostscriptWeightNamepostscriptDefaultCharacterpostscriptWindowsCharacterSetmacintoshFONDFamilyIDmacintoshFONDNameopenTypeGaspRangeRecordsdictListopenTypeNameRecordswoffMajorVersionwoffMinorVersionwoffMetadataUniqueIDwoffMetadataVendorwoffMetadataCredits)woffMetadataDescriptionwoffMetadataLicensewoffMetadataCopyrightwoffMetadataTrademarkwoffMetadataLicenseewoffMetadataExtensions
guidelinesr  c                 C   s&   i }t |  D ]\}}|||< q|S rQ   )r   r   )r  flippedrq  r   r&   r&   r'   	_flipDict  s   
rX  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rC  r  r  r  rF  rG  rA  rE  )	r  r  r  r  r  r  r  r  r  regularitalicboldzbold italic)r  r       !   r   r   r   r        r  r  r  )	zUltra-condensedzExtra-condensed	CondensedzSemi-condensedzMedium (normal)zSemi-expandedExpandedzExtra-expandedzUltra-expandedNormalAllmediumMediumM                  
                                                   )         c                 C   s   t |trt||krt|}|durc| dkr.t|}|du r+td|d|  d|}n5| dkrIt|}|du rFtd|d|  d|}n| dkrct|}|du ratd|d|  d|}t| | } | |fS )z
    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.
    Nr  Cannot convert value () for attribute r   r  r  )	rk   floatint_fontStyle1To2r   r	   _widthName1To2_msCharSet1To2fontInfoAttributesVersion1To2r   r   vr&   r&   r'   r     s6   



r   c                 C   sV   |dur!| dkrt |}n| dkrt|}n	| dkr!t|}t| | } | |fS )z
    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.
    Nr  r  rE  )_fontStyle2To1r   _widthName2To1_msCharSet2To1fontInfoAttributesVersion2To1r   r   r&   r&   r'   r   	  s   
r   c                 C   sn   i }t |  D ],\}}|dkr|dkrqt||\}}|tvr!q|d u r0td|d| d|||< q|S )Nr  r  r  r  r   )r   r   r   r   r	   r   	convertedr   r   newAttrnewValuer&   r&   r'   r   	  s   
r   c                 C   s\   i }t |  D ]#\}}t||\}}|tvrq|d u r'td|d| d|||< q|S )Nr  r  r   )r   r   r   r   r	   r  r&   r&   r'   rw  5	  s   
rw  >   r  r  r  r  >   r  r  r  r  r  r  r  r  r/  r(  r  r  r   r!  r"  r#  r$  r%  r,  r)  r*  r&  r'  r+  c              	   C   s   | t v rzt|}W n ttfy   td|  w | tv r9ztt|}W | |fS  ttfy8   td|  w | tv rezt	t|}W n ttfyT   td|  w |t|kr_t|}||kre|}| |fS )z
    Convert value from version 2 to version 3 format.
    Returns the new attribute name and the converted value.
    If the value is None, None will be returned for the new value.
    zCould not convert value for %s.)
_ufo2To3FloatToIntroundr   r   r	   _ufo2To3NonNegativeIntr  abs_ufo2To3NonNegativeIntOrFloatr  r  r&   r&   r'   6convertFontInfoValueForAttributeFromVersion2ToVersion3o	  s0   r  c                 C   s   | |fS )z
    Convert value from version 3 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.
    r&   r  r&   r&   r'   6convertFontInfoValueForAttributeFromVersion3ToVersion2	  s   r  c                 C   s>   i }t |  D ]\}}t||\}}|tvrq|||< q|S rQ   )r   r   r  r   r  r&   r&   r'   ru  	  s   
ru  c                 C   s4   i }t |  D ]\}}t||\}}|||< q|S rQ   )r   r   r  )r   r  r   r   r&   r&   r'   r   	  s   
r   __main__)r+  r2  r8  r   r   loggingr  enumcollectionsr   r/   fs.basefs.subfs	fs.errorsfs.copyfs.osfsfs.zipfs	fs.tempfsfs.toolsfontTools.miscr   fontTools.ufoLib.validatorsfontTools.ufoLib.filenamesr   fontTools.ufoLib.convertersr   r   r	   fontTools.ufoLib.utilsr
   r   __all____version__	getLoggerr    r   r   r  r  r   r   r   r   r   r   r   LAYERINFO_FILENAMEr   r{  Enumr   __str__r   r,   r   r   r   rm   r   r   rv  r   r   r   range fontInfoOpenTypeHeadFlagsOptions#fontInfoOpenTypeOS2SelectionOptions'fontInfoOpenTypeOS2UnicodeRangesOptions(fontInfoOpenTypeOS2CodePageRangesOptionsfontInfoOpenTypeOS2TypeOptionsr   r   rl   "fontInfoStyleMapStyleNameValidatorr  r  $fontInfoOpenTypeHeadCreatedValidatorgenericIntListValidator&fontInfoOpenTypeOS2WidthClassValidator'fontInfoOpenTypeOS2WeightClassValidator*fontInfoVersion2OpenTypeOS2PanoseValidator'fontInfoOpenTypeOS2FamilyClassValidatorbool fontInfoPostscriptBluesValidator%fontInfoPostscriptOtherBluesValidator fontInfoPostscriptStemsValidator.fontInfoPostscriptWindowsCharacterSetValidatorr   r  rs  r   r   updategenericNonNegativeIntValidator!genericNonNegativeNumberValidator*fontInfoVersion3OpenTypeOS2PanoseValidator)fontInfoOpenTypeGaspRangeRecordsValidator$fontInfoOpenTypeNameRecordsValidator%fontInfoWOFFMetadataUniqueIDValidator#fontInfoWOFFMetadataVendorValidator$fontInfoWOFFMetadataCreditsValidator(fontInfoWOFFMetadataDescriptionValidator$fontInfoWOFFMetadataLicenseValidator&fontInfoWOFFMetadataCopyrightValidator&fontInfoWOFFMetadataTrademarkValidator%fontInfoWOFFMetadataLicenseeValidator'fontInfoWOFFMetadataExtensionsValidatorguidelinesValidatorr   r   r   dataDictr  rX  r  r  r   r  r  r  r  r  r  r   r   r   rw  r  r  r  r  r  ru  r   doctesttestmodr&   r&   r&   r'   <module>   sN   "
	
Q     4      X+





	





 !
"
#
$
%
&
'
(
)
*
+
,
-
.
/
0147
<=@CHMNOPQRWXYZ[\]^_`abc
d
ef
g
hi
jkl
mnqtwz}       

	













 
!
"#&
)
*
+
,-0369<
R

	
	
$	

