a
    w=icǂ                     @   sf  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 d dlmZmZ d d	l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'Z.g d(Z/d4d)d*Z0d5d,d-Z1d.d/ Z2d6d1d2Z3d
S )7    )Config)	xmlWriter)AbstractConfig)Tagbyteordtostr)deprecateArgument)
TTLibError)_TTGlyph_TTGlyphSetCFF_TTGlyphSetGlyf)
SFNTReader
SFNTWriter)BytesIOStringIONc                   @   sx  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dUddZ	dVddZ
dWddZdXddZdYddZdZddZdd Zd d! ZeZd"d# Zd[d$d%Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd\d0d1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&d^dJdKZ'dLdM Z(d_dNdOZ)dPdQ Z*d`dSdTZ+dS )a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::

		>> 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 :ref:`tables`.
	To add a table to the font, use the :py:func:`newTable` function::

		>> 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
	:ref:`ttx` binary)::

		>> 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
rd| nt|| _|	| _|s|| _|| _d | _d S t|dsd}|d urddlm} |dkr||r||d}qt|d}q|||}n
t|d}nd	}|d | jsH|d t| }t|d
r6|j|_|rD|  |}|| _t|||d| _| jj| _| jj| _| jj| _d S )N)verbosequietconfigure logging insteadreadT   )macUtilsr   rbFname)
fontNumber)localsgetr   setattrlazyrecalcBBoxesrecalcTimestamptablesreader
isinstancer   copyr   cfgignoreDecompileErrorssfntVersionflavor
flavorDatahasattr r   ZgetSFNTResIndicesZSFNTResourceReaderopenseekr   r   r   close_tableCacher   )selffileZres_name_or_indexr(   r)   checkChecksumsr   r    ZallowVIDr'   r!   r   r   r   r0   r&   r   valZcloseStreamr   tmp r6   g/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/fontTools/ttLib/ttFont.py__init__[   sT    






zTTFont.__init__c                 C   s   | S Nr6   r1   r6   r6   r7   	__enter__   s    zTTFont.__enter__c                 C   s   |    d S r9   )r/   )r1   typevalue	tracebackr6   r6   r7   __exit__   s    zTTFont.__exit__c                 C   s   | j dur| j   dS )z+If we still have a reader object, close it.N)r#   r/   r:   r6   r6   r7   r/      s    
zTTFont.closec                 C   s   t |ds,| jr&| jjj|kr&tdd}nd}t }| |}|du s|s|du r^| jdu s|du rvt| j	 }nd}|
  t }t||| |  |}|rt|d}||  W d   q1 s0    Y  n||  |  dS )at  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#   r2   r   r	   r   _savelistkeysflushreorderFontTablesr/   r-   r@   getvalue)r1   r2   ZreorderTablesZcreateStreamr5   Zwriter_reordersTables
tableOrderZtmp2r6   r6   r7   save   s6    

.zTTFont.savec                 C   s   | j rd| v r| d  t|  }d|v r4|d t|}t||| j| j| j}g }|D ]}| 	|||| qZ|
  | S )zAInternal function, to be shared by save() and TTCollection.save()head
GlyphOrder)r!   rC   rD   removelenr   r(   r)   r*   _writeTabler/   ZreordersTables)r1   r2   
tableCachetags	numTableswriterdonetagr6   r6   r7   rB      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_saveXMLr/   )r1   
fileOrPathrW   kwargsrR   r6   r6   r7   saveXML   s    	zTTFont.saveXMLrawc
                 C   s  |d urt dd || _|	| _|s`t|  }d|vr@dg| }|r`|D ]}
|
|v rH||
 qHt|}|rddlm} d	|
dd d }|jdtt| jd	d
 |d n |jdtt| jd	d
 d |  |p|}|s|  ntj|j\}}|d | }t|D ]}|| }
|r|t|
 }tj||jd}|jd|d |  |  |jt|
tj|d |  n|}| j||
|d |r|d |  |  q|d |  d S )Nr   r   rK   r   )version.   ttFontr   r   )r(   ttLibVersion)r(   z.%srV   )rb   )srcsplitGlyphs)r   disassembleInstructionsbitmapGlyphDataFormatrC   rD   rL   rM   	fontToolsr^   joinsplitbegintagreprr   r(   newlineospathsplitextfilenamerangetagToIdentifierr   rX   rW   	simpletagtagToXMLbasename_tableToXMLendtagr/   )r1   rR   ZwriteVersionr   r"   Z
skipTablesZsplitTablesre   rf   rg   rT   rQ   r^   ro   extZfileNameTemplateiZ	tablePathZtableWriterr6   r6   r7   rY      s\    

 



zTTFont._saveXMLc           
      C   s   |d urt dd || v r,| | }d| }nd| }t| || vrJd S t|}t }t|drjd|d< ddlm}	 |j|	krd	|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   DefaultTableTr]   glyfrd   )r   loginforu   dictr+   tables.DefaultTabler}   	__class__rk   rm   toXMLrx   )
r1   rR   rT   r   re   tablereportZxmlTagattrsr}   r6   r6   r7   rw   0  s0    





zTTFont._tableToXMLc                 C   sN   |durt dd d| v r*d| v r*|   ddlm} ||| }|  dS )zSImport a TTX file (an XML-based text format), so as to recreate
		a font object.
		Nr   r   maxppostr   )	xmlReader)r   getGlyphOrderfontTools.miscr   Z	XMLReaderr   )r1   rZ   r   r   r#   r6   r6   r7   	importXMLL  s    
zTTFont.importXMLc                 C   s
   || j v S )z\Return true if the table identified by ``tag`` has been
		decompiled and loaded into memory.r"   r1   rT   r6   r6   r7   isLoaded_  s    zTTFont.isLoadedc                 C   s6   |  |rdS | jr"|| jv r"dS |dkr.dS 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.TrK   FN)r   r#   r   r6   r6   r7   has_keyd  s    
zTTFont.has_keyc                 C   s^   t | j }| jr:t | j D ]}||vr"|| q"d|v rL|d t|}dg| S )zSReturns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table.rK   )rC   r"   rD   r#   appendrL   sortedTagList)r1   rD   keyr6   r6   r7   rD   t  s    
zTTFont.keysc                 C   sL   |   D ]8}| | }|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)rD   r   r+   r   )r1   r   rT   r   r6   r6   r7   r     s    
zTTFont.ensureDecompiledc                 C   s   t t|  S r9   )rM   rC   rD   r:   r6   r6   r7   __len__  s    zTTFont.__len__c                 C   s^   t |}| j|}|d u rZ|dkr8t|}|| j|< n"| jd urN| |}ntd| |S )NrK   '%s' table not found)r   r"   r   rK   r#   
_readTableKeyErrorr1   rT   r   r6   r6   r7   __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 nl ty   | j	s t 
d| ddlm} t }tj|d ||}| |_|| j|< |||  Y n0 | 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|   )r2   )r   debugr#   r0   r   getTableClassr"   Z	decompile	Exceptionr'   	exceptionr   r}   r   r>   	print_excrG   r{   )r1   rT   datar   
tableClassr}   r2   r6   r6   r7   r     s8    





zTTFont._readTablec                 C   s   || j t|< d S r9   )r"   r   r   r6   r6   r7   __setitem__  s    zTTFont.__setitem__c                 C   sB   || vrt d| || jv r&| j|= | jr>|| jv r>| j|= d S )Nr   )r   r"   r#   r   r6   r6   r7   __delitem__  s    
zTTFont.__delitem__c                 C   s&   z
| | W S  t y    | Y S 0 dS )zGReturns the table if it exists or (optionally) a default if it doesn't.N)r   )r1   rT   defaultr6   r6   r7   r     s    
z
TTFont.getc                 C   s0   || _ t| dr| `| dr,| d | dS )zTSet the glyph order

		Args:
			glyphOrder ([str]): List of glyph names in order.
		_reverseGlyphOrderDictr~   N)
glyphOrderr+   r   r   setGlyphOrder)r1   r   r6   r6   r7   r     s
    

zTTFont.setGlyphOrderc                 C   s   z| j W S  ty   Y n0 d| v r8| d }| | _ n\d| v r| d  }|du r^|   qt|| d jk rtd |   q|| _ n|   | 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   _getGlyphNamesFromCmaprM   	numGlyphsr   warning)r1   Zcffr   r6   r6   r7   r     s"    


zTTFont.getGlyphOrderc           
      C   s  |  dr| jd }| jd= nd }t| d j}d g| }d|d< td|D ]}d| ||< qL|| _d| v rz| d  }ni }i }t|D ]^}|| }||v r| t|| }|	|dd  }	||< |	dkrd||	d f }|||< qd| v r| jd= || _|r|| jd< d S )Ncmapr   z.notdefr   r   	glyph%.5dz%s.alt%d)
r   r"   intr   rr   r   ZbuildReversed_makeGlyphNameminr   )
r1   ZcmapLoadingr   r   rz   ZreversecmapZuseCountZtempName	glyphNameZnumUsesr6   r6   r7   r     s6    





zTTFont._getGlyphNamesFromCmapc                 C   s<   ddl m} | |jv r |j|  S | dkr0d|  S d|  S d S )Nr   )agli  zuni%04Xzu%X)rh   r   ZUV2AGL)	codepointr   r6   r6   r7   r   <  s    

zTTFont._makeGlyphNamec                 C   s   t |  }|S )z1Get a list of glyph names, sorted alphabetically.)sortedr   )r1   Z
glyphNamesr6   r6   r7   getGlyphNamesF  s    zTTFont.getGlyphNamesc                 C   s   ddl m} ||  S )zNGet a list of glyph names, sorted alphabetically,
		but not case sensitive.
		r   )	textTools)r   r   ZcaselessSortr   )r1   r   r6   r6   r7   getGlyphNames2K  s    zTTFont.getGlyphNames2c                 C   s.   z|   | W S  ty(   d|  Y S 0 dS )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   N)r   
IndexError)r1   glyphIDr6   r6   r7   getGlyphNameR  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   r6   ).0gidZcntr   r6   r7   
<listcomp>a  s   z+TTFont.getGlyphNameMany.<locals>.<listcomp>)r   rM   r1   lstr6   r   r7   getGlyphNameMany]  s
    zTTFont.getGlyphNameManyc                 C   sl   z|   | W S  tyf   |dd dkrbzt|dd W  Y S  ttfy`   t|Y n0 Y n0 dS )z0Returns the ID of the glyph with the given name.N   Zglyph)getReverseGlyphMapr   r   	NameError
ValueError)r1   r   r6   r6   r7   
getGlyphIDd  s    zTTFont.getGlyphIDc                    sL   |    z fdd|D W S  tyF   | jfdd|D  Y S 0 dS )z8Converts a list of glyph names into a list of glyph IDs.c                    s   g | ]} | qS r6   r6   r   r   )dr6   r7   r   s      z)TTFont.getGlyphIDMany.<locals>.<listcomp>c                    s   g | ]} |qS r6   r6   r   )r   r6   r7   r   v  r   N)r   r   r   r   r6   )r   r   r7   getGlyphIDManyo  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   )r1   Zrebuildr6   r6   r7   r   x  s    zTTFont.getReverseGlyphMapc                 C   s,   i  | _ }t|  D ]\}}|||< q|S r9   )r   	enumerater   )r1   r   r   r   r6   r6   r7   r   ~  s    

z"TTFont._buildReverseGlyphOrderDictc           	      C   s   ||v rdS t |}|jD ]0}||vr|| v r@| |||| q|| q|| | |}|dur|t||f}|durtd| |	|| dS td| |||< |dur|| |t||f< dS )zWInternal helper function for self.save(). Keeps track of
		inter-table dependencies.
		Nzreusing '%s' tablezWriting '%s' table to disk)
r   dependenciesrN   r   getTableDatar   r   r   r   ZsetEntry)	r1   rT   rR   rS   rO   r   ZmasterTableZ	tabledataentryr6   r6   r7   rN     s(    


zTTFont._writeTablec                 C   s`   t |}| |r.td| | j| | S | jrT|| jv rTtd| | j| S t|dS )zReturns 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   N)r   r   r   r   r"   compiler#   r   r   r6   r6   r7   r     s    

zTTFont.getTableDatac                 C   sf   |rd| vrd}|r"|s"|  |}d| v s2d| v rH|s>d| vrHt| |S d| v rZt| |S tddS )a  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   ZCFF2r~   zFont contains no outlines)normalizeLocationr   r   r	   )r1   Z	preferCFFlocation
normalizedr6   r6   r7   getGlyphSet  s    


zTTFont.getGlyphSetc                 C   s   ddl m}m} d| vr tddd | d jD }|||}d| v r| d }|j}i }| D ].\}}	||d}
|
dur||	|
}	|	||< q`|}|S )	as  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   piecewiseLinearMapr   zNot a variable fontc                 S   s    i | ]}|j |j|j|jfqS r6   )axisTagZminValuedefaultValueZmaxValue)r   ar6   r6   r7   
<dictcomp>  s   z,TTFont.normalizeLocation.<locals>.<dictcomp>avarN)ZfontTools.varLib.modelsr   r   r	   axessegmentsitemsr   )r1   r   r   r   r   r   ZavarSegmentsZmappedLocationr   r=   ZavarMappingr6   r6   r7   r     s$    



zTTFont.normalizeLocation)   
   )r      )r      )r   r   )r   r   )r   r`   )r   r   )r   r   c                 C   s   | d j |dS )aR  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)r1   r   r6   r6   r7   r     s    zTTFont.getBestCmap)T)N)rU   )TNNNFFTr]   )NF)N)N)N)F)N)TNF)r   ),__name__
__module____qualname____doc__NotImplementedr8   r;   r?   r/   rI   rB   r\   rY   rw   r   r   r   __contains__rD   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   rN   r   r   r   r   r6   r6   r6   r7   r      sb   I
=
/

    
<




!D
		


#r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
rK   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 r9   r6   r   r6   r6   r7   r8     s    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   commentrm   rr   rM   rt   )r1   rR   ra   r   rz   r   r6   r6   r7   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   )r1   r   r   contentra   r6   r6   r7   fromXML  s
    
zGlyphOrder.fromXML)N)r   r   r   r   r8   r   r   r6   r6   r6   r7   rK     s   

rK   c              
   C   s|   ddl m} t| }ztd|  W nH tyl } z0t||dkrTW Y d}~dS |W Y d}~nd}~0 0 t||S dS )zUFetch the packer/unpacker module for a table.
	Return None when no module is found.
	r   r   zfontTools.ttLib.tables.r   N)r,   r"   rs   
__import__ImportErrorstrfindgetattr)rT   r"   pyTagerrr6   r6   r7   getTableModule&  s    r   c                 C   s$   |du rdt |  }||ft| < dS )aP  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_)rs   _customTableRegistry)rT   
moduleName	classNamer6   r6   r7   registerCustomTableClassA  s    
r  c                 C   s
   t | = dS )z8Unregister the custom packer/unpacker class for a table.N)r   rT   r6   r6   r7   unregisterCustomTableClassP  s    r  c                 C   s4   | t vrdS ddl}t |  \}}||}t||S )zyReturn the custom table class for tag, if one has been registered
	with 'registerCustomTableClass()'. Else return None.
	Nr   )r   	importlibimport_moduler   )rT   r  r   r  moduler6   r6   r7   getCustomTableClassU  s    
r  c                 C   sN   t | }|dur|S t| }|du r4ddlm} |S t| }t|d| }|S )z,Fetch the packer/unpacker class for a table.Nr   r|   r   )r  r   r   r}   rs   r   )rT   r   r  r}   r   r6   r6   r7   r   a  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   r6   r6   r7   getClassTago  s    r  c                 C   s   t | }|| S )z!Return a new instance of a table.)r   )rT   r   r6   r6   r7   newTablew  s    r  c                 C   sH   ddl }|d| rd|  S |d| r0| d S tt| dd S dS )z%Helper function for tagToIdentifier()r   Nz[a-z0-9]_z[A-Z]r`   )rematchhexr   )cr  r6   r6   r7   _escapechar}  s    r  c                 C   s   ddl }t| } | dkr| S t| dks0J dt| dkrV| d dkrV| dd } q0d	}| D ]}|t| }q^|d
|rd| }|S )ar  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::

		>>> tagToIdentifier('glyf')
		'_g_l_y_f'
		>>> tagToIdentifier('cvt ')
		'_c_v_t'
		>>> tagToIdentifier('OS/2')
		'O_S_2f_2'
	r   NrK   r   ztag should be 4 characters longr   r    r,   z[0-9]r  )r  r   rM   r  r  )rT   r  identr  r6   r6   r7   rs     s    rs   c                 C   s   | dkr| S t | d r0| d dkr0| dd } t | d r@J d}tdt | dD ]^}| | dkrv|| |d   }qT| |d  dkr|| |  }qT|tt| ||d  d }qT|d	t | d
  }t|S )z!the opposite of tagToIdentifier()rK   r`   r   r  r   Nr,      r   r  )rM   rr   chrr   r   )r  rT   rz   r6   r6   r7   r	    s     r	  c                 C   sH   ddl }t| } | dkrdS | dkr(| S |d| r<|  S t| S d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_2rK   z[A-Za-z_][A-Za-z_0-9]* *$)r  r   r  striprs   )rT   r  r6   r6   r7   ru     s    ru   c                 C   s@   | dkrt dS t| dkr$t| S t | ddt|    S dS )zThe opposite of tagToXML()r  r     r  r   N)r   rM   r	  r  r6   r6   r7   xmlToTag  s
    r  )rJ   hhear   r  ZhmtxZLTSHZVDMXZhdmxr   Zfpgmprepzcvt Zlocar~   kernr   r   ZgaspZPCLT)rJ   r  r   r  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 rF|| | | qF||  |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.
	NZDSIGr   )r   rL   r   OTFTableOrderTTFTableOrderextend)ZtagListrH   ZorderedTablesrT   r6   r6   r7   r     s    



r   Fc                 C   sp   |  d | d t| |d}t|t|j|j|j|j}t|	 }t
||D ]}|| ||< qR|  dS )z]Rewrite a font file, ordering the tables as recommended by the
	OpenType specification 1.4.
	r   )r3   N)r.   r   r   rM   r"   r(   r)   r*   rC   rD   r   r/   )ZinFileZoutFilerH   r3   r#   rR   r"   rT   r6   r6   r7   rF     s    

rF   c                 C   s(   d}| r| d? } |d }qt |d dS )zYReturn the highest exponent of two, so that
	(2 ** exponent) <= x.  Return 0 if x is 0.
	r   r   )max)xexponentr6   r6   r7   maxPowerOfTwo  s
    
r%  r  c                 C   s4   t | }d| | }|}td| | | }|||fS )z3Calculate searchRange, entrySelector, rangeShift.
	r`   r   )r%  r"  )nZitemSizer$  ZsearchRangeZentrySelectorZ
rangeShiftr6   r6   r7   getSearchRange  s
    r'  )N)N)NF)r  )4ZfontTools.configr   r   r   ZfontTools.misc.configToolsr   ZfontTools.misc.textToolsr   r   r   ZfontTools.misc.loggingToolsr   ZfontTools.ttLibr	   ZfontTools.ttLib.ttGlyphSetr
   r   r   ZfontTools.ttLib.sfntr   r   ior   r   rn   loggingr>   	getLoggerr   r   objectr   rK   r   r   r  r  r  r   r  r  r  rs   r	  ru   r  r   r  r   rF   r%  r'  r6   r6   r6   r7   <module>   sN   
      
 

