a
    w=ic4                 `   @   s  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e/eej0Z1ej2e1_2G dd dej0Z3G dd dZ4G dd  d e4Z5G d!d" d"e5Z6e6Z7d#d$ Z8d%d& Z9d'd( Z:d)d* Z;d+d, Z<d-d. Z=e>e?d d/Z@g d0ZAe>e?d d1ZBe>e?d d2ZCg d3ZDh d4ZEeFeGd5eFeGd5eFeGd5eFeGeHd6eFeId5eFeId5eFeId5eFeGd5eFeGd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeJeIfd5eFeGd5eFeGeKd6eFeIeJfd5eFd7eLe@d8eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeId5eFeId5eFeIeJfd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeGd5eFeIeMd6eFeIeNd6eFd7eLeAd8eFeGd5eFd7eOd6eFd7ePd6eFd7eLeBd8eFd7eLeCd8eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFd7eLeDd8eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeIeJfd5eFeId5eFeId5eFeIeJfd5eFeGd5eFeGd5eFeJeIfd5eFeId5eFeIeJfd5eFeIeJfd5eFeQd5eFd7eRd6eFd7eSd6eFd7eRd6eFd7eSd6eFd7eTd6eFd7eTd6eFeIeJfd5eFeIeJfd5eFeJeIfd5eFeQd5eFeIeJfd5eFeIeJfd5eFeGd5eFeGd5eFeIeUd6eFeId5eFeGd5d9^ZVeWeVX ZYeeVZZeZ[eFeIe\d6eFeIeJfe]d6eFeIe]d6eFeId5eFeId5eFeId5eFeId5eFd7e^d6eFeId5eFeId5eFeId5eFeIe]d6eFeIe]d6eFeId5eFeId5eFeId5eFeId5eFeId5eFeId5eFeId5eFeId5eFeId5eFeId5eFd:e_d6eFd:e`d6eFeId5eFeId5eFeId5eFeId5eFeIe\d6eFeIe\d6eFeFead6eFeFebd6eFeFecd6eFeFedd6eFeFeed6eFeFefd6eFeFegd6eFeFehd6eFe>eid6eFe>ejd6d;) eWeZX Zke>eVl D ]\ZmZnd<envrVeoend<< qVe>eZl D ]\ZmZnd<envreoend<< qd=d> Zpd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYZqepeqZreWeqX ZsdZd[d\d]d^ZtepetZudZetd < d_d`dadbdcdddedfdgdh	ZvepevZwdcevdi< dcevdj< dcevdk< dcevdl< d_d`dadbdcdddedfdgdmdndodpdqd/drdsdtdudvdwZxepexZydxdy Zzdzd{ Z{d|d} Z|d~d Z}h dZ~dhZh dZdd Zdd Zdd Zdd Ze!dkrd dlZe  dS )    N)deepcopy)fsdecode)OrderedDict)plistlib)*)userNameToFileName)%convertUFO1OrUFO2KerningToUFO3Kerning)UFOLibError)numberTypes_VersionTupleEnumMixin)makeUFOPathr	   	UFOReader	UFOWriterUFOReaderWriterUFOFileStructurefontInfoAttributesVersion1fontInfoAttributesVersion2fontInfoAttributesVersion3$deprecatedFontInfoAttributesVersion2)validateFontInfoVersion2ValueForAttribute)validateFontInfoVersion3ValueForAttribute6convertFontInfoValueForAttributeFromVersion1ToVersion26convertFontInfoValueForAttributeFromVersion2ToVersion1z3.0.0ZglyphsdataZ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$   j/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/fontTools/ufoLib/__init__.pyr   `   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   k   s   r   c                   @   s&   e Zd Zdd ZdddZdd ZdS )	
_UFOBaseIOc              	   C   sJ   z| j jt|dgdj}W n  t jjt jjfy<   Y dS 0 | S dS )z
		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errorsZMissingInfoNamespaceResourceNotFound	timestamp)selfpathdtr$   r$   r%   getFileModificationTimew   s
    z"_UFOBaseIO.getFileModificationTimeNc              
   C   s   z>| j |d}t|W  d   W S 1 s20    Y  W nx t jjyx   |du rltd|| j f n| Y S Y n@ ty } z(td| d| j  d| W Y d}~n
d}~0 0 dS )al  
		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   loadr0   r1   r	   	Exception)r3   fileNamedefaultfer$   r$   r%   	_getPlist   s    
.z_UFOBaseIO._getPlistc                 C   s   | j r~zt|}W n8 tyL } z td|| j|f W Y d}~n
d}~0 0 | j|rn|| j|krndS | j|| nz| jj	|ddZ}zt
|| W n8 ty } z td|| j|f W Y d}~n
d}~0 0 W d   n1 s0    Y  dS )aO  
		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)r3   r=   objr   r@   fpr$   r$   r%   _writePlist   s*    

z_UFOBaseIO._writePlist)N)r   r   r    r6   rA   rM   r$   r$   r$   r%   r*   u   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dHddZdIddZdd ZdJddZdKd d!Zd"d# ZdLd$d%Zd&d' ZdMd(d)ZdNd*d+Zd,d- Zd.d/ ZdOd0d1ZdPd2d3ZdQd4d5ZdRd6d7Zd8d9 Z dSd:d;Z!d<d= Z"dTd>d?Z#d@dA Z$dBdC Z%dDdE Z&dS )Ur   z
	Read the various components of the .ufo.

	By default read data is validated. Set ``validate`` to
	``False`` to not validate the data.
	Tc              
   C   s  t |dr| }t|trt|}z.|tju rDtjj	|ddd}ntj
|}W n< tjjy } z td| d| W Y d }~n
d }~0 0 |tju rdd |d	D }t|d
kr|j|d tjjd| _qtdt| n|| _d| _|| _nt|tjjr|}z|  W n$ tjjy>   td| Y n0 || _z|d	}W n  tjjyt   t|}Y n0 d| _tj| _ntdt|j t || _!|| _"d | _#z| j$|d W n ty   | %   Y n0 d S )N
__fspath__Futf-8writeencodingunable to open 'z': c                 S   s"   g | ]}|j r|jd kr|jqS Z__MACOSXis_dirname.0pr$   r$   r%   
<listcomp>   s   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)&hasattrrN   
isinstancestr_sniffFileStructurer   r(   r-   zipfsZipFSosfsOSFSr0   ZCreateFailedr	   scandirlenopendirsubfsClosingSubFS_shouldClose_fileStructurebaseFScheckFilesystemClosed
getsyspath	NoSysPathr)   	TypeErrortyper   r   _path	_validate_upConvertedKerningDatareadMetaInfoclose)r3   r4   rb   	structureparentFSr@   rootDirs
filesystemr$   r$   r%   __init__   sd    


*




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DeprecationWarningrz   r3   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   s   | j S )zpThe (major, minor) format version of the UFO.
		This is determined by reading metainfo.plist during __init__.
		)r   r3   r$   r$   r%   formatVersionTuple8  s    zUFOReader.formatVersionTuplec                 C   s   | j S N)rq   r   r$   r$   r%   _get_fileStructure?  s    zUFOReader._get_fileStructurezVThe file structure of the UFO: either UFOFileStructure.ZIP or UFOFileStructure.PACKAGEc                 C   s  | j rD|  }|| j d kr$td|  }|| j d krBtdn|  }|rd}t|tsft|| D ]J\}}t|tst|nt|tst||D ]}t|tst|qqnti |  i |d| _ t	| j d t
| j d |  \}	}}
|	| j d< || j d< |
| j d	< d
S )aF  
		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	   _readGroupsrd   dictitemsre   listr   r   getGlyphSet)r3   rb   ZtestKerningZ
testGroupsr   invalidFormatMessage	groupName	glyphList	glyphNamer   ZconversionMapsr$   r$   r%   _upConvertKerningL  sD    









zUFOReader._upConvertKerningc                 C   s0   z| j t|W S  t jjy*   Y dS 0 dS )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-   rG   r   r0   r1   )r3   r4   r$   r$   r%   readBytesFromPath~  s    zUFOReader.readBytesFromPathNc                 C   sT   t |}z.|du r | j|W S | jj|d|dW S W n tjjyN   Y dS 0 dS )ad  
		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rC   rR   )r   r-   rI   r:   r0   r1   )r3   r4   rR   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yb   tdt d| j Y n0 |dd}zt	||f}W nr t
y } zZd| d	| d
t d| j }|rddlm} |||t	 }td|| W Y d}~n
d}~0 0 ||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{   rA   METAINFO_FILENAMErd   r   r	   KeyErrorr-   
setdefaultr   
ValueErrorfontTools.ufoLib.errorsr   r>   loggerwarning)	r3   rb   r   ZformatVersionMajorr   r   r@   ZunsupportedMsgr   r$   r$   r%   _readMetaInfo  s>    


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.
		ra   r   N)r   r   r3   rb   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.)rA   GROUPS_FILENAMEr   
startswithr   r   fromkeys)r3   r   r   r   r$   r$   r%   r     s
    
zUFOReader._readGroupsc                 C   sX   |du r| j }| jtjk r0| | | jd }n|  }|rTt|\}}|sTt||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	   )r3   rb   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 )a  
		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side2ra   r   )r{   r   r   r#   r   r   r|   )r3   rb   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.)rA   FONTINFO_FILENAMErd   r   r	   r   r$   r$   r%   	_readInfo  s    zUFOReader._readInfoc              	   C   sP  |du r| j }| |}i }| jtjkr^tD ]}||}|dur,|||< q,t|}t|}n| jtj	krt
t D ]$\}}||}|du rqv|||< qvt|}nN| jjtjjkrt
t D ]$\}}||}|du rq|||< qn
t| j|rt|}t
| D ]<\}}zt||| W n  tyF   td| Y n0 qdS )aR  
		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	   )r3   inforb   ZinfoDictZinfoDataToSetattrvaluedataValidationDictr$   r$   r%   readInfo  s@    









zUFOReader.readInfoc                 C   s   |  ti }|S r   )rA   KERNING_FILENAME)r3   r   r$   r$   r%   r   E  s    zUFOReader._readKerningc           	      C   s   |du r| j }| jtjk r0| | | jd }n|  }|rTt|\}}|sTt|i }|D ]*}|| D ]}|| | }||||f< qhq\|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   ZkerningValidatorr	   )	r3   rb   ZkerningNestedr   r   r   leftrightr   r$   r$   r%   readKerningI  s     
zUFOReader.readKerningc                 C   s:   |du r| j }| ti }|r6t|\}}|s6t||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{   rA   LIB_FILENAMEfontLibValidatorr	   )r3   rb   r   r   r   r$   r$   r%   readLibg  s    zUFOReader.readLibc                 C   s^   z@| j jtddd}| W  d   W S 1 s40    Y  W n t jjyX   Y dS 0 dS )z`
		Read features.fea. Return a string.
		The returned string is empty if the file is missing.
		r   rO   rR   N )r-   r:   FEATURES_FILENAMEreadr0   r1   )r3   r?   r$   r$   r%   readFeaturesy  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_DIRNAMErA   LAYERCONTENTS_FILENAMEZlayerContentsValidatorr-   r	   )r3   rb   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$   )rY   	layerNamedirectoryNamer$   r$   r%   r[         z+UFOReader.getLayerNames.<locals>.<listcomp>)r{   r   )r3   rb   layerContentsZ
layerNamesr$   r$   r%   getLayerNames  s
    
zUFOReader.getLayerNamesc                 C   sB   |du r| j }| |}|D ]\}}|tkr|  S qtddS )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	   )r3   rb   r   r   Z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rN|} qhqN|du r|td| z| j|}	W n, tjj	y   td| d| dY n0 ||	| 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   GlyphSetNra   z&No glyphs directory is mapped to "%s".zNo 'z' directory for layer 'r8   T)ufoFormatVersionvalidateReadvalidateWriteexpectContentsFile)fontTools.ufoLib.glifLibr   r{   r   r   r	   r-   rm   r0   r1   r   )
r3   r   r   r   r   	directoryr   ZstoredLayerNameZstoredLayerDirectory
glyphSubFSr$   r$   r%   r     s8    

zUFOReader.getGlyphSetc           	      C   sl   |du r| j }| j||dd}| }i }| D ]4\}}|D ]&}||v rZ|| | q>|g||< q>q2|S )zT
		Return a dictionary that maps unicode values (ints) to
		lists of glyph names.
		NT)r   r   )r{   r   ZgetUnicodesr   append)	r3   r   rb   ZglyphSetZallUnicodesZcmapr   Zunicodescoder$   r$   r%   getCharacterMapping  s    zUFOReader.getCharacterMappingc                 C   s   z| j t| _W n6 t jjy,   g  Y S  t jjyH   tdY n0 zdd | jj	 D W S  t jj
y|   g  Y S 0 dS )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 )r\   )lstriprX   r$   r$   r%   r[     s   z5UFOReader.getDataDirectoryListing.<locals>.<listcomp>N)r-   rm   DATA_DIRNAME_dataFSr0   r1   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 n6 tjj	yN   g  Y S  tjj
yj   tdY n0 g }|dD ]h}|jrqz|r||j}t|d\}}W d   n1 s0    Y  |r||j qz||j qz|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.r\   )ZfileObj)r   r   r#   r{   r-   rm   IMAGES_DIRNAME	_imagesFSr0   r1   r   r	   rk   rV   rI   rW   pngValidatorr   )r3   rb   imagesFSresultr4   rL   r   r   r$   r$   r%   getImageDirectoryListing	  s*    	,z"UFOReader.getImageDirectoryListingc                 C   sr   t |}z8z
| j}W n ty2   | jt}Y n0 ||}W n, tjjyl   t	d| d| j Y n0 |S )zN
		Return bytes for the file named 'fileName' inside the 'data/' directory.
		zNo data file named 'r   )
r   r   r   r-   rm   r   rG   r0   r1   r	   )r3   r=   Z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|}z8z
| j}W n ty`   | j	
t}Y n0 ||}W n, t	jjy   td| d| j	 Y n0 |rt|d\}}|st||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-   rm   r   rG   r0   r1   r   )r3   r=   rb   r  r   r   r   r$   r$   r%   	readImage;  s(    
zUFOReader.readImagec                 C   s   | j r| j  d S r   )rp   r-   r~   r   r$   r$   r%   r~   X  s    zUFOReader.closec                 C   s   | S r   r$   r   r$   r$   r%   	__enter__\  s    zUFOReader.__enter__c                 C   s   |    d S r   )r~   )r3   exc_type	exc_valueexc_tbr$   r$   r%   __exit___  s    zUFOReader.__exit__)T)N)N)N)N)N)N)N)N)N)N)NNN)NN)N)N)'r   r   r    __doc__r   r   propertyr4   r   r   r   r   Z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      sT   
J



2

)



4




+

"
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dCddZdDdd ZdEd!d"ZdFd#d$ZdGd%d&Zd'd( ZdHd)d*ZdId+d,ZdJd-d.ZdKd/d0Zd1d2 Zd3d4 Zd5d6 ZdLd7d8ZdMd9d:ZdNd;d<Z  fd=d>Z!  Z"S )Or   a  
	Write the various components of the .ufo.

	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.

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

	An UnsupportedUFOFormat exception is raised if the requested UFO formatVersion is
	not supported.
	Ncom.github.fonttools.ufoLibTc              
   C   s  zt |}W n@ tyL } z(ddlm} |d||W Y d }~n
d }~0 0 t|dr`| }t|tr<tj	
|}tj	|}|rt|}	|d urzt|}W n ty   td| Y n0 ||	urtd|	|f n|	}n:|d u rtj}tj	|}
|
rtj	|
std| |tju r|rtj }tjj|dd	}tj|| W d    n1 sp0    Y  d
d |dD }t|dkrtdt| n|j|d tjjd| _nLtj	tj	 |d d }tjj|ddd}|!| |j|tjjd| _ntj"j#|dd| _|| _$|| _%d| _&nt|tj'j(r|}z|)  W n$ tj*j+y   td| Y n0 || _z|,d}W n  tj*j-y   t|}Y n0 |r|tjurd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r~d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: rN   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 existrO   r   c                 S   s"   g | ]}|j r|jd kr|jqS rT   rU   rX   r$   r$   r%   r[     s   z&UFOWriter.__init__.<locals>.<listcomp>r\   r   r_   r]   .ufoTrP   creater`   z?The 'structure' argument is not used when input is an FS objectr   r   Fz-Expected a path string or fs object, found %sra   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   rc   rN   rd   re   osr4   normpathrF   rf   r   r	   r)   dirnameisdirr(   r-   ZtempfsZTempFSrg   rh   copycopy_fsrk   rl   rm   rn   ro   splitextbasenamemakedirri   rj   rq   rD   rp   rr   rs   rt   r0   ru   rv   rw   r   r   UserWarningr   rx   ry   r   r   rz   r   _fileCreator_downConversionKerningDatar{   r   r   r   r   r   r   r   _writeMetaInfo)r3   r4   r   fileCreatorr   rb   r@   r   ZhavePreviousFileZexistingStructuredirNamer   ZorigFSr   rootDirr   r   ZpreviousFormatVersionmetaInfor$   r$   r%   r   y  s    &


.





zUFOWriter.__init__c                 C   s   | j S r   )r  r   r$   r$   r%   _get_fileCreator  s    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|rRtd| | jjtj|dd |j	|rtj
|j|| j| n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ZrecreateN)rd   r   r	   r   r-   rF   makedirsr4   r  r  r  Zcopy_dir	copy_file)r3   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 n\ tjjyb   td| Y n< tjj	y   | jj
tj|dd | j|| Y n0 dS )aA  
		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'Tr$  )r   rD   r-   isfilerG   rH   r0   FileExpectedr	   r1   r%  r4   r  )r3   r4   r   r$   r$   r%   writeBytesToPath0  s    zUFOWriter.writeBytesToPathrB   c              
   C   s   t |}z| jj|||dW S  tjjy } zx|d }|dkrNW Y d}~dS |dksf|dksf|dkr| jjtj|dd	 | jj|||dW  Y d}~S W Y d}~nNd}~0  tjj y } z(t	d
| d| j d| W  Y d}~S d}~0 0 dS )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 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   NrB   axTr$  rS   r   r9   )
r   r-   r:   r0   r1   r%  r4   r  r   r	   )r3   r4   rC   rR   r@   mr$   r$   r%   getFileObjectForPathD  s    
2zUFOWriter.getFileObjectForPathFc                 C   s   t |}z| j| W nP tjjy:   | j| Y n0 tjjyh   |sdtd| d| j Y n0 |rtj	|}|rtj
| j| dS )a5  
		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.
		r8   z' does not exist on N)r   r-   remover0   r,  Z
removetreer1   r	   r4   r  ZtoolsZremove_empty)r3   r4   forceremoveEmptyParentsparentr$   r$   r%   
removePath_  s    	
zUFOWriter.removePathc              
   C   s`   | j }|dur\tj|r\zt|d W n0 tyZ } ztd| W Y d}~n
d}~0 0 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)rz   r  r4   rF   utimeOSErrorr   r   )r3   r4   r@   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)Zcreatorr   r   r   )r   r  r   r   minorrM   r   )r3   r"  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 )a  
		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  )r3   mapsremapsideZ	writeNameZdataNamer$   r$   r%   #setKerningGroupConversionRenameMaps  s    z-UFOWriter.setKerningGroupConversionRenameMapsc                 C   s   |du r| j }|r*t|\}}|s*t|| jtjk r| jdur| jd }i }t| D ]\}}||v rlqZ|||< qZt| D ]"\}}||vrq|| }|||< q|}i }	| D ]\}
}t||	|
< q|	r| 	t
|	 n| jr| jt
ddd 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.
		Nr;  TFr3  r4  )r{   r   r	   r   r   r#   r  r   r   rM   r   rD   r6  )r3   r   rb   r   r   r=  ZremappedGroupsrW   r   Z	groupsNewkeyr   r$   r$   r%   writeGroups  s:    



zUFOWriter.writeGroupsc              	   C   s   |du r| j }i }tt D ]N}t||rzt||}W n tyX   td| Y n0 |du rdq|||< q| jt	j
kr|rt|}nJ| jt	jkrt|}|rt|}n(| jt	jkrt|}|rt|}t|}|r| t| dS )aR  
		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   keysrc   getattrr   r	   r   r   r#   r   r"   &_convertFontInfoDataVersion3ToVersion2validateInfoVersion2Datar!   &_convertFontInfoDataVersion2ToVersion1rM   r   )r3   r   rb   infoDatar   r   r$   r$   r%   	writeInfo  s4    



zUFOWriter.writeInfoc                 C   s  |du r| j }|rd}t|s&t|t| D ]p\}}t|ttfsPt|t|dksdt|t|d tszt|t|d tst|t|t	s2t|q2| j
tjk r| jdur| jd }i }t| D ]0\\}}	}|||}||	|	}	||||	f< q|}i }
| D ]4\}}|||f }||
vr@i |
|< ||
| |< q|
rd| t|
 n| jr|| jtddd	 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   r;  TFr@  )r{   ZisDictEnoughr	   r   r   rd   tuplerl   re   r
   r   r   r#   r  r   rC  rM   r   rD   r6  )r3   r   rb   r   pairr   r=  ZremappedKerningr   r   ZkerningDictr   r   r$   r$   r%   writeKerning  sL    




zUFOWriter.writeKerningc                 C   sV   |du r| j }|r*t|\}}|s*t||r<| t| n| jrR| jtddd 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.
		NTFr@  )r{   r   r	   rM   r   rD   r6  )r3   ZlibDictrb   r   r   r$   r$   r%   writeLibK  s    zUFOWriter.writeLibc                 C   sj   |du r| j }| jtjkr"td|r8t|ts8td|rP| t|	d n| j
rf| jtddd dS )zR
		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.utf8TFr@  )r{   r   r   r!   r	   rd   re   r-  r   encoderD   r6  )r3   featuresrb   r$   r$   r%   writeFeatures`  s    
zUFOWriter.writeFeaturesc                    s   |du r j } jtjk rdS |durPg }|D ]}|du r>t}|| q.|}nt j }|rt	|t	 j krt
d fdd|D } t| dS )zq
		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   )rY   r   r   r$   r%   r[     r   z0UFOWriter.writeLayerContents.<locals>.<listcomp>)r{   r   r   r#   r   r   r   r   rC  setr	   rM   r   )r3   Z
layerOrderrb   ZnewOrderr   r   r$   r   r%   writeLayerContentss  s     zUFOWriter.writeLayerContentsc                 C   sZ   d }t | j D ]2\}}|d u r4|tkr4|} qFq||kr|} qFq|sVtd| |S )Nz>Could not locate a glyph set directory for the layer named %s.)r   r   r   r   r	   )r3   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 rH|r4|durHtd| jj d|du r|r| j D ]\}}|tkr^|}q^|du rt	}n|du r|std| jtjk r| j
||||dS | jjtjjkr| j||||||dS t| jdS )a  
		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   defaultLayerrW  r   )r{   r   r   r#   r	   r   r   r   r   r   _getDefaultGlyphSet_getGlyphSetFormatVersion3r   )	r3   r   rX  rW  r   r   r   rU  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   Tr$  rW  r   r   r   r   )r   r   r-   r  r   r   )r3   r   r   rW  r   r   r   r$   r$   r%   rY    s    zUFOWriter._getDefaultGlyphSetc                 C   s   ddl m} |rR| j D ]6\}}	|	tkr@||krPtd| q||krtdq|| jv rh| j| }	n,|rrt}	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   s   h | ]}|  qS r$   lower)rY   dr$   r$   r%   	<setcomp>  r   z7UFOWriter._getGlyphSetFormatVersion3.<locals>.<setcomp>glyphs.existingprefixTr$  r[  )r   r   r   r   r   r	   valuesr   r-   r  r   )r3   r   r   r   rX  rW  r   r   rU  r   rb  r   r$   r$   r%   rZ    s8    	


z$UFOWriter._getGlyphSetFormatVersion3c                 C   s   | j tjk rdS ||krF| j| tkr.|s.dS | j| tkr|rdS n<|du rRt}|| jv rhtd| |rt| j v rtd| |}|rt}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   s   h | ]}|  qS r$   r\  )rY   rW   r$   r$   r%   r_  B  r   z+UFOWriter.renameGlyphSet.<locals>.<setcomp>r`  ra  Tr  )r   r   r#   r   r   r   r	   rd  rV  r   r-   Zmovedir)r3   r   ZnewLayerNamerX  ZoldDirectoryZnewDirectoryrb  r$   r$   r%   renameGlyphSet  s*    


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)r4  )r   r   r#   rV  r6  r   )r3   r   rT  r$   r$   r%   deleteGlyphSetJ  s
    
zUFOWriter.deleteGlyphSetc                 C   s   |  t dt| | dS )zX
		Write data to fileName in the 'data' directory.
		The data must be a bytes string.
		r\   N)r-  r   r   )r3   r=   r   r$   r$   r%   	writeDataV  s    zUFOWriter.writeDatac                 C   s   |  t dt|  dS )z=
		Remove the file named fileName from the data directory.
		r\   N)r6  r   r   )r3   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|}|rTt|d\}}|sTt|| t	 d| | dS )zU
		Write data to fileName in the images directory.
		The data must be a valid PNG.
		NImages are not allowed in UFO r   r  r\   )
r{   r   r   r#   r	   r   r   r   r-  r   )r3   r=   r   rb   r   r   r$   r$   r%   
writeImagee  s    zUFOWriter.writeImagec                 C   s<   | j tjk r td| j j d| t dt|  dS )zA
		Remove the file named fileName from the
		images directory.
		ri  r   r\   N)r   r   r#   r	   r   r6  r   r   )r3   r=   rb   r$   r$   r%   removeImagew  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.
		Nri  r   r\   )	r{   r   r   r#   r	   r   r   r   r*  )r3   r'  ZsourceFileNameZdestFileNamerb   r(  r)  r$   r$   r%   copyImageFromReader  s    zUFOWriter.copyImageFromReaderc                    s   | j rz| jtju rztjtj| jd d }t	j
j| jddd&}t	j| j	|| W d    n1 sp0    Y  t   d S )Nr   r  TrO   rP   )rD   rq   r   r(   r  r4   r  r  rz   r-   rg   rh   r  r  r  superr~   )r3   r!  ZdestFS	__class__r$   r%   r~     s
    4zUFOWriter.close)Nr  NT)rB   N)FT)N)N)N)N)N)NN)NTNNNF)NF)NTNF)F)N)N)N)#r   r   r    r  r   r#  r  r  r*  r-  r1  r6  ZremoveFileForPathr9  r  r?  rB  rI  rL  rM  rQ  rS  rV  r   rY  rZ  re  rf  rg  rh  rj  rk  rl  r~   __classcell__r$   r$   rn  r%   r   g  s^       
 


7
+
9


      
G  
    
2
+


r   c                 C   sL   t | rtjS tj| r"tjS tj| r<t	d|  nt	d|  dS )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'N)
zipfile
is_zipfiler   r(   r  r4   r  r)   r+  r	   )Zufo_pathr$   r$   r%   rf     s    
rf   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   NZufo)r  r4   splitjoin)r4   dirrW   r$   r$   r%   r     s    "r   c                 C   sZ   t |  }|d}|d}|d}|dur:|||}n|tkrN|||}n||}|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.
	ry   valueValidatorvalueOptionsN)r   r   genericTypeValidatorr   r   r   Z	valueType	validatorrx  isValidValuer$   r$   r%   r     s    



r   c                 C   sL   i }t |  D ]6\}}t||}|s>td| d|dq|||< 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	   rH  ZvalidInfoDatar   r   r|  r$   r$   r%   rF    s    


rF  c                 C   sZ   t |  }|d}|d}|d}|dur:|||}n|tkrN|||}n||}|S )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.
	ry   rw  rx  N)r   r   ry  rz  r$   r$   r%   r     s    



r   c                 C   sL   i }t |  D ]6\}}t||}|s>td| d|dq|||< q|S )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     s    


r      )r   r   r            	      @   )r   r   r   r   r  r  >(   
familyNamedesigner	fontStyleascender	styleName
weightNameotFamilyNamefondIDttVendor	otMacName	widthNameversionMajoritalicAngle	createdByfontName	descender	capHeight
slantAngle	trademarkotStyleNamemenuNamenoticefondName	msCharSetyear	ttVersion
unitsPerEmnotexHeightweightValue
ttUniqueIDdefaultWidthlicensedesignerURLuniqueID
licenseURLfullName	vendorURL	copyrightversionMinor)ry   )ry   rw  ZintegerList)ry   rw  rx  )^r  r  styleMapFamilyNamestyleMapStyleNamer  r  r  r  r  r  r  r  r  r  r  r  ZopenTypeHeadCreatedopenTypeHeadLowestRecPPEMZopenTypeHeadFlagsopenTypeHheaAscenderopenTypeHheaDescenderopenTypeHheaLineGapZopenTypeHheaCaretSlopeRiseZopenTypeHheaCaretSlopeRunopenTypeHheaCaretOffsetopenTypeNameDesigneropenTypeNameDesignerURLopenTypeNameManufactureropenTypeNameManufacturerURLopenTypeNameLicenseopenTypeNameLicenseURLopenTypeNameVersionopenTypeNameUniqueIDopenTypeNameDescriptionopenTypeNamePreferredFamilyName"openTypeNamePreferredSubfamilyNameopenTypeNameCompatibleFullNameZopenTypeNameSampleTextZopenTypeNameWWSFamilyNameZopenTypeNameWWSSubfamilyNameopenTypeOS2WidthClassopenTypeOS2WeightClassZopenTypeOS2SelectionopenTypeOS2VendorIDopenTypeOS2PanoseZopenTypeOS2FamilyClassZopenTypeOS2UnicodeRangesZopenTypeOS2CodePageRangesopenTypeOS2TypoAscenderopenTypeOS2TypoDescenderopenTypeOS2TypoLineGapopenTypeOS2WinAscentopenTypeOS2WinDescentZopenTypeOS2TypeopenTypeOS2SubscriptXSizeopenTypeOS2SubscriptYSizeopenTypeOS2SubscriptXOffsetopenTypeOS2SubscriptYOffsetopenTypeOS2SuperscriptXSizeopenTypeOS2SuperscriptYSizeopenTypeOS2SuperscriptXOffsetopenTypeOS2SuperscriptYOffsetopenTypeOS2StrikeoutSizeopenTypeOS2StrikeoutPositionopenTypeVheaVertTypoAscenderopenTypeVheaVertTypoDescenderopenTypeVheaVertTypoLineGapZopenTypeVheaCaretSlopeRiseZopenTypeVheaCaretSlopeRunopenTypeVheaCaretOffsetpostscriptFontNamepostscriptFullNamepostscriptSlantAnglepostscriptUniqueIDZpostscriptUnderlineThicknessZpostscriptUnderlinePositionZpostscriptIsFixedPitchZpostscriptBlueValuesZpostscriptOtherBluesZpostscriptFamilyBluesZpostscriptFamilyOtherBluesZpostscriptStemSnapHZpostscriptStemSnapVZpostscriptBlueFuzzZpostscriptBlueShiftZpostscriptBlueScaleZpostscriptForceBoldpostscriptDefaultWidthXZpostscriptNominalWidthXpostscriptWeightNameZpostscriptDefaultCharacterpostscriptWindowsCharacterSetmacintoshFONDFamilyIDmacintoshFONDNameZdictList))r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ZopenTypeGaspRangeRecordsZopenTypeNameRecordsr  r  r  r  ZwoffMajorVersionZwoffMinorVersionZwoffMetadataUniqueIDZwoffMetadataVendorZwoffMetadataCreditsZwoffMetadataDescriptionZwoffMetadataLicenseZwoffMetadataCopyrightZwoffMetadataTrademarkZwoffMetadataLicenseeZwoffMetadataExtensionsZ
guidelinesrw  c                 C   s&   i }t |  D ]\}}|||< q|S r   )r   r   )r^  ZflippedrA  r   r$   r$   r%   	_flipDict  s    
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  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  Zregularitalicboldzbold italic)r  r       !   r   r   r   r        r  r  r  )	zUltra-condensedzExtra-condensedZ	CondensedzSemi-condensedzMedium (normal)zSemi-expandedZExpandedzExtra-expandedzUltra-expandedZNormalZAllZmediumZMedium
                              )r   r   r   M   r                                               c                 C   s   t |trt||krt|}|dur| dkr\t|}|du rVtd|d|  d|}nj| dkrt|}|du rtd|d|  d|}n4| dkrt|}|du rt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  )	rd   floatint_fontStyle1To2r   r	   _widthName1To2_msCharSet1To2fontInfoAttributesVersion1To2r   r   vr$   r$   r%   r   `  s*    



r   c                 C   sV   |durB| dkrt |}n&| dkr0t|}n| dkrBt|}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  r  )_fontStyle2To1r   _widthName2To1_msCharSet2To1fontInfoAttributesVersion2To1r   r   r$   r$   r%   r   }  s    
r   c                 C   sn   i }t |  D ]X\}}|dkr*|dkr*qt||\}}|tvrBq|d u r`td|d| d|||< q|S )Nr  rs  r  r  r   )r   r   r   r   r	   r   	convertedr   r   ZnewAttrZnewValuer$   r$   r%   r     s    
r   c                 C   s\   i }t |  D ]F\}}t||\}}|tvr0q|d u rNtd|d| d|||< q|S )Nr  r  r   )r   r   r   r   r	   r  r$   r$   r%   rG    s    
rG  >   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  c              	   C   s   | t v r8zt|}W n" ttfy6   td|  Y n0 | tv rvztt|}W q ttfyr   td|  Y q0 n\| tv rzt	t|}W n" ttfy   td|  Y n0 |t|krt|}||kr|}| |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   rx   r	   _ufo2To3NonNegativeIntr  abs_ufo2To3NonNegativeIntOrFloatr  r  r$   r$   r%   6convertFontInfoValueForAttributeFromVersion2ToVersion3  s(    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r0q|||< q|S r   )r   r   r  r   r  r$   r$   r%   rE    s    
rE  c                 C   s4   i }t |  D ]\}}t||\}}|||< q|S r   )r   r   r  )r   r  r   r   r$   r$   r%   r    	  s
    
r   __main__)r  r  r   r   loggingrq  enumcollectionsr   r-   Zfs.baseZfs.subfsZ	fs.errorsZfs.copyZfs.osfsZfs.zipfsZ	fs.tempfsZfs.toolsZfontTools.miscr   ZfontTools.ufoLib.validatorsZfontTools.ufoLib.filenamesr   ZfontTools.ufoLib.convertersr   r   r	   ZfontTools.ufoLib.utilsr
   r   __all____version__	getLoggerr   r   r   r   r   r   r   r   r   r   r   r   ZLAYERINFO_FILENAMEr   rJ  Enumr   __str__r   r*   r   r   r   rf   r   r   rF  r   r   r   rangeZ fontInfoOpenTypeHeadFlagsOptionsZ#fontInfoOpenTypeOS2SelectionOptionsZ'fontInfoOpenTypeOS2UnicodeRangesOptionsZ(fontInfoOpenTypeOS2CodePageRangesOptionsZfontInfoOpenTypeOS2TypeOptionsr   r   re   Z"fontInfoStyleMapStyleNameValidatorr  r  Z$fontInfoOpenTypeHeadCreatedValidatorZgenericIntListValidatorZ&fontInfoOpenTypeOS2WidthClassValidatorZ'fontInfoOpenTypeOS2WeightClassValidatorZ*fontInfoVersion2OpenTypeOS2PanoseValidatorZ'fontInfoOpenTypeOS2FamilyClassValidatorboolZ fontInfoPostscriptBluesValidatorZ%fontInfoPostscriptOtherBluesValidatorZ fontInfoPostscriptStemsValidatorZ.fontInfoPostscriptWindowsCharacterSetValidatorr   rR  rC  r   r   updateZgenericNonNegativeIntValidatorZ!genericNonNegativeNumberValidatorZ*fontInfoVersion3OpenTypeOS2PanoseValidatorZ)fontInfoOpenTypeGaspRangeRecordsValidatorZ$fontInfoOpenTypeNameRecordsValidatorZ%fontInfoWOFFMetadataUniqueIDValidatorZ#fontInfoWOFFMetadataVendorValidatorZ$fontInfoWOFFMetadataCreditsValidatorZ(fontInfoWOFFMetadataDescriptionValidatorZ$fontInfoWOFFMetadataLicenseValidatorZ&fontInfoWOFFMetadataCopyrightValidatorZ&fontInfoWOFFMetadataTrademarkValidatorZ%fontInfoWOFFMetadataLicenseeValidatorZ'fontInfoWOFFMetadataExtensionsValidatorZguidelinesValidatorr   r   r   ZdataDictry  r  r  r  r   r  r  r	  r  r
  r  r   r   r   rG  r  r  r  r  r  rE  r   doctesttestmodr$   r$   r$   r%   <module>   s\   

U     "      <,












`


















+

	
