a
    ׶a                     @   sz  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 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G dd deZG dd deZG dd deZG dd deZdd Zi Zd8d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+d9d.d/Z,d:d1d2Z-d3d4 Z.d;d6d7Z/dS )<    )	xmlWriter)Tagbyteordtostr)deprecateArgument)
TTLibError)
SFNTReader
SFNTWriter)BytesIOStringIONc                   @   sd  e Zd ZdZdddddddeddddddfdd	Zd
d Zdd Zdd ZdQddZ	dRddZ
dSddZdTddZdUddZdVddZdd Zd d! ZeZd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- ZdWd.d/Zd0d1 Zd2d3 Zd4d5 Zed6d7 Zd8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dXdDdEZ$dFdG Z%dYdHdIZ&dJdK Z'dZdLdMZ(d[dOdP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::

		>> 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   sd  dD ].}t  |}|d ur&t|d t| || q|| _|| _|
| _i | _d | _|	| _	|sr|| _
|| _d | _d S t|dsd}|d urddlm} |dkr||r||d}qt|d}q|||}qt|d}nd	}|d | js,|d t| }t|d
r|j|_|r(|  |}|| _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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   r(   r   valZcloseStreamr   tmp r.   f/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/fontTools/ttLib/ttFont.py__init__X   sR    






zTTFont.__init__c                 C   s   | S Nr.   r)   r.   r.   r/   	__enter__   s    zTTFont.__enter__c                 C   s   |    d S r1   )r'   )r)   typevalue	tracebackr.   r.   r/   __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'   r2   r.   r.   r/   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   r*   r   r   r
   _savelistkeysflushreorderFontTablesr'   r%   r8   getvalue)r)   r*   ZreorderTablesZcreateStreamr-   Zwriter_reordersTables
tableOrderZtmp2r.   r.   r/   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   r;   r<   removelenr	   r    r!   r"   _writeTabler'   ZreordersTables)r)   r*   
tableCachetags	numTableswriterdonetagr.   r.   r/   r:      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'   )r)   
fileOrPathrO   kwargsrJ   r.   r.   r/   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   rC   r   )version.   ttFontr   r   )r    ttLibVersion)r    z.%srN   )rZ   )srcsplitGlyphs)r   disassembleInstructionsbitmapGlyphDataFormatr;   r<   rD   rE   	fontToolsrV   joinsplitbegintagreprr   r    newlineospathsplitextfilenamerangetagToIdentifierr   rP   rO   	simpletagtagToXMLbasename_tableToXMLendtagr'   )r)   rJ   ZwriteVersionr   r   Z
skipTablesZsplitTablesr]   r^   r_   rL   rI   rV   rg   extZfileNameTemplateiZ	tablePathZtableWriterr.   r.   r/   rQ      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   DefaultTableTrU   glyfr\   )r   loginform   dictr#   tables.DefaultTableru   	__class__rc   re   toXMLrp   )
r)   rJ   rL   r   r]   tablereportZxmlTagattrsru   r.   r.   r/   ro   ,  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   	XMLReaderr   )r)   rR   r   r   r   r.   r.   r/   	importXMLH  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   r)   rL   r.   r.   r/   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.TrC   FN)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 rL|d t|}dg| S )zSReturns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table.rC   )r;   r   r<   r   appendrD   sortedTagList)r)   r<   keyr.   r.   r/   r<   p  s    
zTTFont.keysc                 C   s   t t|  S r1   )rE   r;   r<   r2   r.   r.   r/   __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 )NrC   '%s' table not found)r   r   r   rC   r   
_readTableKeyErrorr)   rL   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 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   rt   )r*   )rw   debugr   r(   r   getTableClassr   Z	decompile	Exceptionr   	exceptionrz   ru   r   r6   	print_excr?   rs   )r)   rL   datar}   
tableClassru   r*   r.   r.   r/   r     s8    





zTTFont._readTablec                 C   s   || j t|< d S r1   )r   r   r   r.   r.   r/   __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   r.   r.   r/   __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   )r)   rL   defaultr.   r.   r/   r     s    
z
TTFont.getc                 C   s   || _ t| dr| `dS )zTSet the glyph order

		Args:
			glyphOrder ([str]): List of glyph names in order.
		_reverseGlyphOrderDictN)
glyphOrderr#   r   )r)   r   r.   r.   r/   setGlyphOrder  s    
zTTFont.setGlyphOrderc                 C   st   z| j W S  ty   Y n0 d| v r8| d }| | _ n6d| v rf| d  }|du r^|   qn|| _ n|   | j S )zDReturns a list of glyph names ordered by their position in the font.CFF r   N)r   AttributeErrorr   _getGlyphNamesFromCmap)r)   cffr   r.   r.   r/   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   int	numGlyphsrj   r   ZbuildReversed_makeGlyphNameminr   )
r)   ZcmapLoadingr   r   rr   ZreversecmapZuseCountZtempName	glyphNameZnumUsesr.   r.   r/   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)r`   r   ZUV2AGL)	codepointr   r.   r.   r/   r   $  s    

zTTFont._makeGlyphNamec                 C   s   t |  }|S )z1Get a list of glyph names, sorted alphabetically.)sortedr   )r)   Z
glyphNamesr.   r.   r/   getGlyphNames.  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   )r)   r   r.   r.   r/   getGlyphNames23  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)r)   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.   ).0gidZcntr   r.   r/   
<listcomp>I  s   z+TTFont.getGlyphNameMany.<locals>.<listcomp>)r   rE   r)   lstr.   r   r/   getGlyphNameManyE  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   glyph)getReverseGlyphMapr   r   	NameError
ValueErrorr)   r   r.   r.   r/   
getGlyphIDL  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 r.   r.   r   r   )dr.   r/   r   [      z)TTFont.getGlyphIDMany.<locals>.<listcomp>c                    s   g | ]} |qS r.   r.   r   )r   r.   r/   r   ^  r   N)r   r   r   r   r.   )r   r   r/   getGlyphIDManyW  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   )r)   Zrebuildr.   r.   r/   r   `  s    zTTFont.getReverseGlyphMapc                 C   s,   i  | _ }t|  D ]\}}|||< q|S r1   )r   	enumerater   )r)   r   r   r   r.   r.   r/   r   f  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   dependenciesrF   r   getTableDatar   r   rw   r   ZsetEntry)	r)   rL   rJ   rK   rG   r   ZmasterTableZ	tabledataentryr.   r.   r/   rF   l  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   rw   r   r   compiler   r   r   r.   r.   r/   r     s    

zTTFont.getTableDatac                    s   d}|rt  fdddD s<d vrlt  fdddD rld v rHdnd}t t | j d	 jt}|du rd v rt  d t}|du rtd
|S )aS  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.
		Nc                 3   s   | ]}| v V  qd S r1   r.   r   tbr2   r.   r/   	<genexpr>  r   z%TTFont.getGlyphSet.<locals>.<genexpr>)r   CFF2rv   c                 3   s   | ]}| v V  qd S r1   r.   r   r2   r.   r/   r     r   r   r   r   zFont contains no outlines)	any_TTGlyphSetr;   r   valuesZCharStrings_TTGlyphCFF_TTGlyphGlyfr   )r)   Z	preferCFFglyphsZ	table_tagr.   r2   r/   getGlyphSet  s    zTTFont.getGlyphSet)   
   )r      )r      )r   r   )r   r   )r   rX   )r   r   )r   r   c                 C   s   | d j |dS )ab  Return 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::

			(3, 10),
			(0, 6),
			(0, 4),
			(3, 1),
			(0, 3),
			(0, 2),
			(0, 1),
			(0, 0)

		This can be customized via the ``cmapPreferences`` argument.
		r   )cmapPreferences)getBestCmap)r)   r   r.   r.   r/   r     s    zTTFont.getBestCmap)T)N)rM   )TNNNFFTrU   )NF)N)N)F)N)T)r   )*__name__
__module____qualname____doc__NotImplementedr0   r3   r7   r'   rA   r:   rT   rQ   ro   r   r   r   __contains__r<   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   rF   r   r   r   r.   r.   r.   r/   r      s^   I
<
/

    
<



D
		


r   c                   @   sF   e Zd ZdZdd Zdd Zdd ZeZdd	 Zd
d Z	dddZ
dS )r   zfGeneric dict-like GlyphSet class that pulls metrics from hmtx and
	glyph shape from TrueType or CFF.
	c                 C   s0   || _ |d | _d|v r |d nd| _|| _dS )zConstruct a new glyphset.

		Args:
			font (TTFont): The font object (used to get metrics).
			glyphs (dict): A dictionary mapping glyph names to ``_TTGlyph`` objects.
			glyphType (class): Either ``_TTGlyphCFF`` or ``_TTGlyphGlyf``.
		hmtxZvmtxN)_glyphs_hmtx_vmtx
_glyphType)r)   rY   r   Z	glyphTyper.   r.   r/   r0     s    
z_TTGlyphSet.__init__c                 C   s   t | j S r1   )r;   r   r<   r2   r.   r.   r/   r<     s    z_TTGlyphSet.keysc                 C   s
   || j v S r1   )r   r   r.   r.   r/   r     s    z_TTGlyphSet.has_keyc                 C   s4   | j | }| jr| j| nd }| | | j| ||S r1   )r   r   r   r   )r)   r   horizontalMetricsverticalMetricsr.   r.   r/   r     s
    
z_TTGlyphSet.__getitem__c                 C   s
   t | jS r1   )rE   r   r2   r.   r.   r/   r     s    z_TTGlyphSet.__len__Nc                 C   s&   z
| | W S  t y    | Y S 0 d S r1   r   )r)   r   r   r.   r.   r/   r     s    
z_TTGlyphSet.get)N)r   r   r   r   r0   r<   r   r   r   r   r   r.   r.   r.   r/   r     s   r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
_TTGlyphaQ  Wrapper for a TrueType glyph that supports the Pen protocol, meaning
	that it has .draw() and .drawPoints() methods that take a pen object as
	their only argument. Additionally there are 'width' and 'lsb' attributes,
	read from the 'hmtx' table.

	If the font contains a 'vmtx' table, there will also be 'height' and 'tsb'
	attributes.
	Nc                 C   s:   || _ || _|\| _| _|r*|\| _| _nd\| _| _dS )zConstruct a new _TTGlyph.

		Args:
			glyphset (_TTGlyphSet): A glyphset object used to resolve components.
			glyph (ttLib.tables._g_l_y_f.Glyph): The glyph object.
			horizontalMetrics (int, int): The glyph's width and left sidebearing.
		)NNN)	_glyphset_glyphwidthlsbheightZtsb)r)   Zglyphsetr   r   r   r.   r.   r/   r0     s    z_TTGlyph.__init__c                 C   s   | j | dS )zXDraw the glyph onto ``pen``. See fontTools.pens.basePen for details
		how that works.
		N)r   drawr)   penr.   r.   r/   r     s    z_TTGlyph.drawc                 C   s
   t  d S r1   )NotImplementedErrorr   r.   r.   r/   
drawPoints  s    z_TTGlyph.drawPoints)N)r   r   r   r   r0   r   r   r.   r.   r.   r/   r     s   	
r   c                   @   s   e Zd ZdS )r   N)r   r   r   r.   r.   r.   r/   r     s   r   c                   @   s   e Zd Zdd Zdd ZdS )r   c                 C   s:   | j j}| j}t|dr$| j|j nd}|||| dS )zTDraw the glyph onto Pen. See fontTools.pens.basePen for details
		how that works.
		xMinr   N)r   r   r   r#   r   r   r   r)   r   Z	glyfTabler   offsetr.   r.   r/   r     s    z_TTGlyphGlyf.drawc                 C   s:   | j j}| j}t|dr$| j|j nd}|||| dS )zZDraw the glyph onto PointPen. See fontTools.pens.pointPen
		for details how that works.
		r   r   N)r   r   r   r#   r   r   r   r   r.   r.   r/   r   $  s    z_TTGlyphGlyf.drawPointsN)r   r   r   r   r   r.   r.   r.   r/   r     s   	r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
rC   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 r1   r.   r   r.   r.   r/   r0   4  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   commentre   rj   rE   rl   )r)   rJ   rY   r   rr   r   r.   r.   r/   r|   7  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   )r)   r   r   contentrY   r.   r.   r/   fromXMLA  s
    
zGlyphOrder.fromXML)N)r   r   r   r   r0   r|   r  r.   r.   r.   r/   rC   .  s   

rC   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   rk   
__import__ImportErrorstrfindgetattr)rL   r   pyTagerrr.   r.   r/   getTableModuleI  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_)rk   _customTableRegistry)rL   
moduleName	classNamer.   r.   r/   registerCustomTableClassd  s    
r  c                 C   s
   t | = dS )z8Unregister the custom packer/unpacker class for a table.N)r  rL   r.   r.   r/   unregisterCustomTableClasss  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  )rL   r  r  r  moduler.   r.   r/   getCustomTableClassx  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   rt   r
  )r  r	  rz   ru   rk   r  )rL   r   r  ru   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    r  c                 C   s   t | }|| S )z!Return a new instance of a table.)r   )rL   r   r.   r.   r/   newTable  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]rX   )rematchhexr   )cr  r.   r.   r/   _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   NrC   r   ztag should be 4 characters longr   r    r$   z[0-9]r  )r  r   rE   r  r  )rL   r  identr  r.   r.   r/   rk     s    rk   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()rC   rX   r   r  r   Nr$      r   r  )rE   rj   chrr   r   )r   rL   rr   r.   r.   r/   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_2rC   z[A-Za-z_][A-Za-z_0-9]* *$)r  r   r  striprk   )rL   r  r.   r.   r/   rm     s    rm   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   rE   r  r  r.   r.   r/   xmlToTag  s
    r'  )rB   hhear   r#  r   ZLTSHZVDMXZhdmxr   Zfpgmprepzcvt Zlocarv   kernr   r   ZgaspZPCLT)rB   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   rD   r   OTFTableOrderTTFTableOrderextend)ZtagListr@   ZorderedTablesrL   r.   r.   r/   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   )r+   N)r&   r   r	   rE   r   r    r!   r"   r;   r<   r   r'   )ZinFileZoutFiler@   r+   r   rJ   r   rL   r.   r.   r/   r>     s    

r>   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exponentr.   r.   r/   maxPowerOfTwo*  s
    
r1  r!  c                 C   s4   t | }d| | }|}td| | | }|||fS )z3Calculate searchRange, entrySelector, rangeShift.
	rX   r   )r1  r.  )nZitemSizer0  ZsearchRangeZentrySelectorZ
rangeShiftr.   r.   r/   getSearchRange5  s
    r3  )N)N)NF)r!  )0r   r   ZfontTools.misc.textToolsr   r   r   ZfontTools.misc.loggingToolsr   ZfontTools.ttLibr   ZfontTools.ttLib.sfntr   r	   ior
   r   rf   loggingr6   	getLoggerr   rw   objectr   r   r   r   r   rC   r	  r  r  r  r  r   r  r  r  rk   r  rm   r'  r,  r+  r   r>   r1  r3  r.   r.   r.   r/   <module>   sN   
     ?*%
 

