o
    h                    @  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 Z4				d~ddZ5					dddZ6				d~d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<ZH	dd=d>ZI	dd?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 Zb	dddde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rddlqZqeqr  dS 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__ l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fontTools/ufoLib/glifLib.pyr"   B   s   
zGLIFFormatVersion.defaultc                   s8   |d u r	t   S | jh}|tjkr|| j t|S r   )r!   r    
FORMAT_1_0r   
FORMAT_3_0add
FORMAT_2_0	frozenset)r#   r$   versionsr%   r'   r(   r    H   s   

z$GLIFFormatVersion.supported_versionsr   )	__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 )Glyphz
    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)selfr5   r6   r'   r'   r(   __init__c   s   
zGlyph.__init__Fc                 C  s   t ||d}| | dS )z9
        Draw this glyph onto a *FontTools* Pen.
        )outputImpliedClosingLineN)r   
drawPoints)r7   penr9   pointPenr'   r'   r(   drawg   s   z
Glyph.drawc                 C  s   | j | j| | dS )z2
        Draw this glyph onto a PointPen.
        N)r6   	readGlyphr5   )r7   r<   r'   r'   r(   r:   p   s   zGlyph.drawPointsN)F)r/   r0   r1   __doc__r8   r=   r:   r'   r'   r'   r(   r4   ]   s
    
	r4   c                   @  s   e Zd ZdZeZ					d/ddZd0ddZd	d
 Zdd Z	d0ddZ
d0ddZdd Zdd Zd1ddZ				d2ddZdd Zdd Zdd ZeZdd  Zd!d" Zd0d#d$Zd0d%d&Zd0d'd(Zd)d* Zd+d, Zd-d. ZdS )3r   aL  
    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y  } zddlm} |d||d}~ww t|dr*| }t|trKztj	
|}	W n tjjyF   td| w d| _n,t|tjjrn|}	z|	  W n tjjyi   td|	 w d	| _n	td
t|j z|	d}W n tjjy   t|	}Y nw tj|d | _|	| _|	t| _|r| jstt d|j| _|| _ |du rt!}|| _!|| _"|| _#d| _$d| _%| &  dS )a  
        '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@   hasattrrA   
isinstancestrfsosfsOSFSerrorsCreateFailedr	   _shouldClosebaseFScheckFilesystemClosed	TypeErrortyper/   
getsyspath	NoSysPathpathpartsdirNameexistsCONTENTS_FILENAME_havePreviousFilemajorr$   ufoFormatVersionTupler   _validateRead_validateWrite_existingFileNames_reverseContentsrebuildContents)
r7   rW   glyphNameToFileNameFuncr$   validateReadvalidateWriteexpectContentsFileer@   
filesystemr'   r'   r(   r8      sf   


zGlyphSet.__init__c                 C  s   |du r| j }| ti }|rGd}t|tsd}n&| D ]!\}}t|ts(d}t|ts0d}q| j|s>t	dt|f q|rGt	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)r_   	_getPlistr[   rG   dictitemsrH   rI   rZ   r	   contentsra   rb   )r7   re   rm   invalidFormatnamefileNamer'   r'   r(   rc      s0   



zGlyphSet.rebuildContentsc                 C  s:   | j du ri }| 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)rb   rm   rl   lower)r7   dkvr'   r'   r(   getReverseContents   s   
	zGlyphSet.getReverseContentsc                 C  s   |  t| j dS )zv
        Write the contents.plist file out to disk. Call this method when
        you're done writing glyphs.
        N)_writePlistr[   rm   r7   r'   r'   r(   writeContents  s   zGlyphSet.writeContentsc              	   C  sx   |du r| j }| ti }|rt|tstdt|}| D ]\}}zt||| W q  t	y9   td| w 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).)
r_   rj   LAYERINFO_FILENAMErG   rk   r	   validateLayerInfoVersion3Datarl   setattrAttributeError)r7   infore   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 ]+}t||rFzt||}W n ty6   td| w |du sA|dkrB|sBq|||< q|rW|rOt	|}| 
t| dS | jrh| jtrj| jt dS dS 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)r`   r^   r]   r	   layerInfoVersion3ValueDatakeysrF   getattrr|   rz   rv   ry   r\   rI   rZ   remove)r7   r}   rf   infoDatar   r   r'   r'   r(   writeLayerInfo,  s>   
zGlyphSet.writeLayerInfoc                 C  s@   | j | }z| j|W S  tjjy   td||| jf w )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 %s)rm   rI   	readbytesrL   ResourceNotFoundr	   r7   r5   rp   r'   r'   r(   getGLIFP  s   

zGlyphSet.getGLIFc                 C  s   | j | }| |S )ao  
        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.
        )rm   getFileModificationTimer   r'   r'   r(   getGLIFModificationTimee  s   

z GlyphSet.getGLIFModificationTimec                 C  s   |du r| j }| |}zt|}t| j}t|||||d W dS  tyd } z6| j| }	zd| j	
|	 d}
W n t	jjyR   d|	 dt| j	 d}
Y nw |d| d|
 d  d}~ww )a`  
        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'z' from 'zThe issue is in glyph 'z', located in .)r_   r   _glifTreeFromStringr   r    r^   _readGlyphFromTreer	   rm   rI   rU   rL   rV   rH   	_add_note)r7   r5   glyphObjectr<   r   texttreer   glifLibErrorrp   glifLocationr'   r'   r(   r>   r  s8   ,

zGlyphSet.readGlyphc           
   
   C  sX  |du rt | j}n!zt |}W n ty+ } zddlm} |d||d}~ww |t | jvrFddlm} |d|d| jd|du rM| j}| j	|}|du r| j
du rgdd	 | j D | _
| || j
}|| j|< | j
|  | jdur|| j| < t|||||d
}	| jr| j|r|	| j|krdS | j||	 dS )aV  
        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 r   c                 S  s   h | ]}|  qS r'   )rq   ).0rp   r'   r'   r(   	<setcomp>  s    z&GlyphSet.writeGlyph.<locals>.<setcomp>)formatVersionr   )r   r"   r^   rD   rE   r   r    r`   rm   getra   valuesr   r+   rq   rb   _writeGlyphToBytesr\   rI   rZ   r   
writebytes)
r7   r5   r   drawPointsFuncr   r   rh   r   rp   datar'   r'   r(   
writeGlyph  sb   5



zGlyphSet.writeGlyphc                 C  sR   | j | }| j| | jdur| j|  | jdur#| j| = | j |= dS )zPermanently delete the glyph from the glyph set on disk. Will
        raise KeyError if the glyph is not present in the glyph set.
        N)rm   rI   r   ra   rq   rb   r   r'   r'   r(   deleteGlyph"  s   


zGlyphSet.deleteGlyphc                 C  s   t | j S r   )listrm   r   rw   r'   r'   r(   r   0  s   zGlyphSet.keysc                 C  s
   || j v S r   )rm   r7   r5   r'   r'   r(   has_key3     
zGlyphSet.has_keyc                 C  s
   t | jS r   )lenrm   rw   r'   r'   r(   __len__8  r   zGlyphSet.__len__c                 C  s   || j vr	t|| || S r   )rm   KeyError
glyphClassr   r'   r'   r(   __getitem__;  s   
zGlyphSet.__getitem__c                 C  :   i }|du r| j  }|D ]}| |}t|||< q|S )aC  
        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)rm   r   r   _fetchUnicodes)r7   
glyphNamesunicodesr5   r   r'   r'   r(   getUnicodesB     

zGlyphSet.getUnicodesc                 C  r   )aF  
        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)rm   r   r   _fetchComponentBases)r7   r   
componentsr5   r   r'   r'   r(   getComponentReferencesQ  r   zGlyphSet.getComponentReferencesc                 C  r   )a9  
        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)rm   r   r   _fetchImageFileName)r7   r   imagesr5   r   r'   r'   r(   getImageReferences`  r   zGlyphSet.getImageReferencesc                 C  s   | j r
| j  d S d S r   )rN   rI   closerw   r'   r'   r(   r   o  s   zGlyphSet.closec                 C  s   | S r   r'   rw   r'   r'   r(   	__enter__s  s   zGlyphSet.__enter__c                 C  s   |    d S r   )r   )r7   exc_type	exc_valueexc_tbr'   r'   r(   __exit__v  s   zGlyphSet.__exit__)NNTTFr   NNNNNNN)r/   r0   r1   r?   r4   r   r8   rc   ru   rx   r   r   r   r   r>   r   r   r   r   __contains__r   r   r   r   r   r   r   r   r'   r'   r'   r(   r   |   sD    

Q 
	
$
N
e


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
   )r5   existingFileNamesr'   r'   r(   r     s   r   Tc           
   	   C  s   t | }|du rt }n/t t }}|D ]}zt|}	W n ty,   || Y qw ||	 q|s<t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   rD   r+   r   )
aStringr   r<   r   r   r   validFormatVersionsinvalidFormatVersionsrt   r   r'   r'   r(   r     s0   8

r   c                 C  s  zt |}W n ty   ddlm} |dw |r#t| ts#td|r/t| dkr/tdtd| fdt	|j
fg}|jdkrHt	|j|d< td	|}t }	t||| t|d
drct||| t|ddrot||| |j
dkrt|ddrt||| |j
dkrt|ddrt|||	| t|dd}
|j
dkr|
rt|||	| |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.ro   formatformatMinorglyphr   Nnoter   image
guidelinesanchorsoutline)identifiersr   r   
  r   zUTF-8T)encodingxml_declarationpretty_print)r   rD   rE   r   rG   rH   r	   r   r   reprr]   minorr   Elementr   _writeAdvancer   _writeUnicodes
_writeNote_writeImage_writeGuidelines_writeAnchors
SubElementGLIFPointPen_writeAnchorsFormat1r   	_writeLibtostring)r5   r   r   writerr   r   r   
glyphAttrsrootr   r   r   r;   r   r'   r'   r(   r     sZ   	
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)r5   r   r   r   r   r   r'   r'   r(   r   '  s   3
r   c              	   C  s   t | dd }|d ur|rt|tstd|dkrd }t | dd }|d ur6|r0t|ts0td|dkr6d }|d urS|d urSt|dtdt|fdt|fg d S |d uret|dtt|d d S |d urwt|dtt|d d S d S )	Nwidthz$width attribute must be int or floatr   heightz%height attribute must be int or floatadvance)r   )r   )	r   rG   r   r	   r   r   r   r   rk   )r   elementr   r   r   r'   r'   r(   r   d  s.   r   c                 C  sz   t | dd }|rt|tr|g}t }|D ]%}|r"t|ts"td||v r'q|| d| }t|dt|d qd S )Nr   zunicode values must be intz%04Xunicode)hex)	r   rG   intr   r	   r+   r   r   rk   )r   r   r   r   seencodehexCoder'   r'   r(   r   }  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
)r   rG   rH   r	   stripr   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r/t|||< q|d}|d ur=||d< t|d| d S )Nr   zMimage attribute must be a dict or dict-like object with the proper structure.rp   color)	r   r   r	   r   _transformationInfor   r   r   r   )	r   r   r   r   attrsr   r"   r   r   r'   r'   r(   r     s   
r   c                 C  s  t | dg }|rt|std|D ]q}t }|d}|d ur&t||d< |d}|d ur5t||d< |d}	|	d urDt|	|d< |d}
|
d urQ|
|d< |d}|d ur^||d< |d}|d ur||rs||v rstd	| ||d< || t|d
| qd S )Nr   z8guidelines attribute does not have the proper structure.xyanglero   r   
identifier"identifier used more than once: %s	guideline)	r   r   r	   r   r   r   r+   r   r   )r   r   r   r   r   r  r   r   r   r   ro   r   r  r'   r'   r(   r     s8   






r   c                 C  s   |r
t |s
td|D ]7}i }|d }t||d< |d }t||d< |d}|d ur1||d< |   | j||fd|d |   qd S )N5anchors attribute does not have the proper structure.r   r   ro   move)segmentTypero   )r   r	   r   r   	beginPathaddPointendPath)r;   r   r   anchorr   r   r   ro   r'   r'   r(   r     s   

r   c                 C  s   t | dg }|rt|std|D ]X}t }|d }t||d< |d }t||d< |d}	|	d ur8|	|d< |d}
|
d urE|
|d< |d}|d urc|rZ||v rZtd| ||d< || t|d	| qd S )
Nr   r  r   r   ro   r   r  r  r
  )	r   r   r	   r   r   r   r+   r   r   )r   r   r   r   r   r
  r   r   r   ro   r   r  r'   r'   r(   r     s.   



r   c                 C  sf   t | dd }|s
d S |rt|\}}|st|t|ts!t|}tj|dd}t|d	| d S )Nr   r   )indent_level)
r   r   r	   rG   rk   r   totreer   r   append)r   r   r   r   validmessagerh   r'   r'   r(   r     s   
r   )rT   valueValidator)r   r   c                 C  sj   | t vrdS t |  }|d}|d}|d}|dur$|||}|S |tkr/|||}|S ||}|S )a  
    This performs very basic validation of the value for attribute
    following the UFO 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.
    FrT   r  valueOptionsN)r   r   r   )r   r   dataValidationDict	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).)rl   r   r	   r  )r   r   r   r  r'   r'   r(   rz   $  s   

rz   c                 C  sb   t jrt j| t jddd}nt | }| }|jdkr!td|jr/|j dkr/td|S )NTremove_commentsparserr   #The GLIF is not properly formatted. Invalid GLIF structure.)	r   
_have_lxmlparse	XMLParsergetroottagr	   r   r   )aFiler   r   r'   r'   r(   _glifTreeFromFile<  s   

r$  c              
   C  s   t | dd}ztjrtj|tjddd}nt|}W n ty- } ztd|d }~ww |jdkr7td|jrE|j	 d	krEtd
|S )Nr   )r   Tr  r  zGLIF contains invalid XML.r   r  r  r  )
r   r   r  
fromstringr   	Exceptionr	   r"  r   r   )r   r   r   etree_exceptionr'   r'   r(   r   I  s   


r   c              
   C  s   |  d}|r|d u rtd|  dd}ztt|t|f}W n0 tyQ } z$d||f }	|r<ddlm}
 |
|	|t }t	d|	| W Y d }~nd }~ww |r_||vr_td|zt
| }W n typ   t|w || ||||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   rD   rE   r   r"   loggerwarning_READ_GLYPH_FROM_TREE_FUNCSr   NotImplementedErrorr   )r   r   r<   r   r   formatVersionMajorformatVersionMinorr   rh   msgr   readGlyphFromTreer'   r'   r(   r   Z  sL   


r   c              	   K  s  t || | g }d } } }}	| D ]}
|
jdkr@|r6|r!td|
jr(td|
jr6|
j dkr6tdd}t|||
| q|d u rEq|
jdkrZ|rR|rRtd	d}t||
 q|
jd
kr|
d}|d u rltdzt	|d}||vr{|
| W q ty   tdw |
jdkr|r|	rtdd}	t||
 q|
jdkr|r|rtdd}t||
| qtd|
 |rt|d| d S 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   8A unicode element is missing its required hex attribute.   3Illegal value for hex attribute of unicode element.r   'The note element occurs more than once.r   &The lib element occurs more than once.Unknown element in GLIF: %sr   )	_readNamer"  r	   attribr   r   buildOutlineFormat1_readAdvancer   r   r  rD   	_readNote_readLib_relaxedSetattr)r   r   r<   r   kwargsr   haveSeenAdvancehaveSeenOutlinehaveSeenLibhaveSeenNoter   rt   r'   r'   r(   _readGlyphFromTreeFormat1  sj   







rF  c              	   C  s  t || | g }g }g }d } }	 }
 }}t }| D ])}|jdkrO|r@|
r+td|jr2td|jr@|j dkr@tdd}
|d urNt||||| q|d u rTq|jdkri|ra|ratd	d}t|| q|jd
kr|	d}|d u r{tdzt
|d}||vr|| W q ty   tdw |jdkr|rt|rtdt|j}dD ]}||v rt|| ||< q|| q|jdkr|rt|rtdt|j}dD ]}||jv rt|| ||< q|| q|jdkr|r|	rtdt|rtdd}	t||| q|jdkr'|r|rtdd}t|| q|jdkr@|r7|r7tdd}t||| qtd| |rOt|d| |re|r_t||s_tdt|d| |r}|rut||sutd t|d!| d S d S )"NFr   r0  r1  r  r2  Tr   r3  r   r   r4  r5  r6  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   r7  r   r8  r9  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  rD   r   rk   _number
_readImager>  r?  r@  r   r   )r   r   r<   r   r   r   r   r   rB  haveSeenImagerC  rD  rE  r   r   rt   r;  r   r'   r'   r(   _readGlyphFromTreeFormat2  s   













rL  c                 C  s>   | d}|r|std|r| d urt| d| d S d S d S )Nro   zEmpty glyph name in GLIF.)r   r	   r@  )r   r   r   r5   r'   r'   r(   r:  3  s   
r:  c                 C  s<   t |dd}t| d| t |dd}t| d| d S )Nr   r   r   )rI  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>D  s    z_readNote.<locals>.<genexpr>r   )r   splitjoinr@  )r   r   linesr'   r'   r(   r>  B  s   r>  c                 C  sN   t |dksJ |d }t|}|rt|\}}|st|t| d| d S )Nr   r   r   )r   r   fromtreer   r	   r@  )r   r   r   childplistr  r  r'   r'   r(   r?  H  s   
r?  c                 C  sT   t |j}tD ]\}}|||}t|||< q|r"t|s"tdt| d| d S )Nz,The image element is not properly formatted.r   )rk   r;  r   r   rI  r   r	   r@  )r   r   r   	imageDatar   r"   r   r'   r'   r(   rJ  S  s   
rJ  r  >   rO   xScaleyScalexOffsetxyScaleyOffsetyxScale>   r   r   ro   rT   smoothnoyes>   rM  r  curveqcurveoffcurvec                 C  s   g }|D ]E}|j dkr4t|dkr)|d }|j dkr)t||}|d ur)|| q|d ur3t||| q|j dkrD|d urCt||| qtd| | d urb|rd|rZt|sZtdt| d| d S d S 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   rc  r
  r'   r'   r(   r<  t  s.   




r<  c                 C  s   |  ddkr	d S |  d}|d u rd S |  d}|  d}|r(|d u r(td|r2|d u r2tdt|}t|}t|||d}|S )	NrT   r  ro   r   r   z1Required x attribute is missing in point element.z1Required y attribute is missing in point element.)r   r   ro   )r   r	   rI  rk   )rc  r   ro   r   r   r
  r'   r'   r(   rf    s   


rf  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;   rb  r   massagedr'   r'   r(   rg    s   

rg  c                 C  sL   |D ]!}|d }|d }|d }|d }|d }| j ||f|||d qd S )Nr   r   r  r\  ro   r  r\  ro   )r  )r;   rb  rc  r   r   r  r\  ro   r'   r'   r(   rl    s   rl  c                 C  s   |rt |r
td|j D ]}|tvrtd| q|d}|r+|d u r+tdg }tD ]\}}||}|d u r?|}nt|}|| q/| 	|t
| d S )N,Unknown child elements of component element.*Unknown attribute in component element: %srO   3The base attribute is not defined in the component.)r   r	   r;  r   componentAttributesFormat1r   r   rI  r  addComponenttuple)r;   rd  r   r   baseGlyphNametransformationr"   r   r'   r'   r(   rh    s$   

rh  c                 C  sN   |D ]"}|j dkrt|||| q|j dkrt|||| qtd|j  d S )Nrb  rd  re  )r"  _buildOutlineContourFormat2_buildOutlineComponentFormat2r	   )r   r;   r   r   r   r   r'   r'   r(   rH    s   

rH  c                 C  s   |r|j  D ]}|tvrtd| q|d}|d ur8|r3||v r)td| t|s3td| || z| j|d W n tyR   |   t	dt
 Y nw t|ret|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;  r   contourAttributesFormat2r	   r   r   r+   r  rS   r   DeprecationWarningr   rj  pointAttributesFormat2_buildOutlinePointsFormat2r	  )r;   rb  r   r   r   r  rm  r'   r'   r(   rw    s@   

rw  c              
   C  s   |D ]a}|d }|d }|d }|d }|d }	| d}
|
d ur<|r7|
|v r-td|
 t|
s7td|
 ||
 z| j||f|||	|
d	 W q tyc   | j||f|||	d
 tdt Y qw d S )Nr   r   r  r\  ro   r  ry  The identifier %s is not valid.)r  r\  ro   r  rn  z_The addPoint method needs an identifier kwarg. The point's identifier value has been discarded.)r   r	   r   r+   r  rS   r   r|  )r;   rb  r   r   rc  r   r   r  r\  ro   r  r'   r'   r(   r~    s@   


r~  c           
      C  s(  |rt |r
td|j D ]}|tvrtd| q|d}|r+|d u r+tdg }tD ]\}}||}|d u r?|}nt|}|| q/|d}	|	d uro|rj|	|v r^td|	 |rjt	|	sjtd|	 |
|	 z| j|t||	d W d S  ty   | |t| td	t Y d S w )
Nro  rp  rO   rq  r  ry  r  rz  zgThe addComponent method needs an identifier kwarg. The component's identifier value has been discarded.)r   r	   r;  r   componentAttributesFormat2r   r   rI  r  r   r+   rs  rt  rS   r   r|  )
r;   rd  r   r   r   ru  rv  r"   r   r  r'   r'   r(   rx    sH   




rx  Fc                 C  s  t | sd S d }d}g }t| D ]\}}|jdkr td|j t|j}	||	 |rE|	 D ]}
|
|vr<td|
 q0t |rEtddD ]!}
z
t|	|
 |	|
< W qG t	yh } z	td|
 d|d }~ww |	
d	d
}|r{|tvr{td| |d
krd }||	d< |d u rd}n|}|r|dkr|dkrtd|	dd}|r|d ur|tvrtd| |dk}||	d< |r|r|d u rtdd|jvrd |	d< q|r|d d dkrd}t|D ]}	|	d d u r|d7 }q |r|d |  }|rL|rL|d urLt |d | }|D ]?}	|	d }|d u r|d7 }q|rH|dkr)td|dkr2td|dkrA|dkr@tdn|dkrGn	 d}q|S )NFrc  z.Unknown child element (%s) of contour element.z&Unknown attribute in point element: %sz(Unknown child elements in point element.rG  z	Required z' attribute is missing in point element.rT   ra  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.ro   r   zmove can not have an offcurve.rM  zline can not have an offcurve.r_  r   z%Too many offcurves defined for curve.r`  )r   	enumerater"  r	   rk   r;  r  r   rI  r   poppointTypeOptionsr   pointSmoothOptionsreversed)rb  pointAttributesri  r   lastOnCurvePointhaveOffCurvePointrm  indexr   rc  r   rh   	pointTyper\  countoffCurvesCountr  r'   r'   r(   rj  D  s   











rj  c                 C  s(   z	t | || W d S  ty   Y d S w r   )r{   r|   )objectr   r   r'   r'   r(   r@    s
   r@  c                 C  sL   zt | }|W S  ty   Y nw zt| }|W S  ty%   td|  w )a  
    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.)r   rD   floatr	   )snr'   r'   r(   rI    s   rI  c                   @  s   e Zd ZdS )_DoneParsingN)r/   r0   r1   r'   r'   r'   r(   r    s    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   )_elementStackrw   r'   r'   r(   r8     r   z_BaseParser.__init__c                 C  s2   ddl m} | }| j|_| j|_||d d S )Nr   )ParserCreater   )xml.parsers.expatr  startElementHandlerStartElementHandlerendElementHandlerEndElementHandlerParse)r7   r   r  r  r'   r'   r(   r    s
   z_BaseParser.parsec                 C  s   | j | d S r   )r  r  r7   ro   r   r'   r'   r(   r    s   z_BaseParser.startElementHandlerc                 C  s   | j d}||ksJ d S )NrC   )r  r  )r7   ro   otherr'   r'   r(   r    s   z_BaseParser.endElementHandlerN)r/   r0   r1   r8   r  r  r  r'   r'   r'   r(   r    s
    r  c                 C  s   t  }||  |jS )z0
    Get a list of unicodes listed in glif.
    )_FetchUnicodesParserr  r   glifr  r'   r'   r(   r     s   
r   c                      (   e Zd Z fddZ fddZ  ZS )r  c                      g | _ t   d S r   )r   r!   r8   rw   r%   r'   r(   r8        z_FetchUnicodesParser.__init__c                   sx   |dkr3| j r3| j d dkr3|d}|d ur3zt|d}|| jvr(| j| W n	 ty2   Y nw t || d S )Nr   rC   r   r   r5  )r  r   r   r   r  rD   r!   r  )r7   ro   r   r   r%   r'   r(   r    s   


z(_FetchUnicodesParser.startElementHandlerr/   r0   r1   r8   r  r3   r'   r'   r%   r(   r        r  c                 C  s0   t  }z	||  W |jS  ty   Y |jS w )z1
    The image file name (if any) from glif.
    )_FetchImageFileNameParserr  r  rp   r  r'   r'   r(   r     s   r   c                      r  )r  c                   s   d | _ t   d S r   )rp   r!   r8   rw   r%   r'   r(   r8   $  r  z"_FetchImageFileNameParser.__init__c                   s>   |dkr| j r| j d dkr|d| _tt || d S )Nr   rC   r   rp   )r  r   rp   r  r!   r  r  r%   r'   r(   r  (  s   z-_FetchImageFileNameParser.startElementHandlerr  r'   r'   r%   r(   r  #  r  r  c                 C  s2   t  }z||  W n	 ty   Y nw t|jS )z=
    Get a list of component base glyphs listed in glif.
    )_FetchComponentBasesParserr  r  r   basesr  r'   r'   r(   r   2  s   
r   c                      s4   e Zd Z fddZ fddZ fddZ  ZS )r  c                   r  r   )r  r!   r8   rw   r%   r'   r(   r8   ?  r  z#_FetchComponentBasesParser.__init__c                   sL   |dkr| j r| j d dkr|d}|d ur| j| t || d S )Nrd  rC   r   rO   )r  r   r  r  r!   r  )r7   ro   r   rO   r%   r'   r(   r  C  s   
z._FetchComponentBasesParser.startElementHandlerc                   s   |dkrt t | d S )Nr   )r  r!   r  )r7   ro   r%   r'   r(   r  N  s   z,_FetchComponentBasesParser.endElementHandler)r/   r0   r1   r8   r  r  r3   r'   r'   r%   r(   r  >  s    r  ))rV  r   )rY  r   )r[  r   )rW  r   )rX  r   )rZ  r   c                   @  sB   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   zb
    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   rb  prevOffCurveCountprevPointTypesr   )r7   r   r   r   r   r'   r'   r(   r8   i  s   

zGLIFPointPen.__init__c                 K  sz   t  }|d ur/| jjdkr/| jr%|| jv rtd| t|s%td| ||d< | j| t	| j
d|| _d| _d S )Nr   r  %identifier not formatted properly: %sr  rb  r   )r   r   r]   r   r   r	   r   r+   r   r   r   rb  r  )r7   r  rA  r   r'   r'   r(   r  t  s   

zGLIFPointPen.beginPathc                 C  s^   | j r| j d dkr| jr| j d dkrtdt| js!d| j_d | _d | _d| _g | _ d S )Nr   r  rC   ra  z%open contour has loose offcurve pointr   )r  r   r	   r   rb  r   prevPointTyper  rw   r'   r'   r(   r	    s   

zGLIFPointPen.endPathc           	      K  s  t  }|d ur(| jr|D ]}t|tstdqt|d |d< t|d |d< |dkr.d }| jr]|dkr<| jr<td|d	v rP| jrP| jd
 dkrPtd| |dkr]| jdkr]td|d urf||d< nd}|dkrt|  jd7  _nd| _| j| |r| jr|dkrtdd|d< |d ur||d< |d ur| j	j
dkr| jr|| jv rtd| t|std| ||d< | j| t| jd| d S )Nz coordinates must be int or floatr   r   r   r   ra  r  z@move occurs after a point has already been added to the contour.)r  rM  rC   z offcurve occurs before %s point.r_  r   z,too many offcurve points before curve point.rT   z&can't set smooth in an offcurve point.r^  r\  ro   r  r  r  rc  )r   r   rG   r   r	   r   r  r  r  r   r]   r   r   r+   r   r   rb  )	r7   ptr  r\  ro   r  rA  r   coordr'   r'   r(   r    sb   


zGLIFPointPen.addPointc           	      K  s   t d|fg}tt|D ]\\}}}| jrt|tstd||kr(t|||< q|d urX| jj	dkrX| jrN|| j
v rAtd| | jrNt|sNtd| ||d< | j
| t| jd| d S )NrO   z*transformation values must be int or floatr   r  r  r  rd  )r   zipr   r   rG   r   r	   r   r   r]   r   r   r+   r   r   r   )	r7   r5   rv  r  rA  r   r   r"   r   r'   r'   r(   rs    s(   
zGLIFPointPen.addComponent)NNTr   r   )	r/   r0   r1   r?   r8   r  r	  r  rs  r'   r'   r'   r(   r   c  s    


<r   __main__)NNNT)NNNNTr   )NNNr   )FT)sr?   
__future__r   loggingenumwarningsr   collectionsr   rI   fs.base	fs.errorsfs.osfsfs.pathfontTools.misc.textToolsr   fontTools.miscr   fontTools.pens.pointPenr   r   rE   r	   fontTools.ufoLib.filenamesr
   fontTools.ufoLib.validatorsr   r   r   r   r   r   r   r   fontTools.ufoLibr   r   fontTools.ufoLib.utilsr   r   __all__	getLoggerr/   r(  r[   ry   rt  Enumr   __str__r4   r   r   r   r   r   r   r   r   r   r   r   r   r   rk   rH   r   r  rz   r$  r   r    r   rF  rL  r)   r,   r*  r:  r=  r>  r?  rJ  r{  rr  r  rk  r}  r  r  r<  rf  rg  rl  rh  rH  rw  r~  rx  rj  r@  rI  r&  r  r  r   r  r   r  r   r  r   r   doctesttestmodr'   r'   r'   r(   <module>   s    $	
    
V
E
=	


4
<
f
	


!!*
m"	 
