a
    w=ic                     @  s  d Z ddlmZ ddl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Z	ddlZ	ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZmZm Z  ddlm!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' g dZ(e)e*Z+dZ,dZ-G dd de.e'ej/Z0e'j1e0_1G dd dZ2G dd de#Z3dd Z4d~ddZ5dddZ6ddd Z7d!d" Z8d#d$ Z9d%d& Z:d'd( Z;d)d* Z<d+d, Z=d-d. Z>d/d0 Z?e@eAed1e@e@ed1d2ZBd3d4 ZCd5d6 ZDd7d8 ZEd9d: ZFdde0G dfd;d<ZHdd=d>ZIdd?d@ZJe0jKeIe0jLeJiZMdAdB ZNdCdD ZOdEdF ZPdGdH ZQdIdJ ZRdKhZSh dLZTeTdKhB ZUh dMZVeVdKhB ZWdNdOhZXh dPZYdQdR ZZdSdT Z[dUdV Z\dWdX Z]dYdZ Z^d[d\ Z_d]d^ Z`d_d` Zadadb ZbddddeZcdfdg Zddhdi ZeG djdk dkefZgG dldm dmZhdndo ZiG dpdq dqehZjdrds ZkG dtdu duehZldvdw ZmG dxdy dyehZng dzZoG d{d| d|eZpe*d}kr|ddlqZqeqr  dS )a|  
glifLib.py -- Generic module for reading and writing the .glif format.

More info about the .glif format (GLyphInterchangeFormat) can be found here:

	http://unifiedfontobject.org

The main class in this module is GlyphSet. It manages a set of .glif files
in a folder. It offers two ways to read glyph data, and one way to write
glyph data. See the class doc string for details.
    )annotationsN)warn)OrderedDict)tobytes)plistlib)AbstractPointPenPointToSegmentPen)GlifLibError)userNameToFileName)genericTypeValidatorcolorValidatorguidelinesValidatoranchorsValidatoridentifierValidatorimageValidatorglyphLibValidator)etree)
_UFOBaseIOUFOFormatVersion)numberTypes_VersionTupleEnumMixin)GlyphSetr	   readGlyphFromStringwriteGlyphToStringglyphNameToFileNamezcontents.plistzlayerinfo.plistc                      s<   e Zd ZdZdZed fdd	Zed	 fdd	Z  ZS )
GLIFFormatVersion)   r   )   r   Nc                   s    |d urt | |S t  S N)maxsupported_versionssuperdefault)clsufoFormatVersion	__class__ i/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/fontTools/ufoLib/glifLib.pyr"   A   s    zGLIFFormatVersion.defaultc                   s8   |d u rt   S | jh}|tjkr0|| j t|S r   )r!   r    
FORMAT_1_0r   Z
FORMAT_3_0add
FORMAT_2_0	frozenset)r#   r$   versionsr%   r'   r(   r    G   s    

z$GLIFFormatVersion.supported_versions)N)N)	__name__
__module____qualname__r)   r+   classmethodr"   r    __classcell__r'   r'   r%   r(   r   =   s   r   c                   @  s*   e Zd ZdZdd Zd
ddZdd Zd	S )Glyphzy
	Minimal glyph object. It has no glyph attributes until either
	the draw() or the drawPoints() method has been called.
	c                 C  s   || _ || _d S r   )	glyphNameglyphSet)selfr4   r5   r'   r'   r(   __init__a   s    zGlyph.__init__Fc                 C  s   t ||d}| | dS )z-
		Draw this glyph onto a *FontTools* Pen.
		)outputImpliedClosingLineN)r   
drawPoints)r6   penr8   pointPenr'   r'   r(   drawe   s    z
Glyph.drawc                 C  s   | j | j| | dS )z&
		Draw this glyph onto a PointPen.
		N)r5   	readGlyphr4   )r6   r;   r'   r'   r(   r9   l   s    zGlyph.drawPointsN)F)r.   r/   r0   __doc__r7   r<   r9   r'   r'   r'   r(   r3   Z   s   
r3   c                   @  s   e Zd ZdZeZd/ddZd0ddZd	d
 Zdd Z	d1ddZ
d2ddZdd Zdd Zd3ddZd4ddZdd Zdd Zdd ZeZdd  Zd!d" Zd5d#d$Zd6d%d&Zd7d'd(Zd)d* Zd+d, Zd-d. ZdS )8r   a1  
	GlyphSet manages a set of .glif files inside one directory.

	GlyphSet's constructor takes a path to an existing directory as it's
	first argument. Reading glyph data can either be done through the
	readGlyph() method, or by using GlyphSet's dictionary interface, where
	the keys are glyph names and the values are (very) simple glyph objects.

	To write a glyph to the glyph set, you use the writeGlyph() method.
	The simple glyph objects returned through the dict interface do not
	support writing, they are just a convenient way to get at the glyph data.
	NTFc           
   
   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rztj	
|}	W n" tjjy   td| Y n0 d| _n\t|tjjr|}	z|	  W n" tjjy   td|	 Y n0 d	| _ntd
t|j z|	d}W n  tjjy0   t|	}Y n0 tj|d | _|	| _|	t| _|rr| jsrtt d|j| _|| _ |du rt!}|| _!|| _"|| _#d| _$d| _%| &  dS )aE  
		'path' should be a path (string) to an existing local directory, or
		an instance of fs.base.FS class.

		The optional 'glyphNameToFileNameFunc' argument must be a callback
		function that takes two arguments: a glyph name and a list of all
		existing filenames (if any exist). It should return a file name
		(including the .glif extension). The glyphNameToFileName function
		is called whenever a file name is created for a given glyph name.

		``validateRead`` will validate read operations. Its default is ``True``.
		``validateWrite`` will validate write operations. Its default is ``True``.
		``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 create a fresh	glyph set.
		r   )UnsupportedUFOFormatzUnsupported UFO format: N
__fspath__zNo glyphs directory '%s'Tzthe filesystem '%s' is closedFz-Expected a path string or fs object, found %s/z is missing.)'r   
ValueErrorfontTools.ufoLib.errorsr?   hasattrr@   
isinstancestrfsZosfsZOSFSerrorsZCreateFailedr	   _shouldClosebaseZFScheckZFilesystemClosed	TypeErrortyper.   Z
getsyspathZ	NoSysPathpathpartsdirNameexistsCONTENTS_FILENAME_havePreviousFilemajorr$   ufoFormatVersionTupler   _validateRead_validateWrite_existingFileNames_reverseContentsrebuildContents)
r6   rO   ZglyphNameToFileNameFuncr$   validateReadvalidateWriteZexpectContentsFileer?   
filesystemr'   r'   r(   r7      s`    


zGlyphSet.__init__c                 C  s   |du r| j }| ti }|rd}t|ts2d}nL| D ]B\}}t|tsPd}t|ts`d}q:| j|s:t	dt|f q:|rt	dt || _
d| _d| _dS )z
		Rebuild the contents dict by loading contents.plist.

		``validateRead`` will validate the data, by default it is set to the
		class's ``validateRead`` value, can be overridden.
		NFTz,%s references a file that does not exist: %sz%s is not properly formatted)rW   	_getPlistrS   rF   dictitemsrG   rH   rR   r	   contentsrY   rZ   )r6   r\   rc   ZinvalidFormatnamefileNamer'   r'   r(   r[      s.    


zGlyphSet.rebuildContentsc                 C  s:   | j du r4i }| j D ]\}}||| < q|| _ | j S )a  
		Return a reversed dict of self.contents, mapping file names to
		glyph names. This is primarily an aid for custom glyph name to file
		name schemes that want to make sure they don't generate duplicate
		file names. The file names are converted to lowercase so we can
		reliably check for duplicates that only differ in case, which is
		important for case-insensitive file systems.
		N)rZ   rc   rb   lower)r6   dkvr'   r'   r(   getReverseContents   s    	
zGlyphSet.getReverseContentsc                 C  s   |  t| j dS )zd
		Write the contents.plist file out to disk. Call this method when
		you're done writing glyphs.
		N)_writePlistrS   rc   r6   r'   r'   r(   writeContents
  s    zGlyphSet.writeContentsc              	   C  s~   |du r| j }| ti }|r8t|ts0tdt|}| D ]8\}}zt||| W q@ t	yv   td| Y q@0 q@dS )z
		``validateRead`` will validate the data, by default it is set to the
		class's ``validateRead`` value, can be overridden.
		Nz*layerinfo.plist is not properly formatted.zSThe supplied layer info object does not support setting a necessary attribute (%s).)
rW   r`   LAYERINFO_FILENAMErF   ra   r	   validateLayerInfoVersion3Datarb   setattrAttributeError)r6   infor\   ZinfoDictattrvaluer'   r'   r(   readLayerInfo  s    
zGlyphSet.readLayerInfoc              	   C  s   |du r| j }| jjdk r*td| jj i }t D ]Z}t||r6zt||}W n typ   td| Y n0 |du s6|dkr|sq6|||< q6|r|rt	|}| 
t| n| jr| jtr| jt dS )z
		``validateWrite`` will validate the data, by default it is set to the
		class's ``validateWrite`` value, can be overridden.
		N   z)layerinfo.plist is not allowed in UFO %d.zMThe supplied info object does not support getting a necessary attribute (%s).lib)rX   rV   rU   r	   layerInfoVersion3ValueDatakeysrE   getattrrq   ro   rk   rn   rT   rH   rR   remove)r6   rr   r]   infoDatars   rt   r'   r'   r(   writeLayerInfo&  s,    


zGlyphSet.writeLayerInfoc                 C  sH   | j | }z| j|W S  tjjyB   td||| jf Y n0 dS )a  
		Get the raw GLIF text for a given glyph name. This only works
		for GLIF files that are already on disk.

		This method is useful in situations when the raw XML needs to be
		read from a glyph set for a particular glyph before fully parsing
		it into an object structure via the readGlyph method.

		Raises KeyError if 'glyphName' is not in contents.plist, or
		GlifLibError if the file associated with can't be found.
		zOThe file '%s' associated with glyph '%s' in contents.plist does not exist on %sN)rc   rH   	readbytesrI   ZResourceNotFoundr	   r6   r4   re   r'   r'   r(   getGLIFF  s    

zGlyphSet.getGLIFc                 C  s   | j | }| |S )aK  
		Returns the modification time for the GLIF file with 'glyphName', as
		a floating point number giving the number of seconds since the epoch.
		Return None if the associated file does not exist or the underlying
		filesystem does not support getting modified times.
		Raises KeyError if the glyphName is not in contents.plist.
		)rc   ZgetFileModificationTimer   r'   r'   r(   getGLIFModificationTime[  s    
z GlyphSet.getGLIFModificationTimec                 C  sB   |du r| j }| |}t|}t| j}t|||||d dS )aP  
		Read a .glif file for 'glyphName' from the glyph set. The
		'glyphObject' argument can be any kind of object (even None);
		the readGlyph() method will attempt to set the following
		attributes on it:

		width
			the advance width of the glyph
		height
			the advance height of the glyph
		unicodes
			a list of unicode values for this glyph
		note
			a string
		lib
			a dictionary containing custom data
		image
			a dictionary containing image data
		guidelines
			a list of guideline data dictionaries
		anchors
			a list of anchor data dictionaries

		All attributes are optional, in two ways:

		1) An attribute *won't* be set if the .glif file doesn't
		   contain data for it. 'glyphObject' will have to deal
		   with default values itself.
		2) If setting the attribute fails with an AttributeError
		   (for example if the 'glyphObject' attribute is read-
		   only), readGlyph() will not propagate that exception,
		   but ignore that attribute.

		To retrieve outline information, you need to pass an object
		conforming to the PointPen protocol as the 'pointPen' argument.
		This argument may be None if you don't need the outline data.

		readGlyph() will raise KeyError if the glyph is not present in
		the glyph set.

		``validate`` will validate the data, by default it is set to the
		class's ``validateRead`` value, can be overridden.
		NformatVersionsvalidate)rW   r   _glifTreeFromStringr   r    rV   _readGlyphFromTree)r6   r4   glyphObjectr;   r   texttreer   r'   r'   r(   r=   h  s    ,
zGlyphSet.readGlyphc           
   
   C  sn  |du rt | j}nNzt |}W n@ tyb } z(ddlm} |d||W Y d}~n
d}~0 0 |t | jvrddlm} |d|d| jd|du r| j}| j	|}|du r| j
du rdd	 | j D | _
| || j
}|| j|< | j
|  | jdur|| j| < t|||||d
}	| jr\| j|r\|	| j|kr\dS | j||	 dS )a:  
		Write a .glif file for 'glyphName' to the glyph set. The
		'glyphObject' argument can be any kind of object (even None);
		the writeGlyph() method will attempt to get the following
		attributes from it:

		width
			the advance width of the glyph
		height
			the advance height of the glyph
		unicodes
			a list of unicode values for this glyph
		note
			a string
		lib
			a dictionary containing custom data
		image
			a dictionary containing image data
		guidelines
			a list of guideline data dictionaries
		anchors
			a list of anchor data dictionaries

		All attributes are optional: if 'glyphObject' doesn't
		have the attribute, it will simply be skipped.

		To write outline data to the .glif file, writeGlyph() needs
		a function (any callable object actually) that will take one
		argument: an object that conforms to the PointPen protocol.
		The function will be called by writeGlyph(); it has to call the
		proper PointPen methods to transfer the outline to the .glif file.

		The GLIF format version will be chosen based on the ufoFormatVersion
		passed during the creation of this object. If a particular format
		version is desired, it can be passed with the formatVersion argument.
		The formatVersion argument accepts either a tuple of integers for
		(major, minor), or a single integer for the major digit only (with
		minor digit implied as 0).

		An UnsupportedGLIFFormat exception is raised if the requested GLIF
		formatVersion is not supported.

		``validate`` will validate the data, by default it is set to the
		class's ``validateWrite`` value, can be overridden.
		Nr   UnsupportedGLIFFormatz!Unsupported GLIF format version: z!Unsupported GLIF format version (z) for UFO format version .c                 S  s   h | ]}|  qS r'   )rf   ).0re   r'   r'   r(   	<setcomp>  s   z&GlyphSet.writeGlyph.<locals>.<setcomp>)formatVersionr   )r   r"   rV   rC   rD   r   r    rX   rc   getrY   valuesr   r*   rf   rZ   _writeGlyphToBytesrT   rH   rR   r~   Z
writebytes)
r6   r4   r   drawPointsFuncr   r   r^   r   re   datar'   r'   r(   
writeGlyph  s`    .



zGlyphSet.writeGlyphc                 C  sR   | j | }| j| | jdur0| j|  | jdurF| j| = | j |= dS )zPermanently delete the glyph from the glyph set on disk. Will
		raise KeyError if the glyph is not present in the glyph set.
		N)rc   rH   r{   rY   rf   rZ   r   r'   r'   r(   deleteGlyph  s    


zGlyphSet.deleteGlyphc                 C  s   t | j S r   )listrc   ry   rl   r'   r'   r(   ry     s    zGlyphSet.keysc                 C  s
   || j v S r   )rc   r6   r4   r'   r'   r(   has_key
  s    zGlyphSet.has_keyc                 C  s
   t | jS r   )lenrc   rl   r'   r'   r(   __len__  s    zGlyphSet.__len__c                 C  s   || j vrt|| || S r   )rc   KeyError
glyphClassr   r'   r'   r(   __getitem__  s    
zGlyphSet.__getitem__c                 C  s:   i }|du r| j  }|D ]}| |}t|||< q|S )a%  
		Return a dictionary that maps glyph names to lists containing
		the unicode value[s] for that glyph, if any. This parses the .glif
		files partially, so it is a lot faster than parsing all files completely.
		By default this checks all glyphs, but a subset can be passed with glyphNames.
		N)rc   ry   r   _fetchUnicodes)r6   
glyphNamesunicodesr4   r   r'   r'   r(   getUnicodes  s    

zGlyphSet.getUnicodesc                 C  s:   i }|du r| j  }|D ]}| |}t|||< q|S )a(  
		Return a dictionary that maps glyph names to lists containing the
		base glyph name of components in the glyph. This parses the .glif
		files partially, so it is a lot faster than parsing all files completely.
		By default this checks all glyphs, but a subset can be passed with glyphNames.
		N)rc   ry   r   _fetchComponentBases)r6   r   
componentsr4   r   r'   r'   r(   getComponentReferences(  s    

zGlyphSet.getComponentReferencesc                 C  s:   i }|du r| j  }|D ]}| |}t|||< q|S )a  
		Return a dictionary that maps glyph names to the file name of the image
		referenced by the glyph. This parses the .glif files partially, so it is a
		lot faster than parsing all files completely.
		By default this checks all glyphs, but a subset can be passed with glyphNames.
		N)rc   ry   r   _fetchImageFileName)r6   r   Zimagesr4   r   r'   r'   r(   getImageReferences7  s    

zGlyphSet.getImageReferencesc                 C  s   | j r| j  d S r   )rJ   rH   closerl   r'   r'   r(   r   F  s    zGlyphSet.closec                 C  s   | S r   r'   rl   r'   r'   r(   	__enter__J  s    zGlyphSet.__enter__c                 C  s   |    d S r   )r   )r6   exc_type	exc_valueexc_tbr'   r'   r(   __exit__M  s    zGlyphSet.__exit__)NNTTF)N)N)N)NNN)NNNN)N)N)N)r.   r/   r0   r>   r3   r   r7   r[   rj   rm   ru   r}   r   r   r=   r   r   ry   r   __contains__r   r   r   r   r   r   r   r   r'   r'   r'   r(   r   w   s:        
R
 	

 
3
^


r   c                 C  s   |du rt  }t| |ddS )z
	Wrapper around the userNameToFileName function in filenames.py

	Note that existingFileNames should be a set for large glyphsets
	or performance will suffer.
	Nz.glif)existingsuffix)setr
   )r4   ZexistingFileNamesr'   r'   r(   r   U  s    r   Tc           
   	   C  s   t | }|du rt }n^t t  }}|D ]8}zt|}	W n tyX   || Y q,0 ||	 q,|sxtd|t|||||d dS )a|  
	Read .glif data from a string into a glyph object.

	The 'glyphObject' argument can be any kind of object (even None);
	the readGlyphFromString() method will attempt to set the following
	attributes on it:

	width
		the advance width of the glyph
	height
		the advance height of the glyph
	unicodes
		a list of unicode values for this glyph
	note
		a string
	lib
		a dictionary containing custom data
	image
		a dictionary containing image data
	guidelines
		a list of guideline data dictionaries
	anchors
		a list of anchor data dictionaries

	All attributes are optional, in two ways:

	1) An attribute *won't* be set if the .glif file doesn't
	   contain data for it. 'glyphObject' will have to deal
	   with default values itself.
	2) If setting the attribute fails with an AttributeError
	   (for example if the 'glyphObject' attribute is read-
	   only), readGlyphFromString() will not propagate that
	   exception, but ignore that attribute.

	To retrieve outline information, you need to pass an object
	conforming to the PointPen protocol as the 'pointPen' argument.
	This argument may be None if you don't need the outline data.

	The formatVersions optional argument define the GLIF format versions
	that are allowed to be read.
	The type is Optional[Iterable[Tuple[int, int], int]]. It can contain
	either integers (for the major versions to be allowed, with minor
	digits defaulting to 0), or tuples of integers to specify both
	(major, minor) versions.
	By default when formatVersions is None all the GLIF format versions
	currently defined are allowed to be read.

	``validate`` will validate the read data. It is set to ``True`` by default.
	Nz9None of the requested GLIF formatVersions are supported: r   )r   r   r    r   rC   r*   r   )
aStringr   r;   r   r   r   ZvalidFormatVersionsZinvalidFormatVersionsri   r   r'   r'   r(   r   d  s&    8

r   c                 C  s  zt |}W n& ty2   ddlm} |dY n0 |rJt| tsJtd|rbt| dkrbtdtd| fdt	|j
fg}|jdkrt	|j|d< td	|}t }	t||| t|d
drt||| t|ddrt||| |j
dkrt|ddrt||| |j
dkr0t|ddr0t|||	| t|dd}
|j
dkr\|
r\t|||	| |durt|d}t||	|d}|| |j
dkr|
rt||
| t|sd|_t|ddrt||| tj|dddd}|S )z>Return .glif data for a glyph as a UTF-8 encoded bytes string.r   r   z2Unsupported GLIF format version: {formatVersion!r}z)The glyph name is not properly formatted.zThe glyph name is empty.rd   formatformatMinorglyphr   Nnoter   image
guidelinesanchorsoutline)identifiersr   r   
  rw   zUTF-8T)encodingZxml_declarationZpretty_print)r   rC   rD   r   rF   rG   r	   r   r   reprrU   minorr   ZElementr   _writeAdvancerz   _writeUnicodes
_writeNote_writeImage_writeGuidelines_writeAnchors
SubElementGLIFPointPen_writeAnchorsFormat1r   	_writeLibZtostring)r4   r   r   writerr   r   r   Z
glyphAttrsrootr   r   r   r:   r   r'   r'   r(   r     sP    	


r   c                 C  s   t | ||||d}|dS )a-  
	Return .glif data for a glyph as a string. The XML declaration's
	encoding is always set to "UTF-8".
	The 'glyphObject' argument can be any kind of object (even None);
	the writeGlyphToString() method will attempt to get the following
	attributes from it:

	width
		the advance width of the glyph
	height
		the advance height of the glyph
	unicodes
		a list of unicode values for this glyph
	note
		a string
	lib
		a dictionary containing custom data
	image
		a dictionary containing image data
	guidelines
		a list of guideline data dictionaries
	anchors
		a list of anchor data dictionaries

	All attributes are optional: if 'glyphObject' doesn't
	have the attribute, it will simply be skipped.

	To write outline data to the .glif file, writeGlyphToString() needs
	a function (any callable object actually) that will take one
	argument: an object that conforms to the PointPen protocol.
	The function will be called by writeGlyphToString(); it has to call the
	proper PointPen methods to transfer the outline to the .glif file.

	The GLIF format version can be specified with the formatVersion argument.
	This accepts either a tuple of integers for (major, minor), or a single
	integer for the major digit only (with minor digit implied as 0).
	By default when formatVesion is None the latest GLIF format version will
	be used; currently it's 2.0, which is equivalent to formatVersion=(2, 0).

	An UnsupportedGLIFFormat exception is raised if the requested UFO
	formatVersion is not supported.

	``validate`` will validate the written data. It is set to ``True`` by default.
	)r   r   r   r   utf-8)r   decode)r4   r   r   r   r   r   r'   r'   r(   r     s    3r   c              	   C  s   t | dd }|d ur6|r*t|ts*td|dkr6d }t | dd }|d url|r`t|ts`td|dkrld }|d ur|d urt|dtdt|fdt|fg nB|d urt|dtt|d n |d urt|dtt|d d S )	Nwidthz$width attribute must be int or floatr   heightz%height attribute must be int or floatadvance)r   )r   )	rz   rF   r   r	   r   r   r   r   ra   )r   elementr   r   r   r'   r'   r(   r   0  s$    (r   c                 C  sz   t | dd }|r t|tr |g}t }|D ]J}|rDt|tsDtd||v rNq*|| d| }t|dt|d q*d S )Nr   zunicode values must be intz%04Xunicode)hex)	rz   rF   intr   r	   r*   r   r   ra   )r   r   r   r   seencodeZhexCoder'   r'   r(   r   D  s    
r   c                 C  sH   t | dd }|r"t|ts"td| }d| d }|t|d_d S )Nr   znote attribute must be str
)rz   rF   rG   r	   stripr   r   r   )r   r   r   r   r'   r'   r(   r   R  s    r   c           	      C  s   t | dd }|r t|s tdtd|d fg}tD ](\}}|||}||kr6t|||< q6|d}|d urz||d< t|d| d S )Nr   zMimage attribute must be a dict or dict-like object with the proper structure.re   color)	rz   r   r	   r   _transformationInfor   r   r   r   )	r   r   r   r   attrsrs   r"   rt   r   r'   r'   r(   r   Z  s    
r   c                 C  s  t | dg }|r t|s td|D ]}t }|d}|d urLt||d< |d}|d urjt||d< |d}	|	d urt|	|d< |d}
|
d ur|
|d< |d}|d ur||d< |d}|d ur|r||v rtd	| ||d< || t|d
| q$d S )Nr   z8guidelines attribute does not have the proper structure.xyanglerd   r   
identifier"identifier used more than once: %s	guideline)	rz   r   r	   r   r   r   r*   r   r   )r   r   r   r   r   r   r   r   r   r   rd   r   r   r'   r'   r(   r   h  s6    






r   c                 C  s   |rt |std|D ]n}i }|d }t||d< |d }t||d< |d}|d urb||d< |   | j||fd|d |   qd S )N5anchors attribute does not have the proper structure.r   r   rd   move)segmentTyperd   )r   r	   r   r   	beginPathaddPointendPath)r:   r   r   anchorr   r   r   rd   r'   r'   r(   r     s    
r   c                 C  s   t | dg }|r t|s td|D ]}t }|d }t||d< |d }t||d< |d}	|	d urp|	|d< |d}
|
d ur|
|d< |d}|d ur|r||v rtd| ||d< || t|d	| q$d S )
Nr   r   r   r   rd   r   r   r   r   )	rz   r   r	   r   r   r   r*   r   r   )r   r   r   r   r   r   r   r   r   rd   r   r   r'   r'   r(   r     s,    



r   c                 C  sf   t | dd }|sd S |r0t|\}}|s0t|t|tsBt|}tj|dd}t|d	| d S )Nrw   r   )indent_level)
rz   r   r	   rF   ra   r   Ztotreer   r   append)r   r   r   rw   validmessager^   r'   r'   r(   r     s    
r   )rN   valueValidator)r   rw   c                 C  sf   | t vrdS t |  }|d}|d}|d}|durF|||}n|tkrZ|||}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.
	FrN   r   valueOptionsN)rx   r   r   )rs   rt   ZdataValidationDictZ	valueType	validatorr   isValidValuer'   r'   r(   *validateLayerInfoVersion3ValueForAttribute  s    



r   c                 C  sN   |   D ]@\}}|tvr$td| t||}|std| d|dq| S )a  
	This performs very basic validation of the value for infoData
	following the UFO 3 layerinfo.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.
	zUnknown attribute %s.zInvalid value for attribute z (z).)rb   rx   r	   r   )r|   rs   rt   r   r'   r'   r(   ro     s    

ro   c                 C  sb   t jrt j| t jddd}n
t | }| }|jdkrBtd|jr^|j dkr^td|S )NTZremove_commentsparserr   #The GLIF is not properly formatted. Invalid GLIF structure.)	r   
_have_lxmlparse	XMLParserZgetroottagr	   r   r   )ZaFiler   r   r'   r'   r(   _glifTreeFromFile  s    

r   c                 C  sf   t | dd}tjr*tj|tjddd}n
t|}|jdkrFtd|jrb|j dkrbtd	|S )
Nr   )r   Tr   r   r   r   r   r   )	r   r   r   Z
fromstringr   r   r	   r   r   )r   r   r   r'   r'   r(   r     s    

r   c              
   C  s   |  d}|r|d u rtd|  dd}ztt|t|f}W n` ty } zHd||f }	|rxddlm}
 |
|	|t }t	d|	| W Y d }~n
d }~0 0 |r||vrtd|zt
| }W n ty   t|Y n0 || ||||jd	 d S )
Nr   z#Unspecified format version in GLIF.r   r   zUnsupported GLIF format: %s.%sr   z_%s. Assuming the latest supported version (%s). Some data may be skipped or parsed incorrectly.zForbidden GLIF format version: )r   r   r;   r   r   )r   r	   r   r   rC   rD   r   r"   loggerwarning_READ_GLYPH_FROM_TREE_FUNCSr   NotImplementedErrorr   )r   r   r;   r   r   ZformatVersionMajorZformatVersionMinorr   r^   msgr   ZreadGlyphFromTreer'   r'   r(   r     s<    

r   c              	   K  s  t || | g }d } } }}	| D ]V}
|
jdkr|rn|rDtd|
jrRtd|
jrn|
j dkrntdd}t|||
| q$|d u rq$q$|
jdkr|r|rtd	d}t||
 q$|
jd
krz*|
d}t	|d}||vr|
| W n ty
   tdY n0 q$|
jdkr>|r.|	r.tdd}	t||
 q$|
jdkrp|r^|r^tdd}t||
| q$td|
 q$|rt|d| d S )NFr   *The outline element occurs more than once.0The outline element contains unknown attributes.r   Invalid outline structure.Tr   *The advance element occurs more than once.r   r      3Illegal value for hex attribute of unicode element.r   'The note element occurs more than once.rw   &The lib element occurs more than once.Unknown element in GLIF: %sr   )	_readNamer   r	   attribr   r   buildOutlineFormat1_readAdvancer   r   r   rC   	_readNote_readLib_relaxedSetattr)r   r   r;   r   kwargsr   haveSeenAdvancehaveSeenOutlinehaveSeenLibhaveSeenNoter   ri   r'   r'   r(   _readGlyphFromTreeFormat1>  sT    




r  c              	   C  s  t || | g }g }g }d } }	 }
 }}t }| D ]h}|jdkr|r|
rVtd|jrdtd|jr|j dkrtdd}
|d urt||||| q6|d u rq6q6|jdkr|r|rtd	d}t|| q6|jd
kr,z,|	d}t
|d}||vr
|| W n ty(   tdY n0 q6|jdkr|rPt|rPtdt|j}dD ] }||v r^t|| ||< q^|| q6|jdkr|rt|rtdt|j}dD ]"}||jv rt|| ||< q|| q6|jdkr2|r |	rtdt|r tdd}	t||| q6|jdkrb|rR|rRtdd}t|| q6|jdkr|r|rtdd}t||| q6td| q6|rt|d| |r|rt||stdt|d| |r|r t||s tdt|d | d S )!NFr   r  r  r   r  Tr   r  r   r   r  r  r   z&Unknown children in guideline element.)r   r   r   r   z#Unknown children in anchor element.r   r   r   z(The image element occurs more than once.z"Unknown children in image element.r   r  rw   r	  r
  r   z(The guidelines are improperly formatted.r   z%The anchors are improperly formatted.r   )r  r   r   r	   r  r   r   buildOutlineFormat2r  r   r   r   rC   r   ra   _number
_readImager  r  r  r   r   )r   r   r;   r   r   r   r   r   r  ZhaveSeenImager  r  r  r   r   ri   r  rs   r'   r'   r(   _readGlyphFromTreeFormat2n  s    









r  c                 C  s6   | d}|r|std|r2| d ur2t| d| d S )Nrd   zEmpty glyph name in GLIF.)r   r	   r  )r   r   r   r4   r'   r'   r(   r    s
    
r  c                 C  s<   t |dd}t| d| t |dd}t| d| d S )Nr   r   r   )r  r   r  )r   r   r   r   r'   r'   r(   r    s    r  c                 C  s0   |j d}ddd |D }t| d| d S )Nr   c                 s  s   | ]}|  r|  V  qd S r   )r   )r   liner'   r'   r(   	<genexpr>      z_readNote.<locals>.<genexpr>r   )r   splitjoinr  )r   r   linesr'   r'   r(   r    s    r  c                 C  sN   t |dksJ |d }t|}|r>t|\}}|s>t|t| d| d S )Nr   r   rw   )r   r   Zfromtreer   r	   r  )r   rw   r   childplistr   r   r'   r'   r(   r    s    
r  c                 C  sT   t |j}tD ] \}}|||}t|||< q|rDt|sDtdt| d| d S )Nz,The image element is not properly formatted.r   )ra   r  r   r   r  r   r	   r  )r   r   r   Z	imageDatars   r"   rt   r'   r'   r(   r    s    
r  r   >   rK   yScalexScaleyxScalexOffsetyOffsetxyScale>   rN   rd   r   r   smoothnoyes>   qcurvecurveoffcurver   r  c                 C  s   g }|D ]}|j dkrht|dkrR|d }|j dkrRt||}|d urR|| q|d urt||| q|j dkr|d urt||| qtd| q| d ur|r|rt|stdt| d| d S )	Ncontourr   r   point	component&Unknown element in outline element: %sz*GLIF 1 anchors are not properly formatted.r   )	r   r   _buildAnchorFormat1r   _buildOutlineContourFormat1_buildOutlineComponentFormat1r	   r   r  )r   r:   r   r   r   r   r2  r   r'   r'   r(   r     s(    




r  c                 C  s   |  ddkrd S |  d}|d u r(d S |  d}|  d}|rP|d u rPtd|rd|d u rdtdt|}t|}t|||d}|S )	NrN   r   rd   r   r   z1Required x attribute is missing in point element.z1Required y attribute is missing in point element.)r   r   rd   )r   r	   r  ra   )r2  r   rd   r   r   r   r'   r'   r(   r5    s    


r5  c                 C  sH   |r|j rtd|   t|r<t|td|d}t| | |   d S )Nz&Unknown attributes in contour element.T)openContourOffCurveLeniencyr   )r  r	   r   r   "_validateAndMassagePointStructurespointAttributesFormat1_buildOutlinePointsFormat1r   )r:   r1  r   massagedr'   r'   r(   r6  (  s    

r6  c                 C  sL   |D ]B}|d }|d }|d }|d }|d }| j ||f|||d qd S )Nr   r   r   r+  rd   r   r+  rd   )r   )r:   r1  r2  r   r   r   r+  rd   r'   r'   r(   r;  1  s    r;  c                 C  s   |r8t |rtd|j D ]}|tvrtd| q|d}|rV|d u rVtdg }tD ]2\}}||}|d u r~|}nt|}|| q^| 	|t
| d S )N,Unknown child elements of component element.*Unknown attribute in component element: %srK   3The base attribute is not defined in the component.)r   r	   r  ry   componentAttributesFormat1r   r   r  r   addComponenttuple)r:   r3  r   rs   baseGlyphNametransformationr"   rt   r'   r'   r(   r7  :  s"    

r7  c                 C  sP   |D ]F}|j dkr"t|||| q|j dkr<t|||| qtd|j  qd S )Nr1  r3  r4  )r   _buildOutlineContourFormat2_buildOutlineComponentFormat2r	   )r   r:   r   r   r   r   r'   r'   r(   r  P  s    

r  c                 C  s   |r(|j  D ]}|tvrtd| q|d}|d urp|rf||v rRtd| t|sftd| || z| j|d W n$ ty   |   t	dt
 Y n0 t|rt|t|d}t| ||| |   d S )Nz(Unknown attribute in contour element: %sr   )The identifier %s is used more than once.z'The contour identifier %s is not valid.r   zbThe beginPath method needs an identifier kwarg. The contour's identifier value has been discarded.)r   )r  ry   contourAttributesFormat2r	   r   r   r*   r   rM   r   DeprecationWarningr   r9  pointAttributesFormat2_buildOutlinePointsFormat2r   )r:   r1  r   r   rs   r   r<  r'   r'   r(   rF  Y  s*    

rF  c              
   C  s   |D ]}|d }|d }|d }|d }|d }	| d}
|
d urx|rn|
|v rZtd|
 t|
sntd|
 ||
 z| j||f|||	|
d	 W q ty   | j||f|||	d
 tdt Y q0 qd S )Nr   r   r   r+  rd   r   rH  The identifier %s is not valid.)r   r+  rd   r   r=  z_The addPoint method needs an identifier kwarg. The point's identifier value has been discarded.)r   r	   r   r*   r   rM   r   rK  )r:   r1  r   r   r2  r   r   r   r+  rd   r   r'   r'   r(   rM  p  s&    

rM  c           
      C  s*  |r8t |rtd|j D ]}|tvrtd| q|d}|rV|d u rVtdg }tD ]2\}}||}|d u r~|}nt|}|| q^|d}	|	d ur|r|	|v rtd|	 |rt	|	std|	 |
|	 z| j|t||	d W n. ty$   | |t| td	t Y n0 d S )
Nr>  r?  rK   r@  r   rH  rN  rI  zgThe addComponent method needs an identifier kwarg. The component's identifier value has been discarded.)r   r	   r  ry   componentAttributesFormat2r   r   r  r   r   r*   rB  rC  rM   r   rK  )
r:   r3  r   r   rs   rD  rE  r"   rt   r   r'   r'   r(   rG    s:    



rG  Fc                 C  s  t | sd S d }d}g }t| D ]\}}|jdkrBtd|j t|j}	||	 |r|	 D ]}
|
|vrbtd|
 qbt |rtddD ]P}
zt|	|
 |	|
< W q t	y } ztd|
 d|W Y d }~qd }~0 0 q|	
d	d
}|r
|tvr
td| |d
krd }||	d< |d u r0d}n|}|rV|dkrV|dkrVtd|	dd}|r|d ur|tvrtd| |dk}||	d< |r|r|d u rtdd|jvr d |	d< q |r(|d d dkr(d}t|D ]$}	|	d d u r
|d7 }n qq|r(|d |  }|r|r|d urt |d | }|D ]~}	|	d }|d u rr|d7 }n\|r|dkrtdn>|dkrtdn*|dkr|dkrtdn|dkrn d}qR|S )NFr2  z.Unknown child element (%s) of contour element.z&Unknown attribute in point element: %sz(Unknown child elements in point element.r  z	Required z' attribute is missing in point element.rN   r0  zUnknown point type: %sr   Tr   r   z9A move point occurs after the first point in the contour.r+  r,  zUnknown point smooth value: %sr-  z*smooth attribute set in an offcurve point.rd   r   zmove can not have an offcurve.r  zline can not have an offcurve.r/  r   z%Too many offcurves defined for curve.r.  )r   	enumerater   r	   ra   r  r   ry   r  r   poppointTypeOptionsr   pointSmoothOptionsreversed)r1  ZpointAttributesr8  r   ZlastOnCurvePointZhaveOffCurvePointr<  indexr   r2  rs   r^   Z	pointTyper+  countZoffCurvesCountr   r'   r'   r(   r9    s    


*
















r9  c                 C  s(   zt | || W n ty"   Y n0 d S r   )rp   rq   )objectrs   rt   r'   r'   r(   r  
  s    r  c                 C  sT   zt | }|W S  ty    Y n0 zt| }|W S  tyN   td|  Y n0 dS )aw  
	Given a numeric string, return an integer or a float, whichever
	the string indicates. _number("1") will return the integer 1,
	_number("1.0") will return the float 1.0.

	>>> _number("1")
	1
	>>> _number("1.0")
	1.0
	>>> _number("a")  # doctest: +IGNORE_EXCEPTION_DETAIL
	Traceback (most recent call last):
	    ...
	GlifLibError: Could not convert a to an int or float.
	z(Could not convert %s to an int or float.N)r   rC   floatr	   )snr'   r'   r(   r    s    r  c                   @  s   e Zd ZdS )_DoneParsingN)r.   r/   r0   r'   r'   r'   r(   r[  0  r  r[  c                   @  s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
_BaseParserc                 C  s
   g | _ d S r   )_elementStackrl   r'   r'   r(   r7   4  s    z_BaseParser.__init__c                 C  s0   ddl m} | }| j|_| j|_|| d S )Nr   )ParserCreate)Zxml.parsers.expatr^  startElementHandlerStartElementHandlerendElementHandlerEndElementHandlerParse)r6   r   r^  r   r'   r'   r(   r   7  s
    z_BaseParser.parsec                 C  s   | j | d S r   )r]  r   r6   rd   r   r'   r'   r(   r_  >  s    z_BaseParser.startElementHandlerc                 C  s   | j d}||ksJ d S )NrB   )r]  rQ  )r6   rd   otherr'   r'   r(   ra  A  s    z_BaseParser.endElementHandlerN)r.   r/   r0   r7   r   r_  ra  r'   r'   r'   r(   r\  2  s   r\  c                 C  s   t  }||  |jS )z*
	Get a list of unicodes listed in glif.
	)_FetchUnicodesParserr   r   Zglifr   r'   r'   r(   r   H  s    
r   c                      s(   e Zd Z fddZ fddZ  ZS )rf  c                   s   g | _ t   d S r   )r   r!   r7   rl   r%   r'   r(   r7   R  s    z_FetchUnicodesParser.__init__c                   sx   |dkrf| j rf| j d dkrf|d}|d urfz$t|d}|| jvrP| j| W n tyd   Y n0 t || d S )Nr   rB   r   r   r  )r]  r   r   r   r   rC   r!   r_  )r6   rd   r   rt   r%   r'   r(   r_  V  s    


z(_FetchUnicodesParser.startElementHandlerr.   r/   r0   r7   r_  r2   r'   r'   r%   r(   rf  P  s   rf  c                 C  s.   t  }z||  W n ty&   Y n0 |jS )z+
	The image file name (if any) from glif.
	)_FetchImageFileNameParserr   r[  re   rg  r'   r'   r(   r   d  s    r   c                      s(   e Zd Z fddZ fddZ  ZS )ri  c                   s   d | _ t   d S r   )re   r!   r7   rl   r%   r'   r(   r7   q  s    z"_FetchImageFileNameParser.__init__c                   s>   |dkr,| j r,| j d dkr,|d| _tt || d S )Nr   rB   r   re   )r]  r   re   r[  r!   r_  rd  r%   r'   r(   r_  u  s    z-_FetchImageFileNameParser.startElementHandlerrh  r'   r'   r%   r(   ri  o  s   ri  c                 C  s2   t  }z||  W n ty&   Y n0 t|jS )z7
	Get a list of component base glyphs listed in glif.
	)_FetchComponentBasesParserr   r[  r   basesrg  r'   r'   r(   r   }  s    r   c                      s4   e Zd Z fddZ fddZ fddZ  ZS )rj  c                   s   g | _ t   d S r   )rk  r!   r7   rl   r%   r'   r(   r7     s    z#_FetchComponentBasesParser.__init__c                   sL   |dkr:| j r:| j d dkr:|d}|d ur:| j| t || d S )Nr3  rB   r   rK   )r]  r   rk  r   r!   r_  )r6   rd   r   rK   r%   r'   r(   r_    s
    
z._FetchComponentBasesParser.startElementHandlerc                   s   |dkrt t | d S )Nr   )r[  r!   ra  )r6   rd   r%   r'   r(   ra    s    z,_FetchComponentBasesParser.endElementHandler)r.   r/   r0   r7   r_  ra  r2   r'   r'   r%   r(   rj    s   rj  ))r&  r   )r*  r   )r'  r   )r%  r   )r(  r   )r)  r   c                   @  s@   e Zd ZdZdddZdddZdd	 Zdd
dZdddZdS )r   zY
	Helper class using the PointPen protocol to write the <outline>
	part of .glif files.
	NTc                 C  s@   |d u rt  }t|| _|| _|| _d | _d| _g | _|| _d S )Nr   )	r   r   r   r   r   r1  prevOffCurveCountprevPointTypesr   )r6   r   r   r   r   r'   r'   r(   r7     s    
zGLIFPointPen.__init__c                 K  sz   t  }|d ur^| jjdkr^| jrJ|| jv r6td| t|sJtd| ||d< | j| t	| j
d|| _d| _d S )Nr   r   %identifier not formatted properly: %sr   r1  r   )r   r   rU   r   r   r	   r   r*   r   r   r   r1  rl  )r6   r   r  r   r'   r'   r(   r     s    
zGLIFPointPen.beginPathc                 C  s^   | j r0| j d dkr0| jr0| j d dkr0tdt| jsBd| j_d | _d | _d| _g | _ d S )Nr   r   rB   r0  z%open contour has loose offcurve pointr   )rm  r   r	   r   r1  r   ZprevPointTyperl  rl   r'   r'   r(   r     s    
zGLIFPointPen.endPathc           	      K  s  t  }|d urP| jr0|D ]}t|tstdqt|d |d< t|d |d< |dkr\d }| jr|dkrx| jrxtd|d	v r| jr| jd
 dkrtd| |dkr| jdkrtd|d ur||d< nd}|dkr|  jd7  _nd| _| j| |r"| jr|dkrtdd|d< |d ur4||d< |d ur| j	j
dkr| jr|| jv rltd| t|std| ||d< | j| t| jd| d S )Nz coordinates must be int or floatr   r   r   r   r0  r   z@move occurs after a point has already been added to the contour.)r   r  rB   z offcurve occurs before %s point.r/  r   z,too many offcurve points before curve point.rN   z&can't set smooth in an offcurve point.r-  r+  rd   r   rn  r   r2  )r   r   rF   r   r	   r   rm  rl  r   r   rU   r   r   r*   r   r   r1  )	r6   ptr   r+  rd   r   r  r   Zcoordr'   r'   r(   r     sN    




zGLIFPointPen.addPointc           	      K  s   t d|fg}tt|D ]8\\}}}| jr<t|ts<td||krt|||< q|d ur| jj	dkr| jr|| j
v rtd| | jrt|std| ||d< | j
| t| jd| d S )NrK   z*transformation values must be int or floatr   r   rn  r   r3  )r   zipr   r   rF   r   r	   r   r   rU   r   r   r*   r   r   r   )	r6   r4   rE  r   r  r   rs   r"   rt   r'   r'   r(   rB    s    
zGLIFPointPen.addComponent)NNT)N)NNNN)N)	r.   r/   r0   r>   r7   r   r   r   rB  r'   r'   r'   r(   r     s   


0r   __main__)NNNT)NNNNT)NNNT)NNN)NNNr   )FT)sr>   
__future__r   loggingenumwarningsr   collectionsr   rH   Zfs.baseZ	fs.errorsZfs.osfsZfs.pathZfontTools.misc.textToolsr   ZfontTools.miscr   ZfontTools.pens.pointPenr   r   rD   r	   ZfontTools.ufoLib.filenamesr
   ZfontTools.ufoLib.validatorsr   r   r   r   r   r   r   r   ZfontTools.ufoLibr   r   ZfontTools.ufoLib.utilsr   r   __all__	getLoggerr.   r   rS   rn   rC  Enumr   __str__r3   r   r   r   r   r   r   r   r   r   r   r   r   r   ra   rG   rx   r   ro   r   r   r    r   r  r  r)   r+   r   r  r  r  r  r  rJ  rA  rO  r:  rL  rS  rR  r  r5  r6  r;  r7  r  rF  rM  rG  r9  r  r  	Exceptionr[  r\  r   rf  r   ri  r   rj  r   r   doctesttestmodr'   r'   r'   r(   <module>   s   $	
   a    
R     
A    
=


.
1 
Z


			"
c 
l
