o
    h                    @   s  d dl mZmZ d dlZd dlZd dlmZ d dl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 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Zd dlZe e!Z"dd Z#dZ$dZ%dZ&dZ'dZ(dddZ)G dd de*Z+G dd de+Z,G dd dedg dZ-G dd dZ.G dd  d e+Z/G d!d" d"e/Z0G d#d$ d$e/Z1G d%d& d&e+Z2G d'd( d(e+Z3G d)d* d*e+Z4G d+d, d,e+Z5G d-d. d.e+Z6G d/d0 d0e+Z7G d1d2 d2e+Z8G d3d4 d4e+Z9G d5d6 d6e*Z:G d7d8 d8e+Z;G d9d: d:e+Z<d;d< Z=d=d> Z>d?d@ Z?dAdB Z@ddCdDZAdEdF ZBdGdH ZCdIdJ ZDdKdL ZEdMdN ZFdOdP ZGdQdR ZHdSdT ZIdUdV ZJdWdX ZKdYdZ ZLd[d\ ZMd]d^ ZNd_d` ZOdadb ZPddcddZQdedf ZRddgdhZSdidj ZTdkdl ZUdmdn ZVdodp ZWedqdrZXdsdt ZYdudv ZZdwdx Z[dydz Z\d{d| Z]d}d~ Z^dd Z_dd Z`dd Zadd ZbG dd de*ZceddZdeddZe	dddZfdddZgdddZhdddZi						 				dddZjdd Zkdd Zldd Zmdd Zndd ZodS )    )
namedtupleOrderedDictN)fixedToFloat)otRound)ttLib)otTables)ValueRecordvalueRecordFormatDictOTLOffsetOverflowErrorOTTableWriterCountReference)otBase)STATNameStatement)_compression_level_from_envcompact_lookup)OpenTypeLibError)reducec              
   C   sV   | sdS t  }ztt| |jd|_W |S  ty* } z	td| d|d}~ww )a	  Builds a coverage table.

    Coverage tables (as defined in the `OpenType spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-table>`__)
    are used in all OpenType Layout lookups apart from the Extension type, and
    define the glyphs involved in a layout subtable. This allows shaping engines
    to compare the glyph stream with the coverage table and quickly determine
    whether a subtable should be involved in a shaping operation.

    This function takes a list of glyphs and a glyphname-to-ID map, and
    returns a ``Coverage`` object representing the coverage table.

    Example::

        glyphMap = font.getReverseGlyphMap()
        glyphs = [ "A", "B", "C" ]
        coverage = buildCoverage(glyphs, glyphMap)

    Args:
        glyphs: a sequence of glyph names.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        An ``otTables.Coverage`` object or ``None`` if there are no glyphs
        supplied.
    NkeyzCould not find glyph z in font)otCoveragesortedset__getitem__glyphsKeyError
ValueError)r   glyphMapselfe r    l/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fontTools/otlLib/builder.pybuildCoverage   s   r"                  c                    s    du rdS dd  D   sdS t  fdd D s)J dtdd  D  t } d j|_||_ |_t|j|_|durX| jt	O  _t
|tsSJ |||_|S |jt	@ dkseJ d	| |S )
a  Turns a collection of rules into a lookup.

    A Lookup (as defined in the `OpenType Spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookupTbl>`__)
    wraps the individual rules in a layout operation (substitution or
    positioning) in a data structure expressing their overall lookup type -
    for example, single substitution, mark-to-base attachment, and so on -
    as well as the lookup flags and any mark filtering sets. You may import
    the following constants to express lookup flags:

    - ``LOOKUP_FLAG_RIGHT_TO_LEFT``
    - ``LOOKUP_FLAG_IGNORE_BASE_GLYPHS``
    - ``LOOKUP_FLAG_IGNORE_LIGATURES``
    - ``LOOKUP_FLAG_IGNORE_MARKS``
    - ``LOOKUP_FLAG_USE_MARK_FILTERING_SET``

    Args:
        subtables: A list of layout subtable objects (e.g.
            ``MultipleSubst``, ``PairPos``, etc.) or ``None``.
        flags (int): This lookup's flags.
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.

    Returns:
        An ``otTables.Lookup`` object or ``None`` if there are no subtables
        supplied.
    Nc                 S   s   g | ]}|d ur|qS Nr    ).0str    r    r!   
<listcomp>l       zbuildLookup.<locals>.<listcomp>c                 3   s     | ]}|j  d  j kV  qdS r   N
LookupTyper)   t	subtablesr    r!   	<genexpr>o   s    
zbuildLookup.<locals>.<genexpr>z3all subtables must have the same LookupType; got %sc                 S   s   g | ]}|j qS r    r.   r0   r    r    r!   r+   r       r   z]if markFilterSet is None, flags must not set LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x%04x)allreprr   Lookupr/   
LookupFlagSubTablelenSubTableCount"LOOKUP_FLAG_USE_MARK_FILTERING_SET
isinstanceintMarkFilteringSet)r3   flagsmarkFilterSetr   r    r2   r!   buildLookupL   s8   
rC   c                   @   sp   e Zd Z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dd Zdd ZdS )LookupBuilderSUBTABLE_BREAKc                 C   sF   || _ | | _|| _||| _| _d| _d | _d | _|dv s!J d S )Nr   )GPOSGSUB)	fontgetReverseGlyphMapr   locationtablelookup_type
lookupflagrB   lookup_index)r   rH   rJ   rK   rL   r    r    r!   __init__   s   
zLookupBuilder.__init__c                 C   s0   t || jo| j|jko| j|jko| j|jkS r(   )r>   	__class__rK   rM   rB   r   otherr    r    r!   equals   s   


zLookupBuilder.equalsc                 C      i S )z?Infers glyph glasses for the GDEF table, such as {"cedilla":3}.r    r   r    r    r!   inferGlyphClasses      zLookupBuilder.inferGlyphClassesc                 C   rT   )z$Helper for building 'aalt' features.r    rU   r    r    r!   getAlternateGlyphs   rW   z LookupBuilder.getAlternateGlyphsc                 C   s   t || j| jS r(   )rC   rM   rB   r   r3   r    r    r!   buildLookup_      zLookupBuilder.buildLookup_c                 C   sB   i }t | | jjdD ]}|| \}}||vrt|||< q|S )a   {"cedilla": ("BOTTOM", ast.Anchor), ...} --> {"BOTTOM":0, "TOP":1}

        Helper for MarkBasePostBuilder, MarkLigPosBuilder, and
        MarkMarkPosBuilder. Seems to return the same numeric IDs
        for mark classes as the AFDKO makeotf tool.
        r   )r   keysrH   
getGlyphIDr;   )r   marksidsmarkmarkClassName_markAnchorr    r    r!   buildMarkClasses_   s   zLookupBuilder.buildMarkClasses_c                 C   s:   t ||_g |_t|D ]}t|| j}|j| qd S r(   )r;   BacktrackGlyphCountBacktrackCoveragereversedr"   r   append)r   prefixsubtablepcoverager    r    r!   setBacktrackCoverage_   s   
z#LookupBuilder.setBacktrackCoverage_c                 C   6   t ||_g |_|D ]}t|| j}|j| q
d S r(   )r;   LookAheadGlyphCountLookAheadCoverager"   r   rg   )r   suffixri   srk   r    r    r!   setLookAheadCoverage_      
z#LookupBuilder.setLookAheadCoverage_c                 C   rm   r(   )r;   InputGlyphCountInputCoverager"   r   rg   r   r   ri   grk   r    r    r!   setInputCoverage_   rs   zLookupBuilder.setInputCoverage_c                 C   rm   r(   )r;   
GlyphCountr   r"   r   rg   rv   r    r    r!   setCoverage_   rs   zLookupBuilder.setCoverage_c                    sP   i g}|D ]}|d | j kr|i  q|| |d |< q fdd|D }|S )Nr   c                    s   g | ]} |qS r    r    )r)   rq   klassr    r!   r+          z7LookupBuilder.build_subst_subtables.<locals>.<listcomp>)SUBTABLE_BREAK_rg   )r   mappingr}   substitutionsr   r3   r    r|   r!   build_subst_subtables   s   z#LookupBuilder.build_subst_subtablesc                 C   s   t td| dS )zAdd an explicit subtable break.

        Args:
            location: A string or tuple representing the location in the
                original source which produced this break, or ``None`` if
                no location is provided.
        z0unsupported "subtable" statement for lookup typeN)logwarningr   r   rJ   r    r    r!   add_subtable_break   s
   z LookupBuilder.add_subtable_breakN)__name__
__module____qualname__r   rO   rS   rV   rX   rZ   rc   rl   rr   rx   rz   r   r   r    r    r    r!   rD      s    

rD   c                   @   8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )AlternateSubstBuildera  Builds an Alternate Substitution (GSUB3) lookup.

    Users are expected to manually add alternate glyph substitutions to
    the ``alternates`` attribute after the object has been initialized,
    e.g.::

        builder.alternates["A"] = ["A.alt1", "A.alt2"]

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        alternates: An ordered dictionary of alternates, mapping glyph names
            to a list of names of alternates.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C      t | ||dd t | _d S )NrG      )rD   rO   r   
alternatesr   rH   rJ   r    r    r!   rO         zAlternateSubstBuilder.__init__c                 C      t | |o| j|jkS r(   )rD   rS   r   rQ   r    r    r!   rS        zAlternateSubstBuilder.equalsc                 C      |  | jt}| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the alternate
            substitution lookup.
        )r   r   buildAlternateSubstSubtablerZ   rY   r    r    r!   build     
zAlternateSubstBuilder.buildc                 C      | j S r(   )r   rU   r    r    r!   rX     s   z(AlternateSubstBuilder.getAlternateGlyphsc                 C      | j | j| j |f< d S r(   )r   r   r   r    r    r!   r        z(AlternateSubstBuilder.add_subtable_breakN	r   r   r   __doc__rO   rS   r   rX   r   r    r    r    r!   r      s    r   c                   @   s   e Zd Zedd ZdS )ChainContextualRulec                 C   s   | j tjkS r(   )rh   rD   r   rU   r    r    r!   is_subtable_break  s   z%ChainContextualRule.is_subtable_breakN)r   r   r   propertyr   r    r    r    r!   r     s    r   )rh   r   rp   lookupsc                   @   sD   e Zd Zdd Zdd Zedd Zedd Zd	d
 Zdd Z	dS )ChainContextualRulesetc                 C   s
   g | _ d S r(   )rulesrU   r    r    r!   rO   "  s   
zChainContextualRuleset.__init__c                 C   s   | j | d S r(   )r   rg   r   ruler    r    r!   addRule%  r[   zChainContextualRuleset.addRulec                 C   s2   | j D ]}t|jdkst|jdkr dS qdS )Nr   TF)r   r;   rh   rp   r   r    r    r!   hasPrefixOrSuffix(  s
   
z(ChainContextualRuleset.hasPrefixOrSuffixc                 C   s@   | j D ]}|j|j|jfD ]}tdd |D r  dS qqdS )Nc                 s   s    | ]	}t |d kV  qdS )r#   Nr;   r)   xr    r    r!   r4   7      z<ChainContextualRuleset.hasAnyGlyphClasses.<locals>.<genexpr>TF)r   rh   r   rp   any)r   r   rk   r    r    r!   hasAnyGlyphClasses1  s   
z)ChainContextualRuleset.hasAnyGlyphClassesc           	      C   s^   d\}}}g }|||fD ] }g }| j D ]	}|||  q| |}|s' d S || q|S )N)r   r#   r$   )r   rg   _classBuilderForContext)	r   PREFIXGLYPHSSUFFIXclassDefBuildersixcontextrclassesr    r    r!   format2ClassDefs;  s   


z'ChainContextualRuleset.format2ClassDefsc                 C   sF   t dd}|D ]}|D ]}t|}||s  d S || qq|S )NF	useClass0)ClassDefBuilderr   canAddadd)r   r   classdefbuilderpositionglyphsetr   r    r    r!   r   H  s   

z.ChainContextualRuleset._classBuilderForContextN)
r   r   r   rO   r   r   r   r   r   r   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%d
dZd%ddZd%ddZ	dd Z
dd Zd%ddZd&ddZd&ddZd&ddZd&ddZ	 d'd!d"Zd#d$ ZdS )(ChainContextualBuilderc                 C   r   r(   rD   rS   r   rQ   r    r    r!   rS   T  r   zChainContextualBuilder.equalsc                 C   sD   t  g}| jD ]}|jr|t   q|d | qdd |D S )Nr{   c                 S   s   g | ]}t |jd kr|qS r   )r;   r   r   r    r    r!   r+   a      z3ChainContextualBuilder.rulesets.<locals>.<listcomp>)r   r   r   rg   r   )r   rulesetr   r    r    r!   rulesetsW  s   
zChainContextualBuilder.rulesetsc                 C   s<   |sdS |  t|}t }||| j t| }|S Nr   )rZ   copydeepcopyr   compilerH   r;   
getAllData)r   r3   rK   wsizer    r    r!   getCompiledSize_c  s   z'ChainContextualBuilder.getCompiledSize_c                 C   s`  g }|   }tdd |D }| jjd}|s| jdkrd}|D ]}dddg g}|jD ]}|d | || q,|	 }|rJ| 
|||g|d< |jsV| ||g|d	< g }	d
D ]8}
||
 rz	| ||
 }W n ty } ztd|
t| j|f  W Y d}~qZd}~ww |	|||
 f qZ|	std| jt|	dd d\}}|| q!| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the chained
            contextual positioning lookup.
        c                 s   s    | ]}|j V  qd S r(   )r   )r)   r   r    r    r!   r4   x  s    z/ChainContextualBuilder.build.<locals>.<genexpr>z$fontTools.otlLib.builder:WRITE_GPOS7PosTNr   r$   r#   )r#   r$   r   z*Contextual format %i at %s overflowed (%s)zAll candidates overflowedc                 S   s   | d S r   r    r   r    r    r!   <lambda>  s    z.ChainContextualBuilder.build.<locals>.<lambda>r   )r   r   rH   cfggetsubtable_typer   rg   buildFormat3Subtabler   buildFormat2Subtabler   buildFormat1Subtabler   r
   r   r   strrJ   r   minextendrZ   )r   r3   r   chainingwrite_gpos7r   
candidatesr   	classdefscandidates_by_sizeir   r   	_min_sizewinnerr    r    r!   r   n  sH   

zChainContextualBuilder.buildTc                 C   s  | j |d}d|_|  t }i }| jd|d}|jD ]h}| jd|d}|rNt|j|_	t|j
|_dd t|jD |_dd |j
D |_t|j|_nt|j|_dd |jdd  D |_| || t|jd d }	|	|vr}||	 g ||	< ||	 | qt|| j|_g }
|jjD ]#}| jd|d}t||||  t|| d	t||  |
| qt|| jd|d|
 t|| jd|dd	 t|
 |S )
Nr   r#   formatr   c                 S      g | ]}t |d  qS r   listr   r    r    r!   r+     r,   z?ChainContextualBuilder.buildFormat1Subtable.<locals>.<listcomp>c                 S   r   r   r   r   r    r    r!   r+     r,   c                 S   r   r   r   r   r    r    r!   r+     r,   r   Count)newSubtable_FormatpopulateDefaultsr   	ruleAttr_r   newRule_r;   rh   rd   rp   rn   rf   	Backtrack	LookAheadr   rt   ry   InputbuildLookupListr   r   rg   r"   r   r   newRuleSet_setattrruleSetAttr_)r   r   r   r*   rk   rulesetsByFirstGlyphruleAttrr   ruleAsSubtable
firstGlyphruleSetsrw   ruleSetr    r    r!   r     sD   

z+ChainContextualBuilder.buildFormat1Subtablec                    s@  | j |d d _   |rdd |D \ _ _ _n|d   _|d  }g }|D ]}| j	d|d}|
| q.t }| jd|d}	|jD ]}
| jd|d}|rt|
j|_t|
j|_ fddt|
jD |_ fdd|
jD |_t|
j|_ fd	d|
jdd  D |_| jjt|
jd
 d
   }n$t|
j|_ fdd|
jdd  D |_| jjt|
jd
 d
   }| |
| |t|
jd
 O }t||	
| t ||	 dt||	 dd  qJt!|D ]\}}t||	sd ||< qt  | j"d|d| t  | j"d|dd t| t#|| j$ _% S )Nr   r$   c                 S      g | ]}|  qS r    )r   r)   cr    r    r!   r+     r~   z?ChainContextualBuilder.buildFormat2Subtable.<locals>.<listcomp>r#   r   c                        g | ]} j jt|d   qS r   )BacktrackClassDef	classDefsr   r   r*   r    r!   r+     s    c                    r   r   )LookAheadClassDefr   r   r   r   r    r!   r+         c                    r   r   )InputClassDefr   r   r   r   r    r!   r+     r  r   c                    r   r   )ClassDefr   r   r   r   r    r!   r+     r  r   )&r   r   r   r   r  r   r   r  r   r   rg   r   r   r   r   r;   rh   rd   rp   rn   rf   r   r   r   rt   r   r   r   ry   Classr   getattrr   	enumerater   r"   r   r   )r   r   r   r   	inClasses	classSets_classSetrk   classRuleAttrr   r   setForThisRuler   r    r   r!   r     sx   





z+ChainContextualBuilder.buildFormat2Subtablec                 C   s`   | j |d}d|_|r!| |j| | |j| | |j| n| |j| | 	|| |S )Nr   r   )
r   r   rl   rh   rr   rp   rx   r   rz   r   )r   r   r   r*   r    r    r!   r   /  s   z+ChainContextualBuilder.buildFormat3Subtablec                 C   s   t |jD ]:\}}|d ur?t|ts|g}|D ]'}|jd u r2t| tr&d}nd}td| d| j| |}||_	|j|_
qqd S )Nsubstitutionpositioningz2Missing index of the specified lookup, might be a z lookup)r  r   r>   r   rN   ChainContextPosBuilderr   rJ   newLookupRecord_SequenceIndexLookupListIndex)r   r   r*   sequenceIndex
lookupListlrR   recr    r    r!   r   ;  s(   




z&ChainContextualBuilder.buildLookupListc                 C   s$   | j t| j| j| j| jg d S r(   )r   rg   r   r   r   r    r    r!   r   P  s   z)ChainContextualBuilder.add_subtable_breakc                 C   sP   d| j  }|rd| }tt| }t|| j  dd t|| j  dg  |S )NContextChainr   r   LookupRecord)r   r  r   r   )r   r   subtablenamer*   r    r    r!   r   Z  s   z#ChainContextualBuilder.newSubtable_r#   c                 C   L   |dkrd}n|dkrd}nt || jdd  | d}|r$d| }|S )	Nr#   Ruler$   r  r   r   Setr  AssertionErrorr   r   r   r   
formatTyper  r    r    r!   r   m     z#ChainContextualBuilder.ruleSetAttr_c                 C   r  )	Nr#    r$   r  r   r   r  r  r  r   r    r    r!   r   y  r"  z ChainContextualBuilder.ruleAttr_c                 C       t t| || }|  |S r(   )r  r   r   r   r   r   r   r*   r    r    r!   r     
   z"ChainContextualBuilder.newRuleSet_c                 C   r$  r(   )r  r   r   r   r%  r    r    r!   r     r&  zChainContextualBuilder.newRule_NFc                 C   s   |r
d| }d| }t ||st||d t||g  |r |}ntt| }t||t||d  |r>t|||| |S t||| |S )Nr  r   r#   )hasattrr   r  r   insertrg   )r   r*   subtable_name
count_nameexistingindexr   new_subtabler    r    r!   attachSubtableWithCount_  s   
z/ChainContextualBuilder.attachSubtableWithCount_c                 C   s"   | j || j d| j dddS )Nr  r   Fr   )r.  r   r   r*   r    r    r!   r    s   

z'ChainContextualBuilder.newLookupRecord_)T)r#   T)NNF)r   r   r   rS   r   r   r   r   r   r   r   r   r   r   r   r   r   r.  r  r    r    r    r!   r   S  s$    
G
.
L






r   c                   @   s    e Zd ZdZdd Zdd ZdS )r  a>  Builds a Chained Contextual Positioning (GPOS8) lookup.

    Users are expected to manually add rules to the ``rules`` attribute after
    the object has been initialized, e.g.::

        # pos [A B] [C D] x' lookup lu1 y' z' lookup lu2 E;

        prefix  = [ ["A", "B"], ["C", "D"] ]
        suffix  = [ ["E"] ]
        glyphs  = [ ["x"], ["y"], ["z"] ]
        lookups = [ [lu1], None,  [lu2] ]
        builder.rules.append( (prefix, glyphs, suffix, lookups) )

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        rules: A list of tuples representing the rules in this lookup.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   "   t | ||dd g | _d| _d S )NrF   r&   r   rD   rO   r   r   r   r    r    r!   rO        
zChainContextPosBuilder.__init__c                    sT   d}|ddd D ]  | j kr|  S t tr't fdd|D r' }q	|S )z$Helper for add_single_pos_chained_()Nr{   c                 3   s    | ]	}  |V  qd S r(   )can_addr)   glyphlookupvaluer    r!   r4     s    
zCChainContextPosBuilder.find_chainable_single_pos.<locals>.<genexpr>)r   r>   SinglePosBuilderr6   )r   r   r   r8  resr    r6  r!   find_chainable_single_pos  s   
z0ChainContextPosBuilder.find_chainable_single_posN)r   r   r   r   rO   r;  r    r    r    r!   r    s    r  c                   @   0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )ChainContextSubstBuildera?  Builds a Chained Contextual Substitution (GSUB6) lookup.

    Users are expected to manually add rules to the ``rules`` attribute after
    the object has been initialized, e.g.::

        # sub [A B] [C D] x' lookup lu1 y' z' lookup lu2 E;

        prefix  = [ ["A", "B"], ["C", "D"] ]
        suffix  = [ ["E"] ]
        glyphs  = [ ["x"], ["y"], ["z"] ]
        lookups = [ [lu1], None,  [lu2] ]
        builder.rules.append( (prefix, glyphs, suffix, lookups) )

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        rules: A list of tuples representing the rules in this lookup.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   r0  )NrG      Substr1  r   r    r    r!   rO     r2  z!ChainContextSubstBuilder.__init__c              	      s   i }| j D ]<}|jrq|jD ]2}t|ts|g}|D ]%}|d ur?| }| D ]\}}||g    fdd|D  q(qqq|S )Nc                 3   s    | ]	}| vr|V  qd S r(   r    r)   rw   alts_for_glyphr    r!   r4     s    z>ChainContextSubstBuilder.getAlternateGlyphs.<locals>.<genexpr>)	r   r   r   r>   r   rX   items
setdefaultr   )r   resultr   r   r7  altsr5  replacementsr    rA  r!   rX     s&   



z+ChainContextSubstBuilder.getAlternateGlyphsc                    s`   d}| j ddd D ]#}|jr|  S |jD ]t|r,t fddjD s,}qq
|S )z.Helper for add_{single,multi}_subst_chained_()Nr{   c                 3   s*    | ]}| v o | j | kV  qd S r(   r   r@  r   subr    r!   r4     s    
z@ChainContextSubstBuilder.find_chainable_subst.<locals>.<genexpr>)r   r   r   r>   r   r   )r   r   builder_classr:  r   r    rI  r!   find_chainable_subst  s   
z-ChainContextSubstBuilder.find_chainable_substc                    sf   d}| j ddd D ]&}|jr|  S |jD ]ttsqt fddtj| D r/}qq
|S )z(Helper for add_ligature_subst_chained_()Nr{   c                 3   s"    | ]}j |  kV  qd S r(   )	ligaturesr   )r)   seqreplacementrJ  r    r!   r4   +  s
    
zIChainContextSubstBuilder.find_chainable_ligature_subst.<locals>.<genexpr>)r   r   r   r>   LigatureSubstBuilderr6   	itertoolsproduct)r   r   rP  r:  r   r    rO  r!   find_chainable_ligature_subst"  s   

z6ChainContextSubstBuilder.find_chainable_ligature_substN)r   r   r   r   rO   rX   rL  rT  r    r    r    r!   r=    s    r=  c                   @   r<  )rQ  a  Builds a Ligature Substitution (GSUB4) lookup.

    Users are expected to manually add ligatures to the ``ligatures``
    attribute after the object has been initialized, e.g.::

        # sub f i by f_i;
        builder.ligatures[("f","f","i")] = "f_f_i"

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        ligatures: An ordered dictionary mapping a tuple of glyph names to the
            ligature glyphname.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   r   )NrG   r%   )rD   rO   r   rM  r   r    r    r!   rO   J  r   zLigatureSubstBuilder.__init__c                 C   r   r(   )rD   rS   rM  rQ   r    r    r!   rS   N  r   zLigatureSubstBuilder.equalsc                 C   r   )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the ligature
            substitution lookup.
        )r   rM  buildLigatureSubstSubtablerZ   rY   r    r    r!   r   Q  r   zLigatureSubstBuilder.buildc                 C   r   r(   )r   rM  r   r    r    r!   r   ]  r   z'LigatureSubstBuilder.add_subtable_breakNr   r   r   r   rO   rS   r   r   r    r    r    r!   rQ  3  s    rQ  c                   @   r<  )MultipleSubstBuildera  Builds a Multiple Substitution (GSUB2) lookup.

    Users are expected to manually add substitutions to the ``mapping``
    attribute after the object has been initialized, e.g.::

        # sub uni06C0 by uni06D5.fina hamza.above;
        builder.mapping["uni06C0"] = [ "uni06D5.fina", "hamza.above"]

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        mapping: An ordered dictionary mapping a glyph name to a list of
            substituted glyph names.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   r   )NrG   r$   rD   rO   r   r   r   r    r    r!   rO   x  r   zMultipleSubstBuilder.__init__c                 C   r   r(   rD   rS   r   rQ   r    r    r!   rS   |  r   zMultipleSubstBuilder.equalsc                 C   r   r(   )r   r   buildMultipleSubstSubtablerZ   rY   r    r    r!   r     s   
zMultipleSubstBuilder.buildc                 C   r   r(   r   r   r   r    r    r!   r     r   z'MultipleSubstBuilder.add_subtable_breakNrV  r    r    r    r!   rW  a  s    rW  c                   @   r<  )CursivePosBuildera  Builds a Cursive Positioning (GPOS3) lookup.

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        attachments: An ordered dictionary mapping a glyph name to a two-element
            tuple of ``otTables.Anchor`` objects.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   s   t | ||dd i | _d S )NrF   r   )rD   rO   attachmentsr   r    r    r!   rO        
zCursivePosBuilder.__init__c                 C   r   r(   )rD   rS   r]  rQ   r    r    r!   rS     s   zCursivePosBuilder.equalsc                 C   s   |D ]	}||f| j |< qdS )ak  Adds attachment information to the cursive positioning lookup.

        Args:
            location: A string or tuple representing the location in the
                original source which produced this lookup. (Unused.)
            glyphs: A list of glyph names sharing these entry and exit
                anchor locations.
            entryAnchor: A ``otTables.Anchor`` object representing the
                entry anchor, or ``None`` if no entry anchor is present.
            exitAnchor: A ``otTables.Anchor`` object representing the
                exit anchor, or ``None`` if no exit anchor is present.
        N)r]  )r   rJ   r   entryAnchor
exitAnchorr5  r    r    r!   add_attachment  s   z CursivePosBuilder.add_attachmentc                 C   s   t | j| j}| |gS )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the cursive
            positioning lookup.
        )buildCursivePosSubtabler]  r   rZ   r/  r    r    r!   r     s   zCursivePosBuilder.buildN)r   r   r   r   rO   rS   ra  r   r    r    r    r!   r\    s    r\  c                   @   r<  )MarkBasePosBuildera  Builds a Mark-To-Base Positioning (GPOS4) lookup.

    Users are expected to manually add marks and bases to the ``marks``
    and ``bases`` attributes after the object has been initialized, e.g.::

        builder.marks["acute"]   = (0, a1)
        builder.marks["grave"]   = (0, a1)
        builder.marks["cedilla"] = (1, a2)
        builder.bases["a"] = {0: a3, 1: a5}
        builder.bases["b"] = {0: a4, 1: a5}

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        marks: An dictionary mapping a glyph name to a two-element
            tuple containing a mark class ID and ``otTables.Anchor`` object.
        bases: An dictionary mapping a glyph name to a dictionary of
            mark class IDs and ``otTables.Anchor`` object.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   "   t | ||dd i | _i | _d S )NrF   r%   )rD   rO   r^   basesr   r    r    r!   rO     r2  zMarkBasePosBuilder.__init__c                 C   $   t | |o| j|jko| j|jkS r(   )rD   rS   r^   re  rQ   r    r    r!   rS     
   

zMarkBasePosBuilder.equalsc                 C   *   dd | j D }|dd | jD  |S )Nc                 S      i | ]}|d qS )r#   r    r4  r    r    r!   
<dictcomp>  r5   z8MarkBasePosBuilder.inferGlyphClasses.<locals>.<dictcomp>c                 S   ri  r   r    r4  r    r    r!   rj    r5   )re  updater^   r   rE  r    r    r!   rV        z$MarkBasePosBuilder.inferGlyphClassesc           
      C   s   |  | j}i }| j D ]\}\}}||vrtd||f || |f||< qi }| j D ]%\}}i ||< | D ]\}}||vrKtd||f ||| || < q;q/t||| j}	| |	S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the mark-to-base
            positioning lookup.
        z)Mark class %s not found for mark glyph %sz)Mark class %s not found for base glyph %s)rc   r^   rC  r   re  buildMarkBasePosr   rZ   )
r   markClassesr^   r`   mcanchorre  r5  anchorsr3   r    r    r!   r     s(   


zMarkBasePosBuilder.buildNr   r   r   r   rO   rS   rV   r   r    r    r    r!   rc    s    rc  c                   @   r<  )MarkLigPosBuilderac  Builds a Mark-To-Ligature Positioning (GPOS5) lookup.

    Users are expected to manually add marks and bases to the ``marks``
    and ``ligatures`` attributes after the object has been initialized, e.g.::

        builder.marks["acute"]   = (0, a1)
        builder.marks["grave"]   = (0, a1)
        builder.marks["cedilla"] = (1, a2)
        builder.ligatures["f_i"] = [
            { 0: a3, 1: a5 }, # f
            { 0: a4, 1: a5 }  # i
        ]

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        marks: An dictionary mapping a glyph name to a two-element
            tuple containing a mark class ID and ``otTables.Anchor`` object.
        ligatures: An dictionary mapping a glyph name to an array with one
            element for each ligature component. Each array element should be
            a dictionary mapping mark class IDs to ``otTables.Anchor`` objects.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   rd  )NrF      )rD   rO   r^   rM  r   r    r    r!   rO   $  r2  zMarkLigPosBuilder.__init__c                 C   rf  r(   )rD   rS   r^   rM  rQ   r    r    r!   rS   )  rg  zMarkLigPosBuilder.equalsc                 C   rh  )Nc                 S   ri  )r$   r    r4  r    r    r!   rj  1  r5   z7MarkLigPosBuilder.inferGlyphClasses.<locals>.<dictcomp>c                 S   ri  rk  r    r4  r    r    r!   rj  2  r5   )rM  rl  r^   rm  r    r    r!   rV   0  rn  z#MarkLigPosBuilder.inferGlyphClassesc                    s   |  | j  fdd| j D }i }| j D ]\}}g ||< |D ]}||  fdd| D  q#qt||| j}| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the mark-to-ligature
            positioning lookup.
        c                    "   i | ]\}\}}| | |fqS r    r    r)   r`   rq  rr  rp  r    r!   rj  =      z+MarkLigPosBuilder.build.<locals>.<dictcomp>c                    s   i | ]	\}} | |qS r    r    )r)   rq  ary  r    r!   rj  D  s    )rc   r^   rC  rM  rg   buildMarkLigPosr   rZ   )r   r^   ligslig
componentsr   r3   r    ry  r!   r   5  s   
"
zMarkLigPosBuilder.buildNrt  r    r    r    r!   ru    s    ru  c                   @   r<  )MarkMarkPosBuildera  Builds a Mark-To-Mark Positioning (GPOS6) lookup.

    Users are expected to manually add marks and bases to the ``marks``
    and ``baseMarks`` attributes after the object has been initialized, e.g.::

        builder.marks["acute"]     = (0, a1)
        builder.marks["grave"]     = (0, a1)
        builder.marks["cedilla"]   = (1, a2)
        builder.baseMarks["acute"] = {0: a3}

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        marks: An dictionary mapping a glyph name to a two-element
            tuple containing a mark class ID and ``otTables.Anchor`` object.
        baseMarks: An dictionary mapping a glyph name to a dictionary
            containing one item: a mark class ID and a ``otTables.Anchor`` object.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   rd  )NrF   r>  )rD   rO   r^   	baseMarksr   r    r    r!   rO   d  r2  zMarkMarkPosBuilder.__init__c                 C   rf  r(   )rD   rS   r^   r  rQ   r    r    r!   rS   i  rg  zMarkMarkPosBuilder.equalsc                 C   rh  )Nc                 S   ri  rk  r    r4  r    r    r!   rj  q  r5   z8MarkMarkPosBuilder.inferGlyphClasses.<locals>.<dictcomp>c                 S   ri  rk  r    r4  r    r    r!   rj  r  r5   )r  rl  r^   rm  r    r    r!   rV   p  rn  z$MarkMarkPosBuilder.inferGlyphClassesc                    s    jt jd}fddj D }t }d|_t	|_
t|j|_tjj|_t|j|_t |_t	|jj|j_g |j_|jjD ]  fdd|D }|jjt| qR|gS )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the mark-to-mark
            positioning lookup.
        r   c                    rw  r    r    rx  ry  r    r!   rj  ~  rz  z,MarkMarkPosBuilder.build.<locals>.<dictcomp>r#   c                    s   g | ]
}j   |qS r    )r  r   r)   rq  )baser   r    r!   r+     s    z,MarkMarkPosBuilder.build.<locals>.<listcomp>)rc   r^   r   r\   r   rC  r   MarkMarkPosr   r;   
ClassCountr"   r   Mark1Coverager  Mark2CoveragebuildMarkArray
Mark1Array
Mark2Arrayr   
Mark2CountMark2Recordrg   buildMark2RecordrZ   )r   markClassListr^   r*   rs  r    )r  rp  r   r!   r   u  s$   


zMarkMarkPosBuilder.buildNrt  r    r    r    r!   r  I  s    r  c                   @   r<  )ReverseChainSingleSubstBuildera[  Builds a Reverse Chaining Contextual Single Substitution (GSUB8) lookup.

    Users are expected to manually add substitutions to the ``substitutions``
    attribute after the object has been initialized, e.g.::

        # reversesub [a e n] d' by d.alt;
        prefix = [ ["a", "e", "n"] ]
        suffix = []
        mapping = { "d": "d.alt" }
        builder.substitutions.append( (prefix, suffix, mapping) )

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        substitutions: A three-element tuple consisting of a prefix sequence,
            a suffix sequence, and a dictionary of single substitutions.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   s   t | ||dd g | _d S )NrG   r&   )rD   rO   r   r   r    r    r!   rO     r^  z'ReverseChainSingleSubstBuilder.__init__c                 C   r   r(   r   rQ   r    r    r!   rS     r   z%ReverseChainSingleSubstBuilder.equalsc                    s   g }| j D ]7\}} t }d|_| || | || t  | j|_	t
 |_ fdd|j	jD |_|| q| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the chained
            contextual substitution lookup.
        r#   c                       g | ]} | qS r    r    r@  rH  r    r!   r+     r~   z8ReverseChainSingleSubstBuilder.build.<locals>.<listcomp>)r   r   ReverseChainSingleSubstr   rl   rr   r"   r\   r   r   r;   ry   r   
Substituterg   rZ   )r   r3   rh   rp   r*   r    rH  r!   r     s   

z$ReverseChainSingleSubstBuilder.buildc                 C   s   d S r(   r    r   r    r    r!   r     rW   z1ReverseChainSingleSubstBuilder.add_subtable_breakNrV  r    r    r    r!   r    s    r  c                   @   r   )SingleSubstBuilderad  Builds a Single Substitution (GSUB1) lookup.

    Users are expected to manually add substitutions to the ``mapping``
    attribute after the object has been initialized, e.g.::

        # sub x by y;
        builder.mapping["x"] = "y"

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        mapping: A dictionary mapping a single glyph name to another glyph name.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   r   )NrG   r#   rX  r   r    r    r!   rO     r   zSingleSubstBuilder.__init__c                 C   r   r(   rY  rQ   r    r    r!   rS     r   zSingleSubstBuilder.equalsc                 C   r   )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the multiple
            substitution lookup.
        )r   r   buildSingleSubstSubtablerZ   rY   r    r    r!   r        
zSingleSubstBuilder.buildc                 C   s   dd | j  D S )Nc                 S   s   i | ]\}}||gqS r    r    )r)   r5  replr    r    r!   rj    r,   z9SingleSubstBuilder.getAlternateGlyphs.<locals>.<dictcomp>)r   rC  rU   r    r    r!   rX     s   z%SingleSubstBuilder.getAlternateGlyphsc                 C   r   r(   r[  r   r    r    r!   r     r   z%SingleSubstBuilder.add_subtable_breakNr   r    r    r    r!   r    s    
r  c                   @   r   )ClassPairPosSubtableBuilderaS  Builds class-based Pair Positioning (GPOS2 format 2) subtables.

    Note that this does *not* build a GPOS2 ``otTables.Lookup`` directly,
    but builds a list of ``otTables.PairPos`` subtables. It is used by the
    :class:`PairPosBuilder` below.

    Attributes:
        builder (PairPosBuilder): A pair positioning lookup builder.
    c                 C   s(   || _ d\| _| _i | _d| _g | _d S )NNNF)builder_
classDef1_
classDef2_values_forceSubtableBreak_
subtables_)r   builderr    r    r!   rO     s
   
z$ClassPairPosSubtableBuilder.__init__c                 C   s   | j  o| jduo| j|o| jduo| j|}|s/|   tdd| _tdd| _i | _| j| | j| ||f| j||f< dS )a~  Add a pair positioning rule.

        Args:
            gc1: A set of glyph names for the "left" glyph
            value1: An ``otTables.ValueRecord`` object for the left glyph's
                positioning.
            gc2: A set of glyph names for the "right" glyph
            value2: An ``otTables.ValueRecord`` object for the right glyph's
                positioning.
        NTr   F)r  r  r   r  flush_r   r  r   )r   gc1value1gc2value2	mergeabler    r    r!   addPair
  s"   

z#ClassPairPosSubtableBuilder.addPairc                 C   s
   d| _ dS )z-Add an explicit subtable break at this point.TN)r  rU   r    r    r!   addSubtableBreak%  s   
z,ClassPairPosSubtableBuilder.addSubtableBreakc                 C   s   |    | jS )z>Return the list of ``otTables.PairPos`` subtables constructed.)r  r  rU   r    r    r!   r3   )  s   z%ClassPairPosSubtableBuilder.subtablesc                 C   sL   | j d u s
| jd u rd S t| j| jj}|jd u rd S | j| d| _	d S )NF)
r  r  buildPairPosClassesSubtabler  r  r   r   r  rg   r  r/  r    r    r!   r  .  s   

z"ClassPairPosSubtableBuilder.flush_N)	r   r   r   r   rO   r  r  r3   r  r    r    r    r!   r    s    
r  c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )PairPosBuildera  Builds a Pair Positioning (GPOS2) lookup.

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        pairs: An array of class-based pair positioning tuples. Usually
            manipulated with the :meth:`addClassPair` method below.
        glyphPairs: A dictionary mapping a tuple of glyph names to a tuple
            of ``otTables.ValueRecord`` objects. Usually manipulated with the
            :meth:`addGlyphPair` method below.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   s(   t | ||dd g | _i | _i | _d S )NrF   r$   )rD   rO   pairs
glyphPairs	locationsr   r    r    r!   rO   L  s   
zPairPosBuilder.__init__c                 C   s   | j ||||f dS )a  Add a class pair positioning rule to the current lookup.

        Args:
            location: A string or tuple representing the location in the
                original source which produced this rule. Unused.
            glyphclass1: A set of glyph names for the "left" glyph in the pair.
            value1: A ``otTables.ValueRecord`` for positioning the left glyph.
            glyphclass2: A set of glyph names for the "right" glyph in the pair.
            value2: A ``otTables.ValueRecord`` for positioning the right glyph.
        N)r  rg   )r   rJ   glyphclass1r  glyphclass2r  r    r    r!   addClassPairR  s   zPairPosBuilder.addClassPairc           	      C   sX   ||f}| j |d}|dur| j| }td||| dS ||f| j |< || j|< dS )a  Add a glyph pair positioning rule to the current lookup.

        Args:
            location: A string or tuple representing the location in the
                original source which produced this rule.
            glyph1: A glyph name for the "left" glyph in the pair.
            value1: A ``otTables.ValueRecord`` for positioning the left glyph.
            glyph2: A glyph name for the "right" glyph in the pair.
            value2: A ``otTables.ValueRecord`` for positioning the right glyph.
        NzGAlready defined position for pair %s %s at %s; choosing the first value)r  r   r  r   debug)	r   rJ   glyph1r  glyph2r  r   oldValueotherLocr    r    r!   addGlyphPair_  s   
zPairPosBuilder.addGlyphPairc                 C   s    | j | j| j| j| jf d S r(   )r  rg   r   r   r    r    r!   r   {  s   z!PairPosBuilder.add_subtable_breakc                 C   rf  r(   )rD   rS   r  r  rQ   r    r    r!   rS     rg  zPairPosBuilder.equalsc           
      C   s   i }t | }| jD ]\}}}}|| ju r|  q	||||| q	g }| jr1|t| j| j ||	  | 
|}| jjjdt d}	|	dkrWtd t| j|	| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the pair positioning
            lookup.
        z0fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL)defaultr   zCompacting GPOS...)r  r  r   r  r  r  r   buildPairPosGlyphsr   r3   rZ   rH   r   r   r   r   infor   )
r   buildersr  r  r  r  r  r3   r7  levelr    r    r!   r     s(   


zPairPosBuilder.buildN)
r   r   r   r   rO   r  r  r   rS   r   r    r    r    r!   r  8  s    
r  c                   @   r   )r9  a  Builds a Single Positioning (GPOS1) lookup.

    Attributes:
        font (``fontTools.TTLib.TTFont``): A font object.
        location: A string or tuple representing the location in the original
            source which produced this lookup.
        mapping: A dictionary mapping a glyph name to a ``otTables.ValueRecord``
            objects. Usually manipulated with the :meth:`add_pos` method below.
        lookupflag (int): The lookup's flag
        markFilterSet: Either ``None`` if no mark filtering set is used, or
            an integer representing the filtering set to be used for this
            lookup. If a mark filtering set is provided,
            `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
            flags.
    c                 C   rd  )NrF   r#   )rD   rO   r  r   r   r    r    r!   rO     r2  zSinglePosBuilder.__init__c                 C   sD   |  ||s| j| }td||f ||r|| j|< || j|< dS )a?  Add a single positioning rule.

        Args:
            location: A string or tuple representing the location in the
                original source which produced this lookup.
            glyph: A glyph name.
            otValueRection: A ``otTables.ValueRecord`` used to position the
                glyph.
        z7Already defined different position for glyph "%s" at %sN)r3  r  r   r   )r   rJ   r5  otValueRecordr  r    r    r!   add_pos  s   


zSinglePosBuilder.add_posc                 C   s*   t |tsJ | j|}|d u p||kS r(   )r>   r   r   r   )r   r5  r8  curValuer    r    r!   r3    s   zSinglePosBuilder.can_addc                 C   r   r(   rY  rQ   r    r    r!   rS     r   zSinglePosBuilder.equalsc                 C   s   t | j| j}| |S )zBuild the lookup.

        Returns:
            An ``otTables.Lookup`` object representing the single positioning
            lookup.
        )buildSinglePosr   r   rZ   rY   r    r    r!   r     r  zSinglePosBuilder.buildN)	r   r   r   r   rO   r  r3  rS   r   r    r    r    r!   r9    s    r9  c                 C      | sdS t  }t| |_|S )a  Builds a single substitution (GSUB1) subtable.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead.

    Args:
        mapping: A dictionary mapping input glyph names to output glyph names.

    Returns:
        An ``otTables.SingleSubst`` object, or ``None`` if the mapping dictionary
        is empty.
    N)r   SingleSubstdictr   r   r   r    r    r!   r    s
   
r  c                 C   r  )a  Builds a multiple substitution (GSUB2) subtable.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead.

    Example::

        # sub uni06C0 by uni06D5.fina hamza.above
        # sub uni06C2 by uni06C1.fina hamza.above;

        subtable = buildMultipleSubstSubtable({
            "uni06C0": [ "uni06D5.fina", "hamza.above"],
            "uni06C2": [ "uni06D1.fina", "hamza.above"]
        })

    Args:
        mapping: A dictionary mapping input glyph names to a list of output
            glyph names.

    Returns:
        An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary
        is empty.
    N)r   MultipleSubstr  r   r  r    r    r!   rZ    s
   
rZ  c                 C   r  )a  Builds an alternate substitution (GSUB3) subtable.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead.

    Args:
        mapping: A dictionary mapping input glyph names to a list of output
            glyph names.

    Returns:
        An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary
        is empty.
    N)r   AlternateSubstr  r   r  r    r    r!   r   %  s
   
r   c                 C   s~   | sdS t  }i |_t|  |jdD ](}t  }|dd |_t|jd |_	| | |_
|d }|j|g | q|S )a  Builds a ligature substitution (GSUB4) subtable.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead.

    Example::

        # sub f f i by f_f_i;
        # sub f i by f_i;

        subtable = buildLigatureSubstSubtable({
            ("f", "f", "i"): "f_f_i",
            ("f", "i"): "f_i",
        })

    Args:
        mapping: A dictionary mapping tuples of glyph names to output
            glyph names.

    Returns:
        An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary
        is empty.
    Nr   r#   r   )r   LigatureSubstrM  r   r\   _getLigatureSortKeyLigature	Componentr;   	CompCountLigGlyphrD  rg   )r   r   r  ligaturer   r    r    r!   rU  ;  s   
rU  c                 C   sh   t  }| ||_|_d|_|dur||_d|_|dus |dur2|jdks)J d||_||_d|_|S )a  Builds an Anchor table.

    This determines the appropriate anchor format based on the passed parameters.

    Args:
        x (int): X coordinate.
        y (int): Y coordinate.
        point (int): Index of glyph contour point, if provided.
        deviceX (``otTables.Device``): X coordinate device table, if provided.
        deviceY (``otTables.Device``): Y coordinate device table, if provided.

    Returns:
        An ``otTables.Anchor`` object.
    r#   Nr$   z7Either point, or both of deviceX/deviceY, must be None.r   )r   AnchorXCoordinateYCoordinater   AnchorPointXDeviceTableYDeviceTable)r   ypointdeviceXdeviceYr   r    r    r!   buildAnchori  s   r  c                    s`   t  }g |_t| |jdD ]}| |   fddt|D }|jt| qt|j|_	|S )a  Builds a base array record.

    As part of building mark-to-base positioning rules, you will need to define
    a ``BaseArray`` record, which "defines for each base glyph an array of
    anchors, one for each mark class." This function builds the base array
    subtable.

    Example::

        bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}}
        basearray = buildBaseArray(bases, 2, font.getReverseGlyphMap())

    Args:
        bases (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being dictionaries mapping mark class ID
            to the appropriate ``otTables.Anchor`` object used for attaching marks
            of that class.
        numMarkClasses (int): The total number of mark classes for which anchors
            are defined.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        An ``otTables.BaseArray`` object.
    r   c                       g | ]}  |qS r    r   )r)   	markClassbr    r!   r+         z"buildBaseArray.<locals>.<listcomp>)
r   	BaseArray
BaseRecordr   r   rangerg   buildBaseRecordr;   	BaseCount)re  numMarkClassesr   r   r  rs  r    r  r!   buildBaseArray  s   r  c                 C      t  }| |_|S r(   )r   r  
BaseAnchorrs  r   r    r    r!   r       r  c                 C   s   | sdS t  }| |_|S )a  Builds a component record.

    As part of building mark-to-ligature positioning rules, you will need to
    define ``ComponentRecord`` objects, which contain "an array of offsets...
    to the Anchor tables that define all the attachment points used to attach
    marks to the component." This function builds the component record.

    Args:
        anchors: A list of ``otTables.Anchor`` objects or ``None``.

    Returns:
        A ``otTables.ComponentRecord`` object or ``None`` if no anchors are
        supplied.
    N)r   ComponentRecordLigatureAnchorr  r    r    r!   buildComponentRecord  s
   r  c                 C   sv   | sdS t  }d|_t|  ||_g |_|jjD ]}| | \}}t  }||_||_	|j
| qt|j|_|S )ay  Builds a cursive positioning (GPOS3) subtable.

    Cursive positioning lookups are made up of a coverage table of glyphs,
    and a set of ``EntryExitRecord`` records containing the anchors for
    each glyph. This function builds the cursive positioning subtable.

    Example::

        subtable = buildCursivePosSubtable({
            "AlifIni": (None, buildAnchor(0, 50)),
            "BehMed": (buildAnchor(500,250), buildAnchor(0,50)),
            # ...
        }, font.getReverseGlyphMap())

    Args:
        attach (dict): A mapping between glyph names and a tuple of two
            ``otTables.Anchor`` objects representing entry and exit anchors.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        An ``otTables.CursivePos`` object, or ``None`` if the attachment
        dictionary was empty.
    Nr#   )r   
CursivePosr   r"   r\   r   EntryExitRecordr   EntryAnchor
ExitAnchorrg   r;   EntryExitCount)attachr   r   r5  r_  r`  r  r    r    r!   rb    s   rb  c                    s    sdS t  }  }t| |_}t| |_}d|  kr%|ks(J  J  fddt||d D  |_}t|}t|}|dkrI|dk sKJ |dkrX|d	k rXd|_	|S |d
kre|dk red	|_	|S d|_	|S )a  Builds a Device record as part of a ValueRecord or Anchor.

    Device tables specify size-specific adjustments to value records
    and anchors to reflect changes based on the resolution of the output.
    For example, one could specify that an anchor's Y position should be
    increased by 1 pixel when displayed at 8 pixels per em. This routine
    builds device records.

    Args:
        deltas: A dictionary mapping pixels-per-em sizes to the delta
            adjustment in pixels when the font is displayed at that size.

    Returns:
        An ``otTables.Device`` object if any deltas were supplied, or
        ``None`` otherwise.
    Nr   c                    s   g | ]}  |d qS r   r  )r)   r   deltasr    r!   r+   
      zbuildDevice.<locals>.<listcomp>r#   i   r$   ir&   r   )
r   Devicer\   r   	StartSizemaxEndSizer  
DeltaValueDeltaFormat)r  r   r\   	startSizeendSizedeltaValuesmaxDeltaminDeltar    r  r!   buildDevice  s*   
r  c                    sp   t  }g |_t| |jdD ]!}g }| | D ] | fddt|D  q|jt| qt|j|_	|S )a6  Builds a LigatureArray subtable.

    As part of building a mark-to-ligature lookup, you will need to define
    the set of anchors (for each mark class) on each component of the ligature
    where marks can be attached. For example, for an Arabic divine name ligature
    (lam lam heh), you may want to specify mark attachment positioning for
    superior marks (fatha, etc.) and inferior marks (kasra, etc.) on each glyph
    of the ligature. This routine builds the ligature array record.

    Example::

        buildLigatureArray({
            "lam-lam-heh": [
                { 0: superiorAnchor1, 1: inferiorAnchor1 }, # attach points for lam1
                { 0: superiorAnchor2, 1: inferiorAnchor2 }, # attach points for lam2
                { 0: superiorAnchor3, 1: inferiorAnchor3 }, # attach points for heh
            ]
        }, 2, font.getReverseGlyphMap())

    Args:
        ligs (dict): A mapping of ligature names to an array of dictionaries:
            for each component glyph in the ligature, an dictionary mapping
            mark class IDs to anchors.
        numMarkClasses (int): The number of mark classes.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        An ``otTables.LigatureArray`` object if deltas were supplied.
    r   c                    r  r    r  r  	componentr    r!   r+   =  r  z&buildLigatureArray.<locals>.<listcomp>)
r   LigatureArrayLigatureAttachr   r   rg   r  buildLigatureAttachr;   LigatureCount)r}  r  r   r   r~  rs  r    r  r!   buildLigatureArray  s   r  c                 C   s(   t  }dd | D |_t|j|_|S )Nc                 S      g | ]}t |qS r    )r  r   r    r    r!   r+   F  r~   z'buildLigatureAttach.<locals>.<listcomp>)r   r  r  r;   ComponentCount)r  r   r    r    r!   r  C  s   r  c                 C   sX   t  }g |_t|  |jdD ]}| | \}}t||}|j| qt|j|_	|S )a[  Builds a mark array subtable.

    As part of building mark-to-* positioning rules, you will need to define
    a MarkArray subtable, which "defines the class and the anchor point
    for a mark glyph." This function builds the mark array subtable.

    Example::

        mark = {
            "acute": (0, buildAnchor(300,712)),
            # ...
        }
        markarray = buildMarkArray(marks, font.getReverseGlyphMap())

    Args:
        marks (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being a tuple of mark class number and
            an ``otTables.Anchor`` object representing the mark's attachment
            point.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        An ``otTables.MarkArray`` object.
    r   )
r   	MarkArray
MarkRecordr   r\   r   buildMarkRecordrg   r;   	MarkCount)r^   r   r   r`   r  rr  markrecr    r    r!   r  K  s   
r  c                 C      t | ||gS )au  Build a list of MarkBasePos (GPOS4) subtables.

    This routine turns a set of marks and bases into a list of mark-to-base
    positioning subtables. Currently the list will contain a single subtable
    containing all marks and bases, although at a later date it may return the
    optimal list of subtables subsetting the marks and bases into groups which
    save space. See :func:`buildMarkBasePosSubtable` below.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.MarkBasePosBuilder` instead.

    Example::

        # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...

        marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)}
        bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}}
        markbaseposes = buildMarkBasePos(marks, bases, font.getReverseGlyphMap())

    Args:
        marks (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being a tuple of mark class number and
            an ``otTables.Anchor`` object representing the mark's attachment
            point. (See :func:`buildMarkArray`.)
        bases (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being dictionaries mapping mark class ID
            to the appropriate ``otTables.Anchor`` object used for attaching marks
            of that class. (See :func:`buildBaseArray`.)
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A list of ``otTables.MarkBasePos`` objects.
    )buildMarkBasePosSubtable)r^   re  r   r    r    r!   ro  o  s   /ro  c                 C   b   t  }d|_t| ||_t| ||_tdd |  D d |_	t|||_
t||j	||_|S )a  Build a single MarkBasePos (GPOS4) subtable.

    This builds a mark-to-base lookup subtable containing all of the referenced
    marks and bases. See :func:`buildMarkBasePos`.

    Args:
        marks (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being a tuple of mark class number and
            an ``otTables.Anchor`` object representing the mark's attachment
            point. (See :func:`buildMarkArray`.)
        bases (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being dictionaries mapping mark class ID
            to the appropriate ``otTables.Anchor`` object used for attaching marks
            of that class. (See :func:`buildBaseArray`.)
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A ``otTables.MarkBasePos`` object.
    r#   c                 S      g | ]\}}|qS r    r    r)   rq  r	  r    r    r!   r+     r~   z,buildMarkBasePosSubtable.<locals>.<listcomp>)r   MarkBasePosr   r"   MarkCoverager  r  r  valuesr  BaseCoverager  r  )r^   re  r   r   r    r    r!   r    s   r  c                 C   r  )a  Build a list of MarkLigPos (GPOS5) subtables.

    This routine turns a set of marks and ligatures into a list of mark-to-ligature
    positioning subtables. Currently the list will contain a single subtable
    containing all marks and ligatures, although at a later date it may return
    the optimal list of subtables subsetting the marks and ligatures into groups
    which save space. See :func:`buildMarkLigPosSubtable` below.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead.

    Example::

        # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...
        marks = {
            "acute": (0, a1),
            "grave": (0, a1),
            "cedilla": (1, a2)
        }
        ligs = {
            "f_i": [
                { 0: a3, 1: a5 }, # f
                { 0: a4, 1: a5 }  # i
                ],
        #   "c_t": [{...}, {...}]
        }
        markligposes = buildMarkLigPos(marks, ligs,
            font.getReverseGlyphMap())

    Args:
        marks (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being a tuple of mark class number and
            an ``otTables.Anchor`` object representing the mark's attachment
            point. (See :func:`buildMarkArray`.)
        ligs (dict): A mapping of ligature names to an array of dictionaries:
            for each component glyph in the ligature, an dictionary mapping
            mark class IDs to anchors. (See :func:`buildLigatureArray`.)
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A list of ``otTables.MarkLigPos`` objects.

    )buildMarkLigPosSubtable)r^   r}  r   r    r    r!   r|    s   2r|  c                 C   r  )a`  Build a single MarkLigPos (GPOS5) subtable.

    This builds a mark-to-base lookup subtable containing all of the referenced
    marks and bases. See :func:`buildMarkLigPos`.

    Args:
        marks (dict): A dictionary mapping anchors to glyphs; the keys being
            glyph names, and the values being a tuple of mark class number and
            an ``otTables.Anchor`` object representing the mark's attachment
            point. (See :func:`buildMarkArray`.)
        ligs (dict): A mapping of ligature names to an array of dictionaries:
            for each component glyph in the ligature, an dictionary mapping
            mark class IDs to anchors. (See :func:`buildLigatureArray`.)
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A ``otTables.MarkLigPos`` object.
    r#   c                 S   r  r    r    r  r    r    r!   r+     r~   z+buildMarkLigPosSubtable.<locals>.<listcomp>)r   
MarkLigPosr   r"   r  r  r  r  r  r  LigatureCoverager  r  )r^   r}  r   r   r    r    r!   r    s   r  c                 C   s6   t | tsJ t |tjsJ t }| |_||_|S r(   )r>   r?   r   r  r  r  
MarkAnchor)classIDrr  r   r    r    r!   r    s   r  c                 C   r  r(   )r   r  Mark2Anchorr  r    r    r!   r    r  r  c                 C   sB   | d ur| S d}|D ]}|d ur|| d ur|||   O }q
|S r   	getFormat)fr  r   maskr8  r    r    r!   _getValueFormat#  s   r#  c                 C   sV  t  }tdd}tdd}t| D ]\}}|| || || qt }	d|	_t|| 	 d }|	_
t|| 	 d }|	_t|||	_| |	_| |	_| }
| }g |	_|
D ]>}t }g |_|	j| |D ],}t }| ||fd\}}|rt||dnd	|_|rt||dnd	|_|j| qpq_t|	j|	_t||	_|	S )
a  Builds a class pair adjustment (GPOS2 format 2) subtable.

    Kerning tables are generally expressed as pair positioning tables using
    class-based pair adjustments. This routine builds format 2 PairPos
    subtables.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.ClassPairPosSubtableBuilder`
    instead, as this takes care of ensuring that the supplied pairs can be
    formed into non-overlapping classes and emitting individual subtables
    whenever the non-overlapping requirement means that a new subtable is
    required.

    Example::

        pairs = {}

        pairs[(
            [ "K", "X" ],
            [ "W", "V" ]
        )] = ( buildValue(xAdvance=+5), buildValue() )
        # pairs[(... , ...)] = (..., ...)

        pairpos = buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap())

    Args:
        pairs (dict): Pair positioning data; the keys being a two-element
            tuple of lists of glyphnames, and the values being a two-element
            tuple of ``otTables.ValueRecord`` objects.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.
        valueFormat1: Force the "left" value records to the given format.
        valueFormat2: Force the "right" value records to the given format.

    Returns:
        A ``otTables.PairPos`` object.
    Tr   Fr$   r   r#   r  srcvalueFormatN)r   r   r   rl  r   r   PairPosr   r#  r  ValueFormat1ValueFormat2r"   r   r   	ClassDef1	ClassDef2r   Class1RecordClass2Recordrg   r   r   Value1Value2r;   Class1CountClass2Count)r  r   valueFormat1valueFormat2rk   	classDef1	classDef2r  r  r   classes1classes2c1rec1c2rec2val1val2r    r    r!   r  .  sJ   '






r  c           
         s   i }|   D ],\\}}\}}|dur| nd}|dur | nd}|||fi }	||f|	||f< q fddt|  D S )a  Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables.

    This organises a list of pair positioning adjustments into subtables based
    on common value record formats.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder`
    instead.

    Example::

        pairs = {
            ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ),
            ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ),
            # ...
        }

        subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap())

    Args:
        pairs (dict): Pair positioning data; the keys being a two-element
            tuple of glyphnames, and the values being a two-element
            tuple of ``otTables.ValueRecord`` objects.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A list of ``otTables.PairPos`` objects.
    Nr   c                    s"   g | ]\\}}}t | ||qS r    )buildPairPosGlyphsSubtable)r)   formatAformatBposr   r    r!   r+     s    
z&buildPairPosGlyphs.<locals>.<listcomp>)rC  r   rD  r   )
r  r   rj   glyphAglyphBvalAvalBr?  r@  rA  r    rB  r!   r  }  s    

r  c                    s>  t  }d|_t||  d }|_t||  d }|_i }|  D ]\\}}\}}	||g 	|||	f q#t
dd |  D  |_g |_|jjD ]J}
t  }g |_|j	| t||
  fdddD ](\}}}t  }||_|r{t||dnd	|_|rt||dnd	|_|j	| qgt|j|_qLt|j|_|S )
a  Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.

    This builds a PairPos subtable from a dictionary of glyph pairs and
    their positioning adjustments. See also :func:`buildPairPosGlyphs`.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead.

    Example::

        pairs = {
            ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ),
            ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ),
            # ...
        }

        pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap())

    Args:
        pairs (dict): Pair positioning data; the keys being a two-element
            tuple of glyphnames, and the values being a two-element
            tuple of ``otTables.ValueRecord`` objects.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.
        valueFormat1: Force the "left" value records to the given format.
        valueFormat2: Force the "right" value records to the given format.

    Returns:
        A ``otTables.PairPos`` object.
    r#   r   c                 S   s   h | ]\}}|qS r    r    )r)   rw   r	  r    r    r!   	<setcomp>  r~   z-buildPairPosGlyphsSubtable.<locals>.<setcomp>c                    s    | d  S r   r    r   rB  r    r!   r     s    z,buildPairPosGlyphsSubtable.<locals>.<lambda>r   r$  N)r   r'  r   r#  r  r(  r)  rC  rD  rg   r"   r\   r   PairSetr   PairValueRecordr   SecondGlyphr   r.  r/  r;   PairValueCountPairSetCount)r  r   r2  r3  r   rj   rC  rD  rE  rF  r5  psr  r<  r=  pvrr    rB  r!   r>    s8    "r>  c                    s  g t  }i i i }}|  D ] \}}t||g | |d g  |< q| D ]%\}t|t dkr\fdd|D }|t|   q7| D ]6\}	}
fdd|
D }t|dkri }|D ]|	fdd	| D  qx|t|  	| qa| D ]\}vr|D ]}t| i }q|| q|j
 fd
dd |S )a  Builds a list of single adjustment (GPOS1) subtables.

    This builds a list of SinglePos subtables from a dictionary of glyph
    names and their positioning adjustments. The format of the subtables are
    determined to optimize the size of the resulting subtables.
    See also :func:`buildSinglePosSubtable`.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead.

    Example::

        mapping = {
            "V": buildValue({ "xAdvance" : +5 }),
            # ...
        }

        subtables = buildSinglePos(pairs, font.getReverseGlyphMap())

    Args:
        mapping (dict): A mapping between glyphnames and
            ``otTables.ValueRecord`` objects.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A list of ``otTables.SinglePos`` objects.
    r   rv  c                    s   i | ]}|  qS r    r    r@  )r   r  r    r!   rj  	  r  z"buildSinglePos.<locals>.<dictcomp>c                    s   g | ]}| vr|qS r    r    )r)   k)handledr    r!   r+   	  r,   z"buildSinglePos.<locals>.<listcomp>r#   c                 3   s    | ]	}|  fV  qd S r(   r    r@  )rO  r  r    r!   r4   #	  r   z!buildSinglePos.<locals>.<genexpr>c                    s
   t |  S r(   )_getSinglePosTableKey)r1   rB  r    r!   r   7	  s   
 z buildSinglePos.<locals>.<lambda>r   )r   rC  _getSinglePosValueKeyrD  rg   r;   _getSinglePosValueSizebuildSinglePosSubtabler   rl  sort)r   r   rE  	coveragesmasksr5  r8  r   format1Mappingr&  r\   f2format2Mappingrw   r*   r    )r   rP  rO  r   r  r!   r    s<   

 


r  c                    s   t  }t ||_ttjdd  D d  |_	 fdd|jj
D tfddD rHd|_|j	dkrCd |_|S d|_|S d	|_|_t|j|_|S )
a  Builds a single adjustment (GPOS1) subtable.

    This builds a list of SinglePos subtables from a dictionary of glyph
    names and their positioning adjustments. The format of the subtable is
    determined to optimize the size of the output.
    See also :func:`buildSinglePos`.

    Note that if you are implementing a layout compiler, you may find it more
    flexible to use
    :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead.

    Example::

        mapping = {
            "V": buildValue({ "xAdvance" : +5 }),
            # ...
        }

        subtable = buildSinglePos(pairs, font.getReverseGlyphMap())

    Args:
        mapping (dict): A mapping between glyphnames and
            ``otTables.ValueRecord`` objects.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A ``otTables.SinglePos`` object.
    c                 S   r   r    r  r)   vr    r    r!   r+   \	  r~   z*buildSinglePosSubtable.<locals>.<listcomp>r   c                    s   g | ]
}t |  d qS )r$  )r   r@  )r&  r  r    r!   r+   ^	  s    c                 3   s    | ]	}| d  kV  qdS r-   r    r[  )valueRecordsr    r!   r4   b	  r   z)buildSinglePosSubtable.<locals>.<genexpr>r#   Nr$   )r   	SinglePosr"   r\   r   r   r?   __or__r  ValueFormatr   r6   r   Valuer;   
ValueCount)r  r   r   r    )r&  r]  r  r!   rT  ;	  s&   


rT  c                 C   s2   t | tjs
J | | jj}t| ||d  fS r   )r>   r   r^  r   r   r;   )ri   r   r   r    r    r!   rQ  o	  s   rQ  c                 C   s   t | ts	J | dg }}| j D ]#\}}t |tjr'||t|f n|||f |t| d O }q|	  |
d| t|S r   )r>   r   __dict__rC  r   r  rg   _makeDeviceTupler	   rU  r(  tuple)valueRecordr&  rE  namer8  r    r    r!   rR  u	  s   
rR  _DeviceTuplez(DeltaFormat StartSize EndSize DeltaValuec                 C   s*   t | j| j| j| jd@ rdS t| jS )Ni   r    )rh  r  r  r  re  r  )devicer    r    r!   rd  	  s   rd  c                 C   sD   d}| dd  D ]\}}t |tr|t|jd 7 }q|d7 }q|S )Nr   r#   r   )r>   rh  r;   r  )valueKeycountr	  r\  r    r    r!   rS  	  s   

rS  c                 C   s(   t  }|  D ]
\}}t||| q|S )a  Builds a positioning value record.

    Value records are used to specify coordinates and adjustments for
    positioning and attaching glyphs. Many of the positioning functions
    in this library take ``otTables.ValueRecord`` objects as arguments.
    This function builds value records from dictionaries.

    Args:
        value (dict): A dictionary with zero or more of the following keys:
            - ``xPlacement``
            - ``yPlacement``
            - ``xAdvance``
            - ``yAdvance``
            - ``xPlaDevice``
            - ``yPlaDevice``
            - ``xAdvDevice``
            - ``yAdvDevice``

    Returns:
        An ``otTables.ValueRecord`` object.
    )r   rC  r   )r8  r   rO  r\  r    r    r!   
buildValue	  s   rl  c                    sH    sdS t  }t  ||_ fdd|jjD |_t|j|_|S )a  Builds an AttachList subtable.

    A GDEF table may contain an Attachment Point List table (AttachList)
    which stores the contour indices of attachment points for glyphs with
    attachment points. This routine builds AttachList subtables.

    Args:
        attachPoints (dict): A mapping between glyph names and a list of
            contour indices.

    Returns:
        An ``otTables.AttachList`` object if attachment points are supplied,
            or ``None`` otherwise.
    Nc                       g | ]}t  | qS r    )buildAttachPointr@  attachPointsr    r!   r+   	  r,   z#buildAttachList.<locals>.<listcomp>)	r   
AttachListr"   r\   r   r   AttachPointr;   ry   )rp  r   r   r    ro  r!   buildAttachList	  s   rs  c                 C   s.   | sd S t  }tt| |_t|j|_|S r(   )r   rr  r   r   
PointIndexr;   
PointCount)pointsr   r    r    r!   rn  	  s   rn  c                 C   s8   t  }t| trd|_| \|_|_|S d|_| |_|S )Nr   r#   )r   
CaretValuer>   re  r   
CoordinateDeviceTable)coordr   r    r    r!   buildCaretValueForCoord	  s   
r{  c                 C   s   t  }d|_| |_|S )Nr$   )r   rw  r   CaretValuePoint)r  r   r    r    r!   buildCaretValueForPoint	  s   r}  c                    s   rt  nt  }r|  fdd|D  dd   D   s+dS t }t  ||_ fdd|jjD |_	t
|j	|_|S )a  Builds a ligature caret list table.

    Ligatures appear as a single glyph representing multiple characters; however
    when, for example, editing text containing a ``f_i`` ligature, the user may
    want to place the cursor between the ``f`` and the ``i``. The ligature caret
    list in the GDEF table specifies the position to display the "caret" (the
    character insertion indicator, typically a flashing vertical bar) "inside"
    the ligature to represent an insertion point. The insertion positions may
    be specified either by coordinate or by contour point.

    Example::

        coords = {
            "f_f_i": [300, 600] # f|fi cursor at 300 units, ff|i cursor at 600.
        }
        points = {
            "c_t": [28] # c|t cursor appears at coordinate of contour point 28.
        }
        ligcaretlist = buildLigCaretList(coords, points, font.getReverseGlyphMap())

    Args:
        coords: A mapping between glyph names and a list of coordinates for
            the insertion point of each ligature component after the first one.
        points: A mapping between glyph names and a list of contour points for
            the insertion point of each ligature component after the first one.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns:
        A ``otTables.LigCaretList`` object if any carets are present, or
            ``None`` otherwise.c                    s$   i | ]}|t  ||qS r    )buildLigGlyphr   r@  )coordsrv  r    r!   rj  
  s   $ z%buildLigCaretList.<locals>.<dictcomp>c                 S   s   i | ]\}}|d ur||qS r(   r    )r)   rw   r   r    r    r!   rj  
  r   Nc                    r  r    r    r@  )caretsr    r!   r+   
  r~   z%buildLigCaretList.<locals>.<listcomp>)r   r\   rl  rC  r   LigCaretListr"   r   r   r  r;   LigGlyphCount)r  rv  r   r   r   r    )r  r  rv  r!   buildLigCaretList	  s    r  c                 C   sn   g }| rt | dd d} |dd | D  |r$|dd t |D  |s(d S t }||_t|j|_|S )Nc                 S   s   t | tr	| d S | S r   )r>   re  )r   r    r    r!   r   %
  r  zbuildLigGlyph.<locals>.<lambda>r   c                 S   r	  r    )r{  r   r    r    r!   r+   &
  r~   z!buildLigGlyph.<locals>.<listcomp>c                 S   r	  r    )r}  )r)   rj   r    r    r!   r+   (
  r~   )r   r   r   r  rw  r;   
CaretCount)r  rv  r  r   r    r    r!   r~  !
  s   r~  c                    s:   | sdS t  }d|_ fdd| D |_t|j|_|S )a  Builds a mark glyph sets definition table.

    OpenType Layout lookups may choose to use mark filtering sets to consider
    or ignore particular combinations of marks. These sets are specified by
    setting a flag on the lookup, but the mark filtering sets are defined in
    the ``GDEF`` table. This routine builds the subtable containing the mark
    glyph set definitions.

    Example::

        set0 = set("acute", "grave")
        set1 = set("caron", "grave")

        markglyphsets = buildMarkGlyphSetsDef([set0, set1], font.getReverseGlyphMap())

    Args:

        markSets: A list of sets of glyphnames.
        glyphMap: a glyph name to ID map, typically returned from
            ``font.getReverseGlyphMap()``.

    Returns
        An ``otTables.MarkGlyphSetsDef`` object.
    Nr#   c                    s   g | ]}t | qS r    )r"   )r)   mrB  r    r!   r+   N
  r  z)buildMarkGlyphSetsDef.<locals>.<listcomp>)r   MarkGlyphSetsDefMarkSetTableFormatr   r;   MarkSetCount)markSetsr   r   r    rB  r!   buildMarkGlyphSetsDef1
  s   r  c                   @   r   )r   z$Helper for building ClassDef tables.c                 C   s   t  | _i | _|| _d S r(   )r   classes_glyphs_
useClass0_)r   r   r    r    r!   rO   V
  s   
zClassDefBuilder.__init__c                 C   sJ   t |ttfrt|}t|}|| jv rdS |D ]
}|| jv r" dS qdS )NTF)r>   r   	frozensetr   re  r  r  r   r   r5  r    r    r!   r   [
  s   

zClassDefBuilder.canAddc                 C   sl   t |ttfrt|}t|}|| jv rd S | j| |D ]}|| jv r.td| dd || j|< qd S )NzGlyph z is already present in class.)	r>   r   r  r   re  r  r   r  r   r  r    r    r!   r   f
  s   

zClassDefBuilder.addc                 C   s*   t | jdd d}| js|dt  |S )Nc                 S   s   t |  | fS r(   r   )rq   r    r    r!   r   
  s    z)ClassDefBuilder.classes.<locals>.<lambda>r   r   )r   r  r  r(  r  rm  r    r    r!   r   t
  s   zClassDefBuilder.classesc                 C   sH   i }t |  D ]\}}|dkrq|D ]}|||< qqt }||_|S r   )r  r   r   r  r   )r   glyphClassesr  r   r5  classDefr    r    r!   r   
  s   
zClassDefBuilder.buildN)	r   r   r   r   rO   r   r   r   r   r    r    r    r!   r   S
  s    r   i   iTc                 C   s   t d| d< t  }| d _t| |||d|_t|| ||d\}}|s)d|_nd|_t	||| ||d}	|	| }| d j
  t }
||
_d|_|
|_t||_d|_d	|_|rkt }||_||_t||_d	S d	S )
a  Add a 'STAT' table to 'ttFont'.

    'axes' is a list of dictionaries describing axes and their
    values.

    Example::

        axes = [
            dict(
                tag="wght",
                name="Weight",
                ordering=0,  # optional
                values=[
                    dict(value=100, name='Thin'),
                    dict(value=300, name='Light'),
                    dict(value=400, name='Regular', flags=0x2),
                    dict(value=900, name='Black'),
                ],
            )
        ]

    Each axis dict must have 'tag' and 'name' items. 'tag' maps
    to the 'AxisTag' field. 'name' can be a name ID (int), a string,
    or a dictionary containing multilingual names (see the
    addMultilingualName() name table method), and will translate to
    the AxisNameID field.

    An axis dict may contain an 'ordering' item that maps to the
    AxisOrdering field. If omitted, the order of the axes list is
    used to calculate AxisOrdering fields.

    The axis dict may contain a 'values' item, which is a list of
    dictionaries describing AxisValue records belonging to this axis.

    Each value dict must have a 'name' item, which can be a name ID
    (int), a string, or a dictionary containing multilingual names,
    like the axis name. It translates to the ValueNameID field.

    Optionally the value dict can contain a 'flags' item. It maps to
    the AxisValue Flags field, and will be 0 when omitted.

    The format of the AxisValue is determined by the remaining contents
    of the value dictionary:

    If the value dict contains a 'value' item, an AxisValue record
    Format 1 is created. If in addition to the 'value' item it contains
    a 'linkedValue' item, an AxisValue record Format 3 is built.

    If the value dict contains a 'nominalValue' item, an AxisValue
    record Format 2 is built. Optionally it may contain 'rangeMinValue'
    and 'rangeMaxValue' items. These map to -Infinity and +Infinity
    respectively if omitted.

    You cannot specify Format 4 AxisValue tables this way, as they are
    not tied to a single axis, and specify a name for a location that
    is defined by multiple axes values. Instead, you need to supply the
    'locations' argument.

    The optional 'locations' argument specifies AxisValue Format 4
    tables. It should be a list of dicts, where each dict has a 'name'
    item, which works just like the value dicts above, an optional
    'flags' item (defaulting to 0x0), and a 'location' dict. A
    location dict key is an axis tag, and the associated value is the
    location on the specified axis. They map to the AxisIndex and Value
    fields of the AxisValueRecord.

    Example::

        locations = [
            dict(name='Regular ABCD', location=dict(wght=300, ABCD=100)),
            dict(name='Bold ABCD XYZ', location=dict(wght=600, ABCD=200)),
        ]

    The optional 'elidedFallbackName' argument can be a name ID (int),
    a string, a dictionary containing multilingual names, or a list of
    STATNameStatements. It translates to the ElidedFallbackNameID field.

    The 'ttFont' argument must be a TTFont instance that already has a
    'name' table. If a 'STAT' table already exists, it will be
    overwritten by the newly created one.
    STATwindowsmac)windowsNamesmacNamesi  i  rg  r&   r   N)r   newTabler   r  rK   _addNameElidedFallbackNameID_buildAxisRecordsVersion_buildAxisValuesFormat4namesrU  AxisRecordArrayAxisDesignAxisRecordSizeDesignAxisRecordr;   DesignAxisCountAxisValueCountAxisValueArray	AxisValue)ttFontaxesr  elidedFallbackNamer  r  	statTableaxisRecords
axisValuesmultiAxisValuesaxisRecordArrayaxisValueArrayr    r    r!   buildStatTable
  s:   T


r  c                 C   s$  g }g }t | D ]\}}t }|d |_t||d d||d|_|d||_|| |ddD ]Y}	t	 }
||
_
|	dd	|
_t||	d ||d|
_d
|	v rh|	d
 |
_d|	v rdd|
_|	d |
_n#d|
_nd|	v rd|
_|	d |
_|	dt|
_|	dt|
_ntd||
 q3q||fS )Ntagrg     r  orderingr  r    rA   r   r8  linkedValuer   r#   nominalValuer$   rangeMinValuerangeMaxValuez$Can't determine format for AxisValue)r  r   
AxisRecordAxisTagr  
AxisNameIDr   AxisOrderingrg   r  	AxisIndexFlagsValueNameIDra  r   LinkedValueNominalValueAXIS_VALUE_NEGATIVE_INFINITYRangeMinValueAXIS_VALUE_POSITIVE_INFINITYRangeMaxValuer   )r  r  r  r  r  r  axisRecordIndexaxisDictaxisaxisVal
axisValRecr    r    r!   r    sH   



r  c                 C   s   i }t |D ]
\}}|||d < qg }| D ]N}	t }
d|
_t||	d ||d|
_|	dd|
_g }|	d  D ]\}}t	 }|| |_
||_|| q8|jdd	 d
 t||
_||
_	||
 q|S )Nr  r%   rg  r  rA   r   rJ   c                 S   r   r(   )r  )avrr    r    r!   r   P  s    z)_buildAxisValuesFormat4.<locals>.<lambda>r   )r  r   r  r   r  r  r   r  rC  AxisValueRecordr  ra  rg   rU  r;   	AxisCount)r  r  r  r  r  axisTagToIndexr  r  r  axisLocationDictr  axisValueRecordsr  r8  r  r    r    r!   r  =  s,   

r  c           	      C   s   | d }t |tr|S t |trt|d}n2t |tr|}n*t |trD| }|D ]}t |tr>||j||j	|j
|j q)td|S td|j|| |||dS )Nrg  )enz*value must be a list of STATNameStatementsz$value must be int, str, dict or list)r  r  r  	minNameID)r>   r?   r   r  r   _findUnusedNameIDr   setNamestring
platformID	platEncIDlangID	TypeErroraddMultilingualName)	r  r8  r  r  r  	nameTabler  nameID
nameRecordr    r    r!   r  W  s0   





r  c                 C   sj   |   }td | d< }t  |_}d|_|  t||_	t
||||||_t|||||	|
|_dS )a,  
    Add a 'MATH' table to 'ttFont'.

    'constants' is a dictionary of math constants. The keys are the constant
    names from the MATH table specification (with capital first letter), and the
    values are the constant values as numbers.

    'italicsCorrections' is a dictionary of italic corrections. The keys are the
    glyph names, and the values are the italic corrections as numbers.

    'topAccentAttachments' is a dictionary of top accent attachments. The keys
    are the glyph names, and the values are the top accent horizontal positions
    as numbers.

    'extendedShapes' is a set of extended shape glyphs.

    'mathKerns' is a dictionary of math kerns. The keys are the glyph names, and
    the values are dictionaries. The keys of these dictionaries are the side
    names ('TopRight', 'TopLeft', 'BottomRight', 'BottomLeft'), and the values
    are tuples of two lists. The first list contains the correction heights as
    numbers, and the second list contains the kern values as numbers.

    'minConnectorOverlap' is the minimum connector overlap as a number.

    'vertGlyphVariants' is a dictionary of vertical glyph variants. The keys are
    the glyph names, and the values are tuples of glyph name and full advance height.

    'horizGlyphVariants' is a dictionary of horizontal glyph variants. The keys
    are the glyph names, and the values are tuples of glyph name and full
    advance width.

    'vertGlyphAssembly' is a dictionary of vertical glyph assemblies. The keys
    are the glyph names, and the values are tuples of assembly parts and italics
    correction. The assembly parts are tuples of glyph name, flags, start
    connector length, end connector length, and full advance height.

    'horizGlyphAssembly' is a dictionary of horizontal glyph assemblies. The
    keys are the glyph names, and the values are tuples of assembly parts
    and italics correction. The assembly parts are tuples of glyph name, flags,
    start connector length, end connector length, and full advance width.

    Where a number is expected, an integer or a float can be used. The floats
    will be rounded.

    Example::

        constants = {
            "ScriptPercentScaleDown": 70,
            "ScriptScriptPercentScaleDown": 50,
            "DelimitedSubFormulaMinHeight": 24,
            "DisplayOperatorMinHeight": 60,
            ...
        }
        italicsCorrections = {
            "fitalic-math": 100,
            "fbolditalic-math": 120,
            ...
        }
        topAccentAttachments = {
            "circumflexcomb": 500,
            "acutecomb": 400,
            "A": 300,
            "B": 340,
            ...
        }
        extendedShapes = {"parenleft", "parenright", ...}
        mathKerns = {
            "A": {
                "TopRight": ([-50, -100], [10, 20, 30]),
                "TopLeft": ([50, 100], [10, 20, 30]),
                ...
            },
            ...
        }
        vertGlyphVariants = {
            "parenleft": [("parenleft", 700), ("parenleft.size1", 1000), ...],
            "parenright": [("parenright", 700), ("parenright.size1", 1000), ...],
            ...
        }
        vertGlyphAssembly = {
            "braceleft": [
                (
                    ("braceleft.bottom", 0, 0, 200, 500),
                    ("braceleft.extender", 1, 200, 200, 200)),
                    ("braceleft.middle", 0, 100, 100, 700),
                    ("braceleft.extender", 1, 200, 200, 200),
                    ("braceleft.top", 0, 200, 0, 500),
                ),
                100,
            ],
            ...
        }
    MATHi   N)rI   r   r  r   r  rK   r  r   _buildMathConstantsMathConstants_buildMathGlyphInfoMathGlyphInfo_buildMathVariantsMathVariants)r  	constantsitalicsCorrectionstopAccentAttachmentsextendedShapes	mathKernsminConnectorOverlapvertGlyphVariantshorizGlyphVariantsvertGlyphAssemblyhorizGlyphAssemblyr   mathrK   r    r    r!   buildMathTableu  s*   j

r  c                 C   sb   | sd S t  }| D ]"}t| |jd}|jr't|jt js#J t	|}t
||j| q|S r   )r   r  getConvertersr   r   rg  
tableClass
issubclassMathValueRecord_mathValueRecordr   )r  mathConstantsconvr8  r    r    r!   r    s   r  c                    s  t | |gs
d S t }|   r7t  | }t |_||j_t|j	|j_
 fdd|j	D |j_r\t | }t |_||j_t|j	|j_fdd|j	D |j_|rdt|| |_|rt| | }t |_||j_t|j	|j_g |j_|j	D ]N}t }dD ]>}	|	|| v r|| |	 \}
}t|
t|d ksJ t }t|
|_dd |
D |_dd |D |_t||	 d| q|jj| q|S )	Nc                    rm  r    r  r)   n)r  r    r!   r+     r  z'_buildMathGlyphInfo.<locals>.<listcomp>c                    rm  r    r  r  )r  r    r!   r+   !  r  >   TopLeftTopRight
BottomLeftBottomRightr#   c                 S   r	  r    r  )r)   hr    r    r!   r+   6  s    c                 S   r	  r    r  r[  r    r    r!   r+   9  r~   MathKern)r   r   r  r   r"   r\   MathItalicsCorrectionInfor   r;   r   ItalicsCorrectionCountItalicsCorrectionMathTopAccentAttachmentTopAccentCoverageTopAccentAttachmentCountTopAccentAttachmentExtendedShapeCoverageMathKernInfoMathKernCoverageMathKernCountMathKernInfoRecordsMathKernInfoRecordr  HeightCountCorrectionHeight	KernValuer   rg   )r   r  r  r  r  r  rk   r5  recordsidecorrectionHeights
kernValueskernr    )r  r  r!   r    sX   








r  c                 C   sf   t ||||gs
d S t }|  ||_|s|r#t| ||\|_|_|s'|r1t| ||\|_|_	|S r(   )
r   r   r  r   MinConnectorOverlap_buildMathGlyphConstructionVertGlyphCoverageVertGlyphConstructionHorizGlyphCoverageHorizGlyphConstruction)r   r  r  r  r  r  variantsr    r    r!   r  @  s,   


r  c                 C   sZ  t  }|r||  |r||  t|| }g }|jD ]}t }|  |rT||v rTt|| |_	g |_
|| D ]\}}	t
 }
||
_t|	|
_|j
|
 q=|r||v r|| \}}t |_t||j_t||j_g |j_|D ]+}|\}}}}}	t }
||
_t||
_t||
_t||
_t|	|
_|jj|
 qw|| q||fS r(   )r   rl  r\   r"   r   r   MathGlyphConstructionr   r;   VariantCountMathGlyphVariantRecordVariantGlyphr   AdvanceMeasurementrg   GlyphAssemblyr  r  	PartCountPartRecordsGlyphPartRecordr5  r?   	PartFlagsStartConnectorLengthEndConnectorLengthFullAdvance)r   r  
assembliesr   rk   constructions	glyphNameconstructionvariantNameadvancer  partsicpart	part_namerA   startendr    r    r!   r  g  sF   







r  c                 C   s   t  }t| |_|S r(   )r   r  r   ra  )r8  value_recordr    r    r!   r    s   
r  r-   )NNNr  )Nr$   TT)TT)r   TT)
NNNNNr   NNNN)pcollectionsr   r   rR  osfontTools.misc.fixedToolsr   fontTools.misc.roundToolsr   	fontToolsr   fontTools.ttLib.tablesr   r   fontTools.ttLib.tables.otBaser   r	   r
   r   r   r   fontTools.feaLib.astr   fontTools.otlLib.optimize.gposr   r   fontTools.otlLib.errorr   	functoolsr   loggingr   	getLoggerr   r   r"   LOOKUP_FLAG_RIGHT_TO_LEFTLOOKUP_FLAG_IGNORE_BASE_GLYPHSLOOKUP_FLAG_IGNORE_LIGATURESLOOKUP_FLAG_IGNORE_MARKSr=   rC   objectrD   r   r   r   r   r  r=  rQ  rW  r\  rc  ru  r  r  r  r  r  r9  r  rZ  r   rU  r  r  r  r  rb  r  r  r  r  ro  r  r|  r  r  r  r#  r  r  r>  r  rT  rQ  rR  rh  rd  rS  rl  rs  rn  r{  r}  r  r~  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r    r    r    r!   <module>   s    
'
9c
12  e-P.&5IDH9.@wA 
.$)'*$25	
O
,@R4

."
?


|
+
 
 :'+