o
    h                     @   sn  d dl mZ d dlmZ d dlmZ d dlmZ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 d dlmZmZ d d	lmZmZmZ d d
lZd d
lZd d
lZeeZG dd de Z!G dd de Z"dd Z#i Z$d3ddZ%dd Z&dd Z'dd Z(dd Z)dd Z*dd Z+dd  Z,d!d" Z-d#d$ Z.d%d& Z/g d'Z0g d(Z1d3d)d*Z2d4d,d-Z3d.d/ Z4d5d1d2Z5d
S )6    )Config)	xmlWriter)AbstractConfig)Tagbyteordtostr)deprecateArgument)
TTLibError)_TTGlyph_TTGlyphSetCFF_TTGlyphSetGlyf_TTGlyphSetVARC)
SFNTReader
SFNTWriter)BytesIOStringIOUnsupportedOperationNc                   @   s  e Zd ZdZdddddddeddddddi fdd	Zd
d Zdd Zdd ZdWddZ	dXddZ
dYddZ								dZddZd[ddZdXddZdd Zd d! ZeZd"d# ZdXd$d%Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ ZdXd0d1Zd2d3 Zd4d5 Zd6d7 Zed8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dDdE Z$d\dFdGZ%dHdI Z&dXdJdKZ'dLdM Z(	d]dNdOZ)dPdQ Z*	Rd^dSdTZ+dUdV Z,dS )_TTFonta_  Represents a TrueType font.

    The object manages file input and output, and offers a convenient way of
    accessing tables. Tables will be only decompiled when necessary, ie. when
    they're actually accessed. This means that simple operations can be extremely fast.

    Example usage:

    .. code-block:: pycon

        >>>
        >> from fontTools import ttLib
        >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file
        >> tt['maxp'].numGlyphs
        242
        >> tt['OS/2'].achVendID
        'B&H '
        >> tt['head'].unitsPerEm
        2048

    For details of the objects returned when accessing each table, see the
    :doc:`tables </ttLib/tables>` documentation.
    To add a table to the font, use the :py:func:`newTable` function:

    .. code-block:: pycon

        >>>
        >> os2 = newTable("OS/2")
        >> os2.version = 4
        >> # set other attributes
        >> font["OS/2"] = os2

    TrueType fonts can also be serialized to and from XML format (see also the
    :doc:`ttx </ttx>` binary):

    .. code-block:: pycon

        >>
        >> tt.saveXML("afont.ttx")
        Dumping 'LTSH' table...
        Dumping 'OS/2' table...
        [...]

        >> tt2 = ttLib.TTFont() # Create a new font object
        >> tt2.importXML("afont.ttx")
        >> tt2['maxp'].numGlyphs
        242

    The TTFont object may be used as a context manager; this will cause the file
    reader to be closed after the context ``with`` block is exited::

            with TTFont(filename) as f:
                    # Do stuff

    Args:
            file: When reading a font from disk, either a pathname pointing to a file,
                    or a readable file object.
            res_name_or_index: If running on a Macintosh, either a sfnt resource name or
                    an sfnt resource index number. If the index number is zero, TTLib will
                    autodetect whether the file is a flat file or a suitcase. (If it is a suitcase,
                    only the first 'sfnt' resource will be read.)
            sfntVersion (str): When constructing a font object from scratch, sets the four-byte
                    sfnt magic number to be used. Defaults to ``   `` (TrueType). To create
                    an OpenType file, use ``OTTO``.
            flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2
                    file.
            checkChecksums (int): How checksum data should be treated. Default is 0
                    (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to
                    raise an exception if any wrong checksums are found.
            recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``,
                    ``head`` bounding box values and ``hhea``/``vhea`` min/max values on save.
                    Also compiles the glyphs on importing, which saves memory consumption and
                    time.
            ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation
                    will be ignored, and the binary data will be returned for those tables instead.
            recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in
                    the ``head`` table on save.
            fontNumber (int): The index of the font in a TrueType Collection file.
            lazy (bool): If lazy is set to True, many data structures are loaded lazily, upon
                    access only. If it is set to False, many data structures are loaded immediately.
                    The default is ``lazy=None`` which is somewhere in between.
    Nz   r   TFc                 C   s  dD ]}t  |}|d urt|d t| || q|| _|| _|
| _i | _d | _t	|t
r2| nt|| _|	| _|sG|| _|| _d | _d S d}t|ds}d}|d urwddlm} |dkrp||rj||d}n7t|d}n1|||}n*t|d}n$d	}t|d
r| }nt|drz|d W n ty   d	}Y nw | js|r|d t| }t|dr|j|_|r|  |}n|std|| _ t!|||d| _| jj| _| jj| _| jj| _d S )N)verbosequietconfigure logging insteadTread   )macUtilsr   rbFseekableseeknamez*Input file must be seekable when lazy=True)
fontNumber)"localsgetr   setattrlazyrecalcBBoxesrecalcTimestamptablesreader
isinstancer   copyr   cfgignoreDecompileErrorssfntVersionflavor
flavorDatahasattr r   getSFNTResIndicesSFNTResourceReaderopenr   r   r   r   r   r   closer	   _tableCacher   )selffileres_name_or_indexr,   r-   checkChecksumsr   r$   allowVIDr+   r%   r   r#   r   r5   r*   r   valr   closeStreamr   tmp r>   j/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fontTools/ttLib/ttFont.py__init__j   sj   









zTTFont.__init__c                 C   s   | S Nr>   r6   r>   r>   r?   	__enter__      zTTFont.__enter__c                 C   s   |    d S rA   )r4   )r6   typevalue	tracebackr>   r>   r?   __exit__   s   zTTFont.__exit__c                 C   s   | j dur| j   dS dS )z+If we still have a reader object, close it.N)r'   r4   rB   r>   r>   r?   r4      s   
zTTFont.closec                 C   s   t |ds| jr| jjj|krtdd}nd}t }| |}|du sP|sP|du r/| jdu sP|du r;t| j	 }nd}|
  t }t||| |  |}|rot|d}||  W d   n1 siw   Y  n||  |  dS )a  Save the font to disk.

        Args:
                file: Similarly to the constructor, can be either a pathname or a writable
                        file object.
                reorderTables (Option[bool]): If true (the default), reorder the tables,
                        sorting them by tag (recommended by the OpenType specification). If
                        false, retain the original font order. If None, reorder by table
                        dependency (fastest).
        writez4Can't overwrite TTFont when 'lazy' attribute is TrueTFNwb)r/   r#   r'   r7   r   r	   r   _savelistkeysflushreorderFontTablesr4   r3   rI   getvalue)r6   r7   reorderTablescreateStreamr=   writer_reordersTables
tableOrdertmp2r>   r>   r?   save   s4   

zTTFont.savec                 C   s   | j rd| v r| d  t|  }d|v r|d t|}t||| j| j| j}g }|D ]
}| 	|||| q-|
  | S )zAInternal function, to be shared by save() and TTCollection.save()head
GlyphOrder)r%   rL   rM   removelenr   r,   r-   r.   _writeTabler4   reordersTables)r6   r7   
tableCachetags	numTableswriterdonetagr>   r>   r?   rK      s    
zTTFont._save
c                 K   s,   t j||d}| j|fi | |  dS )a  Export the font as TTX (an XML-based text file), or as a series of text
        files when splitTables is true. In the latter case, the 'fileOrPath'
        argument should be a path to a directory.
        The 'tables' argument must either be false (dump all tables) or a
        list of tables to dump. The 'skipTables' argument may be a list of tables
        to skip, but only when the 'tables' argument is false.
        
newlinestrN)r   	XMLWriter_saveXMLr4   )r6   
fileOrPathre   kwargsr`   r>   r>   r?   saveXML  s   	zTTFont.saveXMLrawc
                 C   s  |d ur	t dd || _|	| _|s0t|  }d|vr dg| }|r0|D ]}
|
|v r/||
 q$t|}|rZddlm} d	|
dd d }|jdtt| jd	d
 |d n|jdtt| jd	d
 d |  |pq|}|sy|  n	tj|j\}}t|D ]T}|| }
|r|d t|
 | }tj||jd}|jd|d |  |  |jt|
tj|d |  n|}| j||
|d |r|d |  |  q|d |  d S )Nr   r   rX   r   )version.   ttFontr   r   )r,   ttLibVersion)r,   rd   )rp   )srcsplitGlyphs)r   disassembleInstructionsbitmapGlyphDataFormatrL   rM   rY   rZ   	fontToolsrl   joinsplitbegintagreprr   r,   newlineospathsplitextfilenamerangetagToIdentifierr   rf   re   	simpletagtagToXMLbasename_tableToXMLendtagr4   )r6   r`   writeVersionr   r&   
skipTablessplitTablesrs   rt   ru   rb   r_   rl   r}   exti	tablePathtableWriterr>   r>   r?   rg   $  sb   


 



zTTFont._saveXMLc           
      C   s   |d ur	t dd || v r| | }d| }nd| }t| || vr%d S t|}t }t|dr5d|d< ddlm}	 |j|	krDd	|d
< |j	|fi | |
  |dkr^|j|| |d n|||  || |
  |
  d S )Nr   r   zDumping '%s' table...zNo '%s' table found.ERRORzdecompilation errorr   DefaultTableTrk   glyfrr   )r   loginfor   dictr/   tables.DefaultTabler   	__class__ry   r{   toXMLr   )
r6   r`   rb   r   rs   tablereportxmlTagattrsr   r>   r>   r?   r   j  s0   





zTTFont._tableToXMLc                 C   sN   |dur	t dd d| v rd| v r|   ddlm} ||| }|  dS )z_Import a TTX file (an XML-based text format), so as to recreate
        a font object.
        Nr   r   maxppostr   )	xmlReader)r   getGlyphOrderfontTools.miscr   	XMLReaderr   )r6   rh   r   r   r'   r>   r>   r?   	importXML  s   
zTTFont.importXMLc                 C   s
   || j v S )zbReturn true if the table identified by ``tag`` has been
        decompiled and loaded into memory.r&   r6   rb   r>   r>   r?   isLoaded  s   
zTTFont.isLoadedc                 C   s2   |  |rdS | jr|| jv rdS |dkrdS dS )zTest if the table identified by ``tag`` is present in the font.

        As well as this method, ``tag in font`` can also be used to determine the
        presence of the table.TrX   F)r   r'   r   r>   r>   r?   has_key  s   
zTTFont.has_keyc                 C   s^   t | j }| jrt | j D ]}||vr|| qd|v r&|d t|}dg| S )zSReturns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table.rX   )rL   r&   rM   r'   appendrY   sortedTagList)r6   rM   keyr>   r>   r?   rM     s   


zTTFont.keysc                 C   sL   |   D ]}| | }|du r| jdu}|r t|dr |j|d qd| _dS )zEDecompile all the tables, even if a TTFont was opened in 'lazy' mode.NFensureDecompiled)recurse)rM   r#   r/   r   )r6   r   rb   r   r>   r>   r?   r     s   

zTTFont.ensureDecompiledc                 C   s   t t|  S rA   )rZ   rL   rM   rB   r>   r>   r?   __len__  s   zTTFont.__len__c                 C   sb   t |}| j|}|d u r/|dkrt|}|| j|< |S | jd ur)| |}|S td| |S )NrX   '%s' table not found)r   r&   r!   rX   r'   
_readTableKeyErrorr6   rb   r   r>   r>   r?   __getitem__  s   


zTTFont.__getitem__c                 C   s   t d| | j| }| jd ur| j||f}|d ur|S t|}||}|| j|< t d| z|||  W n6 tyo   | j	sD t 
d| ddlm} t }tj|d ||}| |_|| j|< |||  Y nw | jd ur||| j||f< |S )NReading '%s' table from diskzDecompiling '%s' tablez@An exception occurred during the decompilation of the '%s' tabler   r   )r7   )r   debugr'   r5   r!   getTableClassr&   	decompile	Exceptionr+   	exceptionr   r   r   rG   	print_excrP   r   )r6   rb   datar   
tableClassr   r7   r>   r>   r?   r     s:   





zTTFont._readTablec                 C   s   || j t|< d S rA   )r&   r   r   r>   r>   r?   __setitem__  s   zTTFont.__setitem__c                 C   sJ   || vr
t d| || jv r| j|= | jr!|| jv r#| j|= d S d S d S )Nr   )r   r&   r'   r   r>   r>   r?   __delitem__  s   
zTTFont.__delitem__c                 C   s"   z| | W S  t y   | Y S w )zGReturns the table if it exists or (optionally) a default if it doesn't.)r   )r6   rb   defaultr>   r>   r?   r!     s
   
z
TTFont.getc                 C   s4   || _ t| dr
| `| dr| d | dS dS )zmSet the glyph order

        Args:
                glyphOrder ([str]): List of glyph names in order.
        _reverseGlyphOrderDictr   N)
glyphOrderr/   r   r   setGlyphOrder)r6   r   r>   r>   r?   r     s   

zTTFont.setGlyphOrderc                 C   s   z| j W S  ty   Y nw d| v r| d }| | _ | j S d| v rN| d  }|du r3|   | j S t|| d jk rHtd |   | j S || _ | j S |   | j S )zDReturns a list of glyph names ordered by their position in the font.CFF r   Nr   zMNot enough names found in the 'post' table, generating them from cmap instead)r   AttributeErrorr   _getGlyphNamesFromCmaprZ   	numGlyphsr   warning)r6   cffr   r>   r>   r?   r     s0   
zTTFont.getGlyphOrderc           
      C   s  |  dr| jd }| jd= nd }t| d j}dd t|D }d|d< || _d| v r3| d  }ni }i }t|D ]-}|| }||v rh| || }||dd  }	||< |	dkrdd||	d f }|||< q;d| v r}| jd= || _|r|| jd< d S d S d S )	Ncmapr   c                 S   s   g | ]}d | qS 	glyph%.5dr>   ).0r   r>   r>   r?   
<listcomp>T      z1TTFont._getGlyphNamesFromCmap.<locals>.<listcomp>z.notdefr   r   z%s.alt%d)	r   r&   intr   r   r   buildReversedMin_makeGlyphNamer!   )
r6   cmapLoadingr   r   reversecmapuseCountr   tempName	glyphNamenumUsesr>   r>   r?   r   7  s8   


zTTFont._getGlyphNamesFromCmapc                 C   s8   ddl m} | |jv r|j|  S | dkrd|  S d|  S )Nr   )agli  zuni%04Xzu%X)rv   r   UV2AGL)	codepointr   r>   r>   r?   r   y  s   

zTTFont._makeGlyphNamec                 C   s   t |  }|S )z1Get a list of glyph names, sorted alphabetically.)sortedr   )r6   
glyphNamesr>   r>   r?   getGlyphNames  s   zTTFont.getGlyphNamesc                 C   s   ddl m} ||  S )zZGet a list of glyph names, sorted alphabetically,
        but not case sensitive.
        r   )	textTools)r   r   caselessSortr   )r6   r   r>   r>   r?   getGlyphNames2  s   zTTFont.getGlyphNames2c                 C   s*   z|   | W S  ty   d|  Y S w )zReturns the name for the glyph with the given ID.

        If no name is available, synthesises one with the form ``glyphXXXXX``` where
        ```XXXXX`` is the zero-padded glyph ID.
        r   )r   
IndexError)r6   glyphIDr>   r>   r?   getGlyphName  s
   zTTFont.getGlyphNamec                    s$   |   t  fdd|D S )z8Converts a list of glyph IDs into a list of glyph names.c                    s$   g | ]}| k r| nd | qS r   r>   )r   gidcntr   r>   r?   r     s   $ z+TTFont.getGlyphNameMany.<locals>.<listcomp>)r   rZ   r6   lstr>   r   r?   getGlyphNameMany  s   zTTFont.getGlyphNameManyc                 C   sb   z|   | W S  ty0   |dd dkr/zt|dd W  Y S  ttfy.   t|w  w )z0Returns the ID of the glyph with the given name.N   glyph)getReverseGlyphMapr   r   	NameError
ValueError)r6   r   r>   r>   r?   
getGlyphID  s   zTTFont.getGlyphIDc                    sH   |    z
 fdd|D W S  ty#   | jfdd|D  Y S w )z8Converts a list of glyph names into a list of glyph IDs.c                    s   g | ]} | qS r>   r>   r   r   )dr>   r?   r     r   z)TTFont.getGlyphIDMany.<locals>.<listcomp>c                    s   g | ]} |qS r>   r>   r   )r   r>   r?   r     r   )r   r   r   r   r>   )r   r   r?   getGlyphIDMany  s   zTTFont.getGlyphIDManyc                 C   s   |st | ds|   | jS )z.Returns a mapping of glyph names to glyph IDs.r   )r/   _buildReverseGlyphOrderDictr   )r6   rebuildr>   r>   r?   r     s   zTTFont.getReverseGlyphMapc                 C   s,   i  | _ }t|  D ]\}}|||< q|S rA   )r   	enumerater   )r6   r   r   r   r>   r>   r?   r     s   

z"TTFont._buildReverseGlyphOrderDictc           	      C   s   ||v rdS t |}|jD ]}||vr%|| v r | |||| q|| q|| | |}|durO|t||f}|durOtd| |	|| dS td| |||< |duri|| |t||f< dS dS )zcInternal helper function for self.save(). Keeps track of
        inter-table dependencies.
        Nzreusing '%s' tablezWriting '%s' table to disk)
r   dependenciesr[   r   getTableDatar!   r   r   r   setEntry)	r6   rb   r`   ra   r]   r   masterTable	tabledataentryr>   r>   r?   r[     s,   



zTTFont._writeTablec                 C   s\   t |}| |rtd| | j| | S | jr*|| jv r*td| | j| S t|)a  Returns the binary representation of a table.

        If the table is currently loaded and in memory, the data is compiled to
        binary and returned; if it is not currently loaded, the binary data is
        read from the font file and returned.
        zCompiling '%s' tabler   )r   r   r   r   r&   compiler'   r   r   r>   r>   r?   r     s   

zTTFont.getTableDatac                 C   s   |rd| vrd}|r|s|  |}d}d| v sd| v r'|s!d| vr't| |}nd| v r3t| ||d}ntdd| v rAt| ||}|S )	ab  Return a generic GlyphSet, which is a dict-like object
        mapping glyph names to glyph objects. The returned glyph objects
        have a ``.draw()`` method that supports the Pen protocol, and will
        have an attribute named 'width'.

        If the font is CFF-based, the outlines will be taken from the ``CFF ``
        or ``CFF2`` tables. Otherwise the outlines will be taken from the
        ``glyf`` table.

        If the font contains both a ``CFF ``/``CFF2`` and a ``glyf`` table, you
        can use the ``preferCFF`` argument to specify which one should be taken.
        If the font contains both a ``CFF `` and a ``CFF2`` table, the latter is
        taken.

        If the ``location`` parameter is set, it should be a dictionary mapping
        four-letter variation tags to their float values, and the returned
        glyph-set will represent an instance of a variable font at that
        location.

        If the ``normalized`` variable is set to True, that location is
        interpreted as in the normalized (-1..+1) space, otherwise it is in the
        font's defined axes space.
        fvarNr   CFF2r   )recalcBoundszFont contains no outlinesVARC)normalizeLocationr   r   r	   r   )r6   	preferCFFlocation
normalizedr   glyphSetr>   r>   r?   getGlyphSet  s   
zTTFont.getGlyphSetc                 C   sN   ddl m} d| vrtd| d  }|||}d| v r%| d || }|S )a  Normalize a ``location`` from the font's defined axes space (also
        known as user space) into the normalized (-1..+1) space. It applies
        ``avar`` mapping if the font contains an ``avar`` table.

        The ``location`` parameter should be a dictionary mapping four-letter
        variation tags to their float values.

        Raises ``TTLibError`` if the font is not a variable font.
        r   )r   r   zNot a variable fontavar)fontTools.varLib.modelsr   r	   getAxesrenormalizeLocation)r6   r  r   axesr>   r>   r?   r     s   

zTTFont.normalizeLocation)   
   )r      )r      )r  r   )r   r  )r   rn   )r   r   )r   r   c                 C   s   | d j |dS )a(  Returns the 'best' Unicode cmap dictionary available in the font
        or ``None``, if no Unicode cmap subtable is available.

        By default it will search for the following (platformID, platEncID)
        pairs in order::

                        (3, 10), # Windows Unicode full repertoire
                        (0, 6),  # Unicode full repertoire (format 13 subtable)
                        (0, 4),  # Unicode 2.0 full repertoire
                        (3, 1),  # Windows Unicode BMP
                        (0, 3),  # Unicode 2.0 BMP
                        (0, 2),  # Unicode ISO/IEC 10646
                        (0, 1),  # Unicode 1.1
                        (0, 0)   # Unicode 1.0

        This particular order matches what HarfBuzz uses to choose what
        subtable to use by default. This order prefers the largest-repertoire
        subtable, and among those, prefers the Windows-platform over the
        Unicode-platform as the former has wider support.

        This order can be customized via the ``cmapPreferences`` argument.
        r   )cmapPreferences)getBestCmap)r6   r  r>   r>   r?   r  ,  s   #zTTFont.getBestCmapc                 C   s   ddl m } || | d S )Nr   reorderGlyphsr  )r6   new_glyph_orderr  r>   r>   r?   r  Q  s   zTTFont.reorderGlyphs)TrA   )rc   )TNNNFFTrk   NF)F)TNFT)r
  )-__name__
__module____qualname____doc__NotImplementedr@   rC   rH   r4   rV   rK   rj   rg   r   r   r   r   __contains__rM   r   r   r   r   r   r   r!   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r[   r   r  r   r  r  r>   r>   r>   r?   r      s    U
X

1


F


 
#B


	

)
%r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
rX   zA pseudo table. The glyph order isn't in the font as a separate
    table, but it's nice to present it as such in the TTX format.
    Nc                 C   s   d S rA   r>   r   r>   r>   r?   r@   \  rD   zGlyphOrder.__init__c                 C   sP   |  }|d |  tt|D ]}|| }|jd||d |  qd S )NzAThe 'id' attribute is only for humans; it is ignored when parsed.GlyphID)idr   )r   commentr{   r   rZ   r   )r6   r`   ro   r   r   r   r>   r>   r?   r   _  s   
zGlyphOrder.toXMLc                 C   s8   t | dsg | _|dkr| j|d  || j d S )Nr   r  r   )r/   r   r   r   )r6   r   r   contentro   r>   r>   r?   fromXMLj  s
   
zGlyphOrder.fromXMLrA   )r  r  r  r  r@   r   r   r>   r>   r>   r?   rX   W  s
    
rX   c              
   C   sl   ddl m} t| }ztd|  W n ty0 } zt||dkr*W Y d}~dS |d}~ww t||S )z[Fetch the packer/unpacker module for a table.
    Return None when no module is found.
    r   r   zfontTools.ttLib.tables.r   N)r0   r&   r   
__import__ImportErrorstrfindgetattr)rb   r&   pyTagerrr>   r>   r?   getTableModuler  s   

r(  c                 C   s$   |du r
dt |  }||ft| < dS )ab  Register a custom packer/unpacker class for a table.

    The 'moduleName' must be an importable module. If no 'className'
    is given, it is derived from the tag, for example it will be
    ``table_C_U_S_T_`` for a 'CUST' tag.

    The registered table class should be a subclass of
    :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable`
    Ntable_)r   _customTableRegistry)rb   
moduleName	classNamer>   r>   r?   registerCustomTableClass  s   
r-  c                 C   s
   t | = dS )z8Unregister the custom packer/unpacker class for a table.N)r*  rb   r>   r>   r?   unregisterCustomTableClass  s   
r/  c                 C   s4   | t vrdS ddl}t |  \}}||}t||S )zReturn the custom table class for tag, if one has been registered
    with 'registerCustomTableClass()'. Else return None.
    Nr   )r*  	importlibimport_moduler%  )rb   r0  r+  r,  moduler>   r>   r?   getCustomTableClass  s   

r3  c                 C   sN   t | }|dur
|S t| }|du rddlm} |S t| }t|d| }|S )z,Fetch the packer/unpacker class for a table.Nr   r   r)  )r3  r(  r   r   r   r%  )rb   r   r2  r   r&  r>   r>   r?   r     s   r   c                 C   s.   | j }|dd dksJ |dd }t|S )z'Fetch the table tag for a class object.Nr  r)  )r  identifierToTag)klassr   r>   r>   r?   getClassTag  s   r6  c                 C   s   t | }|| S )z!Return a new instance of a table.)r   )rb   r   r>   r>   r?   newTable  s   r7  c                 C   sD   ddl }|d| rd|  S |d| r| d S tt| dd S )z%Helper function for tagToIdentifier()r   Nz[a-z0-9]_z[A-Z]rn   )rematchhexr   )cr9  r>   r>   r?   _escapechar  s   r=  c                 C   s   ddl }t| } | dkr| S t| dksJ dt| dkr6| d dkr6| dd } t| dkr6| d dks$d	}| D ]}|t| }q:|d
|rMd| }|S )a  Convert a table tag to a valid (but UGLY) python identifier,
    as well as a filename that's guaranteed to be unique even on a
    caseless file system. Each character is mapped to two characters.
    Lowercase letters get an underscore before the letter, uppercase
    letters get an underscore after the letter. Trailing spaces are
    trimmed. Illegal characters are escaped as two hex bytes. If the
    result starts with a number (as the result of a hex escape), an
    extra underscore is prepended. Examples:
    .. code-block:: pycon

        >>>
        >> tagToIdentifier('glyf')
        '_g_l_y_f'
        >> tagToIdentifier('cvt ')
        '_c_v_t'
        >> tagToIdentifier('OS/2')
        'O_S_2f_2'
    r   NrX   r  ztag should be 4 characters longr   r    r0   z[0-9]r8  )r9  r   rZ   r=  r:  )rb   r9  identr<  r>   r>   r?   r     s   r   c                 C   s   | dkr| S t | d r| d dkr| dd } t | d r J d}tdt | dD ]/}| | dkr;|| |d   }q*| |d  dkrJ|| |  }q*|tt| ||d  d }q*|d	t | d
  }t|S )z!the opposite of tagToIdentifier()rX   rn   r   r8  r   Nr0      r  r>  )rZ   r   chrr   r   )r?  rb   r   r>   r>   r?   r4    s    r4  c                 C   sD   ddl }t| } | dkrdS | dkr| S |d| r|  S t| S )zSimilarly to tagToIdentifier(), this converts a TT tag
    to a valid XML element name. Since XML element names are
    case sensitive, this is a fairly simple/readable translation.
    r   NOS/2OS_2rX   z[A-Za-z_][A-Za-z_0-9]* *$)r9  r   r:  stripr   )rb   r9  r>   r>   r?   r     s   r   c                 C   s<   | dkrt dS t| dkrt| S t | ddt|    S )zThe opposite of tagToXML()rC  rB     r>  r  )r   rZ   r4  r.  r>   r>   r?   xmlToTag"  s
   rF  )rW   hhear   rB  hmtxLTSHVDMXhdmxr   fpgmprepzcvt locar   kernr   r   gaspPCLT)rW   rG  r   rB  r   r   r   r   c                 C   sv   t | } |du rd| v r| d | d d| v rt}nt}g }|D ]}|| v r3|| | | q#||  |S )zReturn a sorted copy of tagList, sorted according to the OpenType
    specification, or according to a custom tableOrder. If given and not
    None, tableOrder needs to be a list of tag names.
    NDSIGr   )r   rY   r   OTFTableOrderTTFTableOrderextend)tagListrT   orderedTablesrb   r>   r>   r?   r   F  s    




r   Fc                 C   sp   |  d | d t| |d}t|t|j|j|j|j}t|	 }t
||D ]}|| ||< q)|  dS )zcRewrite a font file, ordering the tables as recommended by the
    OpenType specification 1.4.
    r   )r9   N)r   r   r   rZ   r&   r,   r-   r.   rL   rM   r   r4   )inFileoutFilerT   r9   r'   r`   r&   rb   r>   r>   r?   rO   ^  s   

rO   c                 C   s*   d}| r| d? } |d }| st |d dS )z_Return the highest exponent of two, so that
    (2 ** exponent) <= x.  Return 0 if x is 0.
    r   r   )max)xexponentr>   r>   r?   maxPowerOfTwor  s   r]  r@  c                 C   s4   t | }d| | }|}td| | | }|||fS )z1Calculate searchRange, entrySelector, rangeShift.rn   r   )r]  rZ  )nitemSizer\  searchRangeentrySelector
rangeShiftr>   r>   r?   getSearchRange}  s
   
rc  rA   r  )r@  )6fontTools.configr   r   r   fontTools.misc.configToolsr   fontTools.misc.textToolsr   r   r   fontTools.misc.loggingToolsr   fontTools.ttLibr	   fontTools.ttLib.ttGlyphSetr
   r   r   r   fontTools.ttLib.sfntr   r   ior   r   r   r|   loggingrG   	getLoggerr  r   objectr   rX   r(  r*  r-  r/  r3  r   r6  r7  r=  r   r4  r   rF  rT  rS  r   rO   r]  rc  r>   r>   r>   r?   <module>   sP    
      G
#

