
    h                       S r SSKJrJrJr  SSKJrJr  SSKJ	r	J
r
  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJrJrJrJr  SSKJr  SSKJr  SSKJr  SSKJ r   SSK!J"r"  SSK#J$r$  SSKJ%r%  SSK&J'r'  SSK(r(SSK)r)SSK*J+r+  SSK,J-r-  SSK.J/r/  SSK0r0SSK1r1SSK2r2SSK3J4r4J5r5J6r6J7r7J8r8J9r9J:r:  SSK;r;\0Rx                  " S5      r=S r>S r?\)R                  " SSSS9 " S S \85      5       rA\)R                  " SSSS9 " S! S"\A5      5       rB\)R                  " SSSS9 " S# S$\A5      5       rC " S% S&\6\D\A4   5      rE " S' S(\E5      rF " S) S*\E5      rG " S+ S,\/5      rHS- rI SUS. jrJS/ rKS0 rL\MSSSS1.S2 jrN SVS3 jrOSVS4 jrPSVS5 jrQS6 rRS7 rSS8 rT\+S9 5       rUS: rVS; rW\MS<.S= jrXS> rYS? rZ " S@ SA\[5      r\SB r]SC r^SD r_SE r`SF raSG rbSH rcSI rdSJ reSK rfSL rgSS\HR                  S4SSM.SN jjriSO rjSP\5\D   SQ\4\D\7\A   4   4SR jrkSS rlSWST jrmg)Xa  Partially instantiate a variable font.

The module exports an `instantiateVariableFont` function and CLI that allow to
create full instances (i.e. static fonts) from variable fonts, as well as "partial"
variable fonts that only contain a subset of the original variation space.

For example, if you wish to pin the width axis to a given location while also
restricting the weight axis to 400..700 range, you can do:

.. code-block:: sh

    $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700

See `fonttools varLib.instancer --help` for more info on the CLI options.

The module's entry point is the `instantiateVariableFont` function, which takes
a TTFont object and a dict specifying either axis coodinates or (min, max) ranges,
and returns a new TTFont representing either a partial VF, or full instance if all
the VF axes were given an explicit coordinate.

E.g. here's how to pin the wght axis at a given location in a wght+wdth variable
font, keeping only the deltas associated with the wdth axis:
.. code-block:: pycon

    >>>
    >> from fontTools import ttLib
    >> from fontTools.varLib import instancer
    >> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
    >> [a.axisTag for a in varfont["fvar"].axes]  # the varfont's current axes
    ['wght', 'wdth']
    >> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
    >> [a.axisTag for a in partial["fvar"].axes]  # axes left after pinning 'wght'
    ['wdth']

If the input location specifies all the axes, the resulting instance is no longer
'variable' (same as using fontools varLib.mutator):
.. code-block:: pycon

    >>>    
    >> instance = instancer.instantiateVariableFont(
    ...     varfont, {"wght": 700, "wdth": 67.5}
    ... )
    >> "fvar" not in instance
    True

If one just want to drop an axis at the default location, without knowing in
advance what the default value for that axis is, one can pass a `None` value:
.. code-block:: pycon

    >>>
    >> instance = instancer.instantiateVariableFont(varfont, {"wght": None})
    >> len(varfont["fvar"].axes)
    1

From the console script, this is equivalent to passing `wght=drop` as input.

This module is similar to fontTools.varLib.mutator, which it's intended to supersede.
Note that, unlike varLib.mutator, when an axis is not mentioned in the input
location, the varLib.instancer will keep the axis and the corresponding deltas,
whereas mutator implicitly drops the axis at its default coordinate.

The module supports all the following "levels" of instancing, which can of
course be combined:

L1
    dropping one or more axes while leaving the default tables unmodified;
    .. code-block:: pycon

        >>>
        >> font = instancer.instantiateVariableFont(varfont, {"wght": None})

L2
    dropping one or more axes while pinning them at non-default locations;
    .. code-block:: pycon
    
        >>>
        >> font = instancer.instantiateVariableFont(varfont, {"wght": 700})

L3
    restricting the range of variation of one or more axes, by setting either
    a new minimum or maximum, potentially -- though not necessarily -- dropping
    entire regions of variations that fall completely outside this new range.
    .. code-block:: pycon
    
        >>>
        >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)})

L4
    moving the default location of an axis, by specifying (min,defalt,max) values:
    .. code-block:: pycon
    
        >>>
        >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)})

Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table)
are supported, but support for CFF2 variable fonts will be added soon.

The discussion and implementation of these features are tracked at
https://github.com/fonttools/fonttools/issues/1537
    )floatToFixedToFloatstrToFixedToFloatotRound)normalizeValuepiecewiseLinearMap)TTFontnewTable)TupleVariation)_g_l_y_f)varLib)subset)privateDictOperators2)programToCommandscommandsToProgramspecializeCommandsgeneralizeCommands)builder)MVAR_ENTRIES)MutatorMerger)names   )instantiateFeatureVariations)makeOutputFileName)solver)VarComponentFlagsN)contextmanager)deepcopy)IntEnum)DictIterableMappingOptionalSequenceTupleUnionzfontTools.varLib.instancerc                 P    [         R                  " S[        SS9  [        U S U5      $ )Nz/AxisRange is deprecated; use AxisTriple instead   
stacklevel)warningswarnDeprecationWarning
AxisTripleminimummaximums     U/var/www/html/env/lib/python3.13/site-packages/fontTools/varLib/instancer/__init__.py	AxisRanger2      s(    MM9
 gtW--    c                 P    [         R                  " S[        SS9  [        U S U5      $ )Nz9NormalizedAxisRange is deprecated; use AxisTriple insteadr'   r(   )r*   r+   r,   NormalizedAxisTripler.   s     r1   NormalizedAxisRanger6      s(    MMC
  w77r3   TF)frozenorderreprc            
           \ rS rSr% Sr\\   \S'   \\   \S'   \\   \S'   S rS r	S r
S	 rS
 r\S\S \\\\4   \\\\4   4   SS 4S j5       rSS jrSrg)r-      zA triple of (min, default, max) axis values.

Any of the values can be None, in which case the limitRangeAndPopulateDefaults()
method can be used to fill in the missing values based on the fvar axis values.
r/   defaultr0   c           
      `   U R                   c;  U R                  U R                  :X  a!  [        R	                  U SU R                  5        U R                  b'  U R                   b  U R                  U R                   :  dh  U R                   b'  U R                  b  U R                   U R                  :  d4  U R                  bq  U R                  bc  U R                  U R                  :  aH  [        [        U 5      R                   SU R                   SU R                    SU R                   S35      eg g g )Nr<   z
 minimum (z), default (z), maximum (z) must be in sorted order)r<   r/   r0   object__setattr__
ValueErrortype__name__selfs    r1   __post_init__AxisTriple.__post_init__   s   <<DLLDLL$@tY= (LL,LL4<</ (LL,LL4<</ (LL,LL4<</ :&&'z$,,|DLL>Yefjfrfres  tM  N  0 - )r3   c                 ^    [         R                  " U 5      n[        XU   R                  5      $ N)dataclassesfieldsgetattrname)rD   irJ   s      r1   __getitem__AxisTriple.__getitem__   s%    ##D)tAY^^,,r3   c                 @    [        [        R                  " U 5      5      $ rH   )lenrI   rJ   rC   s    r1   __len__AxisTriple.__len__   s    ;%%d+,,r3   c                 0    [         R                  " U 40 UD6$ rH   )rI   replace)rD   kwargss     r1   _replaceAxisTriple._replace   s    ""42622r3   c                 :    SSR                  S U  5       5       S3$ )N(, c              3   B   #    U  H  ob  [        US5      OSv   M     g 7f)NgNone)format.0vs     r1   	<genexpr>&AxisTriple.__repr__.<locals>.<genexpr>   s     Tt!M&C.vEt   ))joinrC   s    r1   __repr__AxisTriple.__repr__   s$    		TtTTUUVW	
r3   rb   returnc                 H   [        X5      (       a  U$ [        U[        [        45      (       a	  U " XU5      $  [        U5      nSnUS:X  a  Uu  pVOUS:  a  U " U6 $ [        SU SU< 35      eU " XTU5      $ ! [         a!  n[        S[        U5       SU< 35      UeSnAff = f)zConvert a single value or a tuple into an AxisTriple.

If the input is a single value, it is interpreted as a pin at that value.
If the input is a tuple, it is interpreted as (min, max) or (min, default, max).
z-expected float, 2- or 3-tuple of floats; got : Nr'      z!expected sequence of 2 or 3; got )
isinstanceintfloatrQ   	TypeErrorr@   rA   )clsrb   ner<   r/   r0   s          r1   expandAxisTriple.expand   s     aHa#u&&qQ<	AA
 6 GW!V7N@2aUKLL7W--  	?Qy1%P	s   A6 6
B! BB!c                 ,   U R                   nUc  US   nU R                  nUc  US   nU R                  nUc  US   n[        X!S   5      n[        XAS   5      n[	        X!S   5      n[	        XAS   5      n[        U[	        XC5      5      n[        X#U5      $ )a  Return a new AxisTriple with the default value filled in.

Set default to fvar axis default if the latter is within the min/max range,
otherwise set default to the min or max value, whichever is closer to the
fvar axis default.
If the default value is already set, return self.
r   r   r'   )r/   r<   r0   maxminr-   )rD   
fvarTripler/   r<   r0   s        r1   limitRangeAndPopulateDefaults(AxisTriple.limitRangeAndPopulateDefaults   s     ,,? mG,,? mG,,? mGg!}-g!}-g!}-g!}-gs745'G44r3    N)rj   r-   )rB   
__module____qualname____firstlineno____doc__r"   rp   __annotations__rE   rN   rR   rW   rh   classmethodr%   r$   ru   r{   __static_attributes__r}   r3   r1   r-   r-      s     e_e_e_0--3

 .%,%%&(
. 
. .B5r3   r-   c                   >    \ rS rSr% Sr\\S'   \\S'   \\S'   S rSrg)	r5   i  z7A triple of (min, default, max) normalized axis values.r/   r<   r0   c                 ~   U R                   c?  [        R                  U S[        U R                  [        U R                  S5      5      5        SU R                  s=::  a(  U R                   s=::  a  U R                  s=::  a  S::  d8  O  [        SU R                  S SU R                   S SU R                  S S	35      eg 
Nr<   r               ?z8Normalized axis values not in -1..+1 range; got minimum=r]   z
, default=z
, maximum=rf   r<   r>   r?   rx   r/   ry   r0   r@   rC   s    r1   rE   "NormalizedAxisTriple.__post_init__      <<tYDLL#dllTUBV0WXKKKK<<**T\\!4DJt||\]N^^_a  Lr3   r}   N)	rB   r~   r   r   r   rp   r   rE   r   r}   r3   r1   r5   r5     s    ANNNr3   r5   c                   v    \ rS rSr% Sr\\S'   \\S'   \\S'   Sr\\   \S'   Sr	\\   \S'   S	 r
S
 rSS jrSrg) NormalizedAxisTripleAndDistancesi&  zA triple of (min, default, max) normalized axis values,
with distances between min and default, and default and max,
in the *pre-normalized* space.r/   r<   r0   r   distanceNegativedistancePositivec                 ~   U R                   c?  [        R                  U S[        U R                  [        U R                  S5      5      5        SU R                  s=::  a(  U R                   s=::  a  U R                  s=::  a  S::  d8  O  [        SU R                  S SU R                   S SU R                  S S	35      eg r   r   rC   s    r1   rE   .NormalizedAxisTripleAndDistances.__post_init__2  r   r3   c                 T    U nU R                  US   * US   * US   * US   US   5      $ )Nr'   r   r      rm   )	__class__)rD   rb   s     r1   reverse_negate/NormalizedAxisTripleAndDistances.reverse_negate;  s8    ~~qteadUQqTE1Q41>>r3   c                 L   U u  p4pVnX4s=::  a  U::  d   e   eU(       d  [        U[        XQ5      5      nX:X  a  gUS:  a   U R                  5       R                  U* US9* $ X:  a	  X-
  XT-
  -  $ US:  a	  X-
  XC-
  -  $ Xc* -  Xt-  -   nUS:  a  XA-
  U-  n	OU* U-  Xt-  -   n	U	* U-  $ )zRenormalizes a normalized value v to the range of this axis,
considering the pre-normalized distances as well as the new
axis limits.r   )extrapolate)rx   ry   r   renormalizeValue)
rD   rb   r   lowerr<   upperr   r   totalDistance	vDistances
             r1   r   1NormalizedAxisTripleAndDistances.renormalizeValue?  s    
 EIA1A(5(((((E3u=)A<Q;'')::A2;:WWW ;KEO44 A:KGO44 )614D4NN6 (88I--0@0JJIzM))r3   r}   NT)rB   r~   r   r   r   rp   r   r   r"   r   rE   r   r   r   r}   r3   r1   r   r   &  sE    & NNN()huo)()huo)?$*r3   r   c                       \ rS rSrS\S\4S jrS\\   4S jrS\	4S jr
S\4S jrS\4S jrS\\\4   4S	 jrS\\\4   4S
 jrSrg)_BaseAxisLimitsif  keyrj   c                      U R                   U   $ rH   _data)rD   r   s     r1   rN   _BaseAxisLimits.__getitem__g  s    zz#r3   c                 ,    [        U R                  5      $ rH   )iterr   rC   s    r1   __iter___BaseAxisLimits.__iter__j  s    DJJr3   c                 ,    [        U R                  5      $ rH   )rQ   r   rC   s    r1   rR   _BaseAxisLimits.__len__m      4::r3   c                 N    [        U 5      R                   SU R                  < S3$ )NrZ   rf   )rA   rB   r   rC   s    r1   rh   _BaseAxisLimits.__repr__p  s$    t*%%&a

~Q77r3   c                 ,    [        U R                  5      $ rH   )strr   rC   s    r1   __str___BaseAxisLimits.__str__s  r   r3   c                 l    U R                  5        VVs0 s H  u  pXR                  _M     snn$ s  snnf )z%Return a dict of default axis values.)itemsr<   rD   krb   s      r1   defaultLocation_BaseAxisLimits.defaultLocationv  s(    )-699666s   0c                     U R                  5        VVs0 s H-  u  pUR                  UR                  :X  d  M!  XR                  _M/     snn$ s  snnf )z1Return a location dict with only the pinned axes.)r   r/   r0   r<   r   s      r1   pinnedLocation_BaseAxisLimits.pinnedLocationz  s9    )-Paii9O99PPPs
    AAr}   N)rB   r~   r   r   r   r-   rN   r    r   ro   rR   rh   r   r   rp   r   r   r   r}   r3   r1   r   r   f  su    s z  (3-   8# 8 7c5j!1 7QS%Z 0 Qr3   r   c                   6    \ rS rSrSrS rSS jrS	S
S jjrSrg)
AxisLimitsi  z*Maps axis tags (str) to AxisTriple values.c                     0 =U l         n[        U0 UD6R                  5        H(  u  pEUc  XSU'   M   [        R	                  U5      nXcU'   M*     g ! [
         a  n[        SU< SU< 35      UeS nAff = fNzInvalid axis limits for rl   )r   dictr   r-   ru   r@   rD   argsrV   datar   rb   triplert   s           r1   __init__AxisLimits.__init__  s    
T$)&)//1DAyQU'..q1F !Q 2 " U$'?uBqe%LMSTTUs   A
A3A..A3c                 Z   US   nUR                    Vs0 s H0  o3R                  UR                  UR                  UR                  4_M2     nn0 nU R                  5        H4  u  pgXF   nUS   n	Uc  [        XU	5      XV'   M!  UR                  U5      XV'   M6     [        U 5      " U5      $ s  snf )zyReturn a new AxisLimits with defaults filled in from fvar table.

If all axis limits already have defaults, return self.
fvarr   )	axesaxisTagminValuedefaultValuemaxValuer   r-   r{   rA   )
rD   varfontr   afvarTriples	newLimitsr   r   rz   r<   s
             r1   limitAxesAndPopulateDefaults'AxisLimits.limitAxesAndPopulateDefaults  s    
 vIM
IRAII

ANNAJJ?? 	 
 	#zz|OG$-J mG~%/'%J	"%+%I%I*%U	"  , Dz)$$
s   7B(c                   ^^ US   n[        U R                  5       5      R                  S UR                   5       5      nU(       a  [	        SR                  U5      5      eUR                   Vs0 s HC  nUR                  U ;   d  M  UR                  UR                  UR                  UR                  4_ME     nn0 nU(       a  SU;   a  US   R                  n0 nUR                  5        Hr  u  n	mTS   TS   -
  n
TS   TS   -
  nX	   c  [        SSSX5      X'   M3  X	   u  pnUc  TS   nUR                  U	S5      m[        / UU4S	 jXU4 5       QU
PUP76 X'   Mt     [        U5      $ s  snf )
zReturn a new NormalizedAxisLimits with normalized -1..0..+1 values.

If usingAvar is True, the avar table is used to warp the default normalization.
r   c              3   8   #    U  H  oR                   v   M     g 7frH   r   )ra   r   s     r1   rc   'AxisLimits.normalize.<locals>.<genexpr>  s     /M9a		9   z$Cannot limit: {} not present in fvaravarr   r   r'   Nc              3   >   >#    U  H  n[        UTT5      v   M     g 7frH   )	normalize)ra   rb   avarMappingr   s     r1   rc   r     s     T=S)Av{33=Ss   )setkeys
differencer   r@   r_   r   r   r   r   segmentsr   r   getNormalizedAxisLimits)rD   r   	usingAvarr   	badLimitsr   r   avarSegmentsnormalizedLimitsaxis_tagr   r   minVdefaultVmaxVr   r   s                  @@r1   r   AxisLimits.normalize  s   
 v		$///M499/MM	CJJ9UVV YY
yyD  @AII

ANNAJJ?? 	 
 7*"6?33L $

Hf%ay6!94%ay6!94~%-Mq!-. * #'> DD!!9&**8T:K)I *Tdd=ST* * !*&! !-, $$455E
s   0E-2E-r   N)rj   r   r   )rj   r   )	rB   r~   r   r   r   r   r   r   r   r}   r3   r1   r   r     s    4!%&,6 ,6r3   r   c                       \ rS rSrSrS rSrg)r   i  z4Maps axis tags (str) to NormalizedAxisTriple values.c                     0 =U l         n[        U0 UD6R                  5        H  u  pE [        R	                  U5      nXcU'   M!     g ! [
         a  n[        SU< SU< 35      UeS nAff = fr   )r   r   r   r   ru   r@   r   s           r1   r   NormalizedAxisLimits.__init__  s{    
T$)&)//1DAQ9@@C G 2  Q #;A51%!HIqPQs   A
A*A%%A*r   N)rB   r~   r   r   r   r   r   r}   r3   r1   r   r     s
    >r3   r   c                   $    \ rS rSrSrSrSrSrSrg)OverlapModei  r   r   r'   rm   r}   N)	rB   r~   r   r   KEEP_AND_DONT_SET_FLAGSKEEP_AND_SET_FLAGSREMOVEREMOVE_AND_IGNORE_ERRORSr   r}   r3   r1   r   r     s    F r3   r   c                 V  ^^ [         R                  S5        U S   R                  nSU ;   a  U S   R                  O/ mTR	                  5       n[        T5       VVs/ s H  u  pEUR                  U;  d  M  UPM     nnn[        U5       VVs0 s H  u  ptXG_M	     nnnUR                  (       ag  UR                  R                  n	[        U	5       HB  u  pJ[        UU4S jU
 5       5      (       a  [        S5      eU
 Vs/ s H  oxU   PM	     snX'   MD     UR                  nU(       ap  UR                  R                   HU  n/ nUR                   H@  nTUR                     R                  nUT;   a  [        S5      eXR                     Ul        MB     MW     g g s  snnf s  snnf s  snf )NzInstantiating VARC tablesVARCr   c              3   H   >#    U  H  nTU   R                   T;   v   M     g 7frH   r   )ra   j
axisLimitsfvarAxess     r1   rc   "instantiateVARC.<locals>.<genexpr>  s      Jk8A;&&*4ks   "z5Instancing across VarComponent axes is not supported.)loginfotabler   r   	enumerater   AxisIndicesListItemanyNotImplementedErrorMultiVarStoreSparseVarRegionListRegionSparseVarRegionAxis	AxisIndex)r   r   varclocationrM   axisaxisMapr   reverseAxisMapaxisIndicesListaxisIndicesstoreregionnewRegionAxisregionRecordtagr   s    `              @r1   instantiateVARCr    s   HH() 6?  D'-'8wv##bH((*H )( 3T 3WQt||87Sq 3GT'0'9:'9tqad'9N:..33'8NAJkJJJ)K  >I!I["3[!IO 9 E//66FM & : :|556>>*$-O  *88N8N)O& !; 7  U: "Js   F6FF ?F&c                    [        X5      n[        R                  " 5       nU HQ  nUb  UR                  X#5        [	        UR
                  R                  5       5      nXu;   a  XW==   U-  ss'   MM  XeU'   MS     UR                  [	        5       S5      nUR                  5        H  nUR                  5         M     [        UR                  5       5      U SS& Ub  UR                  $ / $ )a  Instantiate TupleVariation list at the given location, or limit axes' min/max.

The 'variations' list of TupleVariation objects is modified in-place.
The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples
specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes
have minimum == default == maximum.

A 'full' instance (i.e. static font) is produced when all the axes are pinned to
single coordinates; a 'partial' instance (i.e. a less variable font) is produced
when some of the axes are omitted, or restricted with a new range.

Tuples that do not participate are kept as they are. Those that have 0 influence
at the given location are removed from the variation store.
Those that are fully instantiated (i.e. all their axes are being pinned) are also
removed from the variation store, their scaled deltas accummulated and returned, so
that they can be added by the caller to the default instance's coordinates.
Tuples that are only partially instantiated (i.e. not all the axes that they
participate in are being pinned) are kept in the store, and their deltas multiplied
by the scalar support of the axes to be pinned at the desired location.

Args:
    variations: List[TupleVariation] from either 'gvar' or 'cvar'.
    axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max)
        normalized coordinates for the full or partial instance.
    origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar'
        inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).
    endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas.

Returns:
    List[float]: the overall delta adjustment after applicable deltas were summed.
N)changeTupleVariationsAxisLimitscollectionsOrderedDictcalcInferredDeltas	frozensetr   r   popvaluesroundDeltaslistcoordinates)	
variationsr   
origCoordsendPtsnewVariationsmergedVariationsvarr   
defaultVars	            r1   instantiateTupleVariationStorer*  	  s    F 4JKM"..0!"":6 )*#"c)"%(T"  "%%ik48J&&( ))0023JqM%/%;:!!CCr3   c           	          [        UR                  5       5       H-  u  p#/ nU  H  nUR                  [        XRU5      5        M      Un M/     U $ rH   )sortedr   extendchangeTupleVariationAxisLimit)r#  r   r   	axisLimitr&  r(  s         r1   r  r  F  sO    $Z%5%5%78C  !>sY!WX "
	 9
 r3   c                    [        U[        5      (       d   eU R                  R                  US5      u  p4nUS:X  a  XR                  ;   a  U R                  U	 U /$ X4s=::  a  U::  a  O  / $ US:  a  US:  a  / $ XR                  ;  a  U /$ U R                  U   n[        R
                  " Xb5      n/ nU H  u  p[        U5      S:  a   [        U R                  U R                  5      OU n
Uc  U
R                  R                  U5        OUS   S:w  d   U5       eXjR                  U'   X-  n
UR                  U
5        M     U$ )N)r   r   r   r   )rn   r   r   r   r   
rebaseTentrQ   r
   r"  r  append)r(  r   r/  r   peakr   tent	solutionsoutscalarnewVars              r1   r.  r.  O  s3   i!ABBBB gz:Eqy hh!u"U"	 ).	eai	hhu88GD!!$2I
C!9<Y!9KN388S__5QT 	 <KKOOG$7a<%%<#'KK 

6 " Jr3   )round
specialize
generalize	downgradec                  ^^%^&^'^(^) [         R                  S5        U S   R                  nU S   R                  nUR                  S   nUR
                  R                  m(T((       d  U(       a  SSKJn	  U	" U 5        g UR                  5         U(4S jm&UR                  R                  5       n
[        5       n/ nUR                   HK  nUR                  U;  d  M  UR                  UR                  5        UR!                  UR                  5        MM     / nU
 Hu  nUR"                  R$                  R                  T(L d   e['        UR(                  T&S9nU(       a  [+        U5      nU(       a  [-        UU(       + S9nUR!                  U5        Mw     U&U(U)4S	 jnU%U&UU'U(U)4S
 jnT(R.                   H'  nUR0                  / :X  d   eUR2                  S:X  a  M'   e   U H5  nSm)U H*  nUS   S:X  a
  US   S   m)M  US    H  nU" U5        M     M,     M7     Sm)[4         H  u  nnnnnUS;  a  M  Sm)U H  n[7        UU5      (       d  M  [9        UU5      nUS:X  a  US   m)M/  US:X  a  U/nU HZ  n[;        U[<        5      (       d  M  [?        U5      T&" T)5      S-   -  S:X  d   e[?        U5      T&" T)5      S-   -  nU" UU/-   5        M\     M     M     [A        T(Xa5      m%S/[?        T(R.                  5      -  m'U HN  nSm)U HC  nUS   S:X  a
  US   S   m)M  / nUS    H  nURC                  U" U5      5        M     UUS   S S & ME     MP     [4         H  u  nnnnnUS;  a  M  U H  n[7        UU5      (       d  M  [9        UU5      nUS:X  a  U/n/ n U H\  n[;        U[<        5      (       d  U R!                  U5        M+  UR!                  S5        U" U5      nU RC                  S U 5       5        M^     US:X  a  U S   n [E        UUU 5        M     M     [G        T(R.                  5       H=  u  n!nT'U!   UR2                  :X  d   T'U!   UR2                  45       e/ Ul        SUl        M?     [        5       n"U H  n[I        S U 5       5      (       aM  Sm)U HC  nUS   S:X  a
  US   S   m)M  [I        S US    5       5      (       d  M2  U"R                  T)5        ME     Mg  U Vs/ s H  nUS   S:w  d  M  UPM     snUS S & M     [G        [K        U"5      5       V!V#s0 s H	  u  n!n#U#U!_M     n$n!n#[G        T(R.                  5       V!Vs/ s H  u  n!nU!U";   d  M  UPM     snn!T(l        [?        T(R.                  5      T(l&        U H(  nU H  nUS   S:X  d  M  U$US   S      US   S'   M!     M*     U H+  nU(       d  M  US   SS/4:X  d  M  URO                  S5        M-     [Q        X5       H  u  nn[S        U5      Ul        M     T(R.                  (       dM  SURT                  ;   a  URT                  S	 U?UR                  ?+U H  nU?M     U(       a  SSKJn	  U	" U 5        g g g s  snf s  sn#n!f s  snn!f )NzInstantiating CFF2 tabler   CFF2r   )convertCFF2ToCFFc                 X   > TR                   U b  U    R                  $ S   R                  $ Nr   )VarDataVarRegionCount)vsindexvarStores    r1   getNumRegions&instantiateCFF2.<locals>.getNumRegions  s-    7+>FUUUAFUUUr3   )rG  )generalizeFirstc                   > [        U [        5      (       d  g [        S U S S  5       5      (       a  [        S5      eU S   n[	        U 5      S-
  U-  S:X  d   e[	        U 5      S-
  U-  S-
  nUT" T5      :X  d   e[        U[	        U 5      S-
  U5       HY  nXX2-    n[	        U5      U:X  d   eTR                  T   nUR                  R                  U5        U=R                  S-  sl	        M[     g )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7frH   rn   r!  ra   subargs     r1   rc   AinstantiateCFF2.<locals>.storeBlendsToVarStore.<locals>.<genexpr>       ?hFz&$''hre   r1  &Nested blend lists not supported (yet)r   r   )
rn   r!  r  r  rQ   rangerC  r  r3  	ItemCount)	argcountnRegionsrM   deltasvarDatarG  rF  rE  s	         r1   storeBlendsToVarStore.instantiateCFF2.<locals>.storeBlendsToVarStore  s    #t$$?c#2h???%&NOOBC1%***HqLU*Q.=1111uc#hlH5AQ\*Fv;(***&&w/GLL'" 6r3   c                   > [        U [        5      (       d  U /$ [        S U S S  5       5      (       a  [        S5      eU S   n[	        U 5      S-
  U-  S:X  d   eT" T5      n/ n/ n[        U5       H  nX   nTnTU   nTU==   S-  ss'   US-  U-   n	UT" TU	   5      -  nUR                  U5        TR                  U   n
U
R                  U   n[	        U5      U:X  d   eUR                  U5        M     U(       d  U$ X4-   U/-   /$ )Nc              3   B   #    U  H  n[        U[        5      v   M     g 7frH   rL  rM  s     r1   rc   CinstantiateCFF2.<locals>.fetchBlendsFromVarStore.<locals>.<genexpr>  rP  re   r1  rQ  r   r      )
rn   r!  r  r  rQ   rR  r3  rC  r  r-  )rT  rU  
numRegionsnewDefaults	newDeltasrM   r   majorminorvarIdxrX  rW  defaultDeltasrG  r:  varDataCursorrF  rE  s               r1   fetchBlendsFromVarStore0instantiateCFF2.<locals>.fetchBlendsFromVarStore  s2   #t$$5L?c#2h???%&NOOBC1%***"7+
	uA6LE!%(E% A% rkU*FE-"788L|,&&u-G\\%(Fv;*,,,V$ " '5'122r3   rE  r   )numberdeltaarrayri  c              3   Z   #    U  H!  n[        U[        5      (       a  US S OUv   M#     g 7f)Nr1  rL  r`   s     r1   rc   "instantiateCFF2.<locals>.<genexpr>1  s'      Uu!:a+>+>3BA!Eu   )+c              3   Z   #    U  H!  oS      H  n[        U[        5      v   M     M#     g7f)r   NrL  )ra   commandrT  s      r1   rc   rm  D  s&     SHPQ
z#t$$
$Hrn  c              3   B   #    U  H  n[        U[        5      v   M     g 7frH   rL  )ra   rT  s     r1   rc   rm  J  s     C
z#t,,
re   VarStore),r   r   r   cfftopDictIndexrr  
otVarStorefontTools.cffLib.CFF2ToCFFr@  desubroutinizeCharStringsr  r   FDArrayPrivateaddr3  privatevstorer   programr   r   rC  r  rS  r   hasattrrK   rn   r!  rQ   instantiateItemVariationStorer-  setattrr  r  r,  VarDataCountr  zipr   rawDictrF  )*r   r   r:  r;  r<  r=  r   rs  topDictr@  charStringsuniquePrivateDictsprivateDictsfdallCommandscscommandsrY  rg  rX  rp  rT  opcoderL   arg_typer<   	converterr|  r  valuerU  newArgs	newValuesrM   usedVsindexrb   vsindexMappingre  rG  rf  rF  rE  s*     `                                  @@@@@r1   instantiateCFF2r  u  sq   & HH'(v##H
&/

Cq!G**HCW%V %%,,.K Loo:://""2::.

+ 
 Kzz  ++x777$RZZ}M)(3H)(
NSH8$ #$ 3  3F ##||r!!!  A%%% $
  GqzY&!!*Q-qz%c* "	     G6K2h77#G7D))Wd+Fy  )8# !%..5z]7%;a%?@AEEEE
}W'='AB%eugo6   $ 7L4 2(HQM C#h..//MGqzY&!!*Q-Gqz6s;< "#GAJqM     7L2h77#G7D))Wd+F8# I!%..$$U+Q/6   Uu UU   8#%aL	GT9-) $	 7L6   0 01
7Q7#4#44 	
!7
 	
4  2 %KSHSSSG#1:*%ajmGC
CCCOOG, $ 3;V(wgajI>U7(VHQK   (11D'EF'Etq!ad'ENF"+H,<,<"="=JAwkAQ"=H   0 01HGqzY& .wqz!} =
1      8	A3'77LLO  
 K5H&x0
 6 (
+(#G $ CW%  / W Gs    Y 1Y Y%Y+Y+c                    UR                  XU5      u  pxUR                  n	UR                  R                  U 5      n
U
(       a,  [	        XXy5      nU(       a  U[
        R                  " U5      -  nUR                  XX45        U
(       d  XR                  ;   a  UR                  U 	 g U(       a<  UR                  5         X   R                  5       nU
 H  nUR                  XyUS9  M     g g )N)isComposite)_getCoordinatesAndControlsr%  r#  r   r*  r   GlyphCoordinates_setCoordinatestoIntr  optimize)	glyphnameglyfgvarhMetricsvMetricsr   r  r"  ctrlr%  tupleVarStorere  r  r(  s                 r1   _instantiateGvarGlyphr  r  s     77	XVK[[F OO''	2M6{
 844]CCK 	D'	* 	o113 CLL+LF ! r3   c           
          U S   nU S   nU S   R                   n[        U R                  S5      SS5      n[        XXFXrUS9  g)z8Remove?
https://github.com/fonttools/fonttools/pull/2266r  r  hmtxvmtxmetricsNr  )r  rK   r   r  )r   r  r   r  r  r  r  r  s           r1   instantiateGvarGlyphr    sM     6?D6?Dv&&Hw{{6*It<Hr3   c                    ^ [         R                  S5        U S   nU S   mU S   R                  n[        U R	                  S5      SS 5      n[        TR                  U4S jS9nU H  n[        UTX4XQUS	9  M     UR                  (       d  U S	 g g )
NzInstantiating glyf/gvar tablesr  r  r  r  r  c                 |   > TU    R                  5       (       a   TU    R                  T5      R                  U 4$ SU 4$ rB  )r  getCompositeMaxpValuesmaxComponentDepth)rL   r  s    r1   <lambda>!instantiateGvar.<locals>.<lambda>  sI     :))++ T
11$7II 
 
r3   )r   r  )	r   r   r  rK   r   r,  
glyphOrderr  r#  )	r   r   r  r  r  r  
glyphnamesr  r  s	           @r1   instantiateGvarr    s    HH-.6?D6?Dv&&Hw{{6*It<H
 

J  	tTXH	
  
 ??FO r3   c                 h    [        U5       H#  u  p#U(       d  M  X==   [        U5      -  ss'   M%     g rH   )r  r   )cvtrW  rM   rj  s       r1   setCvarDeltasr    s(    f%5Fgen$F &r3   c                     [         R                  S5        U S   n[        UR                  U5      nU(       a  [	        U S   U5        UR                  (       d  U S	 g g )NzInstantiating cvt/cvar tablescvarzcvt )r   r   r*  r#  r  )r   r   r  re  s       r1   instantiateCvarr    sL    HH,-6?D24??JOMgfo}5??FO r3   c           	         U S   R                   nUR                  nU Hc  nUR                  nU[        ;  a  M  [        U   u  pgXR                     nUS:w  d  M<  [        X   U[        X   U5      [        U5      -   5        Me     g )NMVARr   )r   ValueRecordValueTagr   VarIdxr  rK   r   )	r   rW  mvarrecordsrecmvarTagtableTagitemNamerj  s	            r1   setMvarDeltasr    s    6?  DG,,,&)'2zz"A:!)84wu~E r3   c              #   X  #    S Vs/ s H  n[        U S   U5      PM     nnUS Vs/ s H  n[        U S   U5      PM     sn:H  nUv   U(       aJ  S Vs/ s H  n[        U S   U5      PM     nnX$:w  a%  [        SU5       H  u  p[        U S   X5        M     gggs  snf s  snf s  snf 7f)a  Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.

When applying MVAR deltas to the OS/2 table, if the ascender, descender and
line gap change but they were the same as the respective hhea metrics in the
original font, this context manager ensures that hhea metrcs also get updated
accordingly.
The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
to have the hhea metrics be equal to those for compat reasons.

https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
https://github.com/fonttools/fonttools/issues/3297
)sTypoAscendersTypoDescendersTypoLineGapOS/2)ascender	descenderlineGaphheaN)rK   r  r  )r   attrcurrent_os2_vmetricsmetrics_are_syncednew_os2_vmetricsr  s         r1   verticalMetricsKeptInSyncr    s     " HGD 	&G   .3W23W4&3W2   L
K GFOT*K 	 
  3"46F  5  4 2
s&   B*BB*B  B*B%-=B*c                    [         R                  S5        U S   R                  nU S   R                  nUR                  n[        XCU5      n[        U 5         [        X5        S S S 5        UR                  R                  (       a7  UR                  5       nUR                   H  nXgR                     Ul        M     g U S	 g ! , (       d  f       Nd= f)NzInstantiating MVAR tabler  r   )r   r   r   r   rr  r  r  r  VarRegionListr  r  r  r  )r   r   r  r   rF  re  varIndexMappingr  s           r1   instantiateMVARr    s    HH'(6?  Dv##H}}H1(jQM	"7	+g- 
, $$"++-##C(4CJ $ FO 
,	+s   C
Cc                     [        X5      R                  nU Vs/ s H	  oRXE      PM     nn[        X[        R                  " Xc5      5        g s  snf rH   )rK   mappingr  r   buildVarIdxMap)r   attrNamer  r  
oldMapping	glyphName
newMappings          r1   _remapVarIdxMapr  ,  sG    )11JJTU*Y*"78*JUEW33JKL Vs   A)r:  c                l   UR                  5       nUR                  nU S   R                  n[        R	                  SU5        X   R
                  nUR                  nSU ;   a?  [        U5      R                  S U 5       5      (       a  [        R	                  SU5        X	 g [        XU5      n	SU ;  a  US:X  a  SOSn
X;   a  [        XrR                  5      nX
   nUR                  nUR                  5        HB  u  nu  nnU(       a  UR                  U   nOU R                  U5      nX" U	U   5      -   U4X'   MD     US:X  a+  [        XrR                   5      b  [        R#                  S	5        [        U5      R                  S
 U 5       5      (       a  [        R	                  SU5        X	 g UR$                  R&                  (       a  [        XrR                  5      (       a  UR)                  SS9nU R+                  5       n[-        XrR                  UU5        [        XrR.                  5      (       a  [-        XrR.                  UU5        [        XrR0                  5      (       a  [-        XrR0                  UU5        US:X  a3  [        XrR                   5      (       a  [-        XrR                   UU5        g g g g g )Nr   zInstantiating %s tabler  c              3   8   #    U  H  oR                   v   M     g 7frH   r   ra   r  s     r1   rc   $_instantiateVHVAR.<locals>.<genexpr>?  s     #FXTLLXr   zDropping %s tableVVARr  r  z;VORG table not yet updated to reflect changes in VVAR tablec              3   8   #    U  H  oR                   v   M     g 7frH   r   r  s     r1   rc   r  b  s     'Jr   F)use_NO_VARIATION_INDEX)r   r  r   r   r   r   rr  r   
issupersetr  rK   
advMappingr  r   r  
getGlyphIDvOrigMappingwarningr  r  r  getGlyphOrderr  sb1sb2)r   r   tableFieldsr:  r  r  r   vhvarrF  re  
metricsTagr  metricsTabler  r  advanceWidthsbrd  r  r  s                       r1   _instantiateVHVARr  3  sg   ((*H##Hv##HHH%x0##E~~H x=###FX#FFFHH((3!1(jQMW  (61Vv
  (>(>?J".L"**G18-	-L"'//	:F$//	:F&2U=;P5Q&QSU%V" 2A F"E#;#;<HQ
 8}'''J'JJJ,h7%$$ 50011&//u/MO ..0JE#9#9?JWuoo..Tuoo..T6!ge5M5M&N&N33_j 'O! 2	 %r3   c                 6    [        X[        R                  5      $ rH   )r  r   HVAR_FIELDSr   r   s     r1   instantiateHVARr  y      W&2D2DEEr3   c                 6    [        X[        R                  5      $ rH   )r  r   VVAR_FIELDSr  s     r1   instantiateVVARr  }  r  r3   c                   <    \ rS rSrS r\S 5       rS rS rS r	Sr
g)	_TupleVarStoreAdapteri  c                 4    Xl         X l        X0l        X@l        g rH   )regions	axisOrdertupleVarData
itemCounts)rD   r  r  r  r  s        r1   r   _TupleVarStoreAdapter.__init__  s    "($r3   c           
        ^ U Vs/ s H  o3R                   PM     nnUR                  R                   Vs/ s H  oUR                  U5      PM     snm/ n/ nUR                   H  n/ n	U4S jUR
                   5       n
[        U
[        UR                  6 5       H)  u  pU	R                  [        U[        U5      5      5        M+     UR                  U	5        UR                  UR                  5        M     U " TXFU5      $ s  snf s  snf )Nc              3   .   >#    U  H
  nTU   v   M     g 7frH   r}   )ra   rM   r  s     r1   rc   9_TupleVarStoreAdapter.fromItemVarStore.<locals>.<genexpr>  s     I2HQgaj2Hs   )r   r  r  get_supportrC  VarRegionIndexr  r  r3  r
   r!  rS  )rr   itemVarStorer   r  r  r  r  r  rX  r#  varDataRegionsr   r"  r  s                @r1   fromItemVarStore&_TupleVarStoreAdapter.fromItemVarStore  s    .67hd\\h	77C7Q7Q7X7X
7XVx(7X
 
#++GJI'2H2HIN%(gll9K%L!!!.tK7H"IJ &M
+g//0 , 7IZ@@ 8
s
   D Dc                 >   [         R                  R                  S U R                   5       5      n/ nU R                   H6  n[        UR                  5       5      nXA;   d  M#  UR                  U5        X	 M8     U(       a  UR                  S U 5       5        X l        g )Nc              3   |   #    U  H2  nU  H(  n[        UR                  R                  5       5      v   M*     M4     g 7frH   )r  r   r   )ra   r#  r(  s      r1   rc   7_TupleVarStoreAdapter.rebuildRegions.<locals>.<genexpr>  s7      "3J%C #((..*++% ,"3s   :<c              3   8   #    U  H  n[        U5      v   M     g 7frH   )r   )ra   r  s     r1   rc   r    s     Gvd6llr   )	r  r  fromkeysr  r  r  r   r3  r-  )rD   uniqueRegions
newRegionsr  
regionAxess        r1   rebuildRegions$_TupleVarStoreAdapter.rebuildRegions  s     $//88"&"3"3
 
llF"6<<>2J*!!&)!-	 #
 GGG!r3   c                 \   / n[        U R                  U R                  5       H.  u  p4[        X15      nU(       d  S/U-  nUR	                  U5        M0     U R                  5         [        UR                  5       5      nU R                   Vs/ s H  owU;  d  M
  UPM     snU l        U$ s  snf rB  )	r  r  r  r*  r3  r  r   r   r  )rD   r   defaultDeltaArrayr#  	itemCountre  
pinnedAxesr   s           r1   instantiate!_TupleVarStoreAdapter.instantiate  s    %():):DOO%L!J::RM !"i$$]3	 &M 	2245
#'>>
#1J5NG>
 ! 	
s   	B)B)c           
      J   U R                    Vs/ s H  n[        UR                  5       5      PM     nn/ n[        U R                  U R
                  5       H  u  pEU(       a  [        US   R                  5      U:X  d   eU Vs/ s H4  obR                  [        UR                  R                  5       5      5      PM6     nn[        [        S U 5       6 5      nUR                  [        R                  " XxSS95        M  UR                  [        R                  " / [        U5       V	s/ s H  n	/ PM     sn	5      5        M     [        R                  " U R                   U R                   5      n
[        R"                  " X5      nUR%                  5         U$ s  snf s  snf s  sn	f )Nr   c              3   8   #    U  H  oR                   v   M     g 7frH   r"  )ra   r(  s     r1   rc   7_TupleVarStoreAdapter.asItemVarStore.<locals>.<genexpr>  s     )PZc//Zr   Fr  )r  r  r   r  r  r  rQ   r"  indexr   r!  r3  r   buildVarDatarR  buildVarRegionListr  buildVarStoreprune_regions)rD   r   regionOrdervarDatasr#  r  r(  varRegionIndicesvarDataItems_
regionListr  s               r1   asItemVarStore$_TupleVarStoreAdapter.asItemVarStore  sV   ;?<<H<4y.<H%():):DOO%L!J:a=445BBBNX$NXs%%i0@&ABj ! $  $C)PZ)P$QR(()9RWX ((%	:J-K:JQb:J-KL &M //dnnM
,,ZB""$) I
$ .Ls   #F;F(F )r  r  r  r  N)rB   r~   r   r   r   r   r  r  r  r.  r   r}   r3   r1   r  r    s,    % A A ",!$r3   r  c           	         [         R                  X5      nUR                  U5      nUR                  5       nUR                  U l        [        U S5      (       d  [        UR                  5      U l        U R                  UR                  :X  d   eUR                  U l        [        U5       VVVV	s0 s H#  u  pg[        U5        H  u  pUS-  U-   U	_M     M%     n
nnnn	SXR                  '   U
$ s  sn	nnnf )a  Compute deltas at partial location, and update varStore in-place.

Remove regions in which all axes were instanced, or fall outside the new axis
limits. Scale the deltas of the remaining regions where only some of the axes
were instanced.

The number of VarData subtables, and the number of items within each, are
not modified, in order to keep the existing VariationIndex valid.
One may call VarStore.optimize() method after this to further optimize those.

Args:
    varStore: An otTables.VarStore object (Item Variation Store)
    fvarAxes: list of fvar's Axis objects
    axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
        min/default/max axis coordinates. May not specify coordinates/ranges for
        all the fvar axes.

Returns:
    defaultDeltas: to be added to the default instance, of type dict of floats
        keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
r  r^  r   )r  r  r  r.  r  r  rQ   rC  r  r  NO_VARIATION_INDEX)r  r   r   r  r  newItemVarStorerb  rW  rc  rj  re  s              r1   r  r    s    , *::<RM%11*=#224O!0!>!>L<00$'(?(?$@!$$(D(DDDD*22L ''899ME%f-LE 2+		&- 
9  
 67M112s   0*C/
c                    SU ;  d;  U S   R                   R                  S:  d  U S   R                   R                  (       d  g SU ;   a  SnOSn[        R	                  U5        U S   R                   nUR                  nU S   R
                  n[        XEU5      n[        XUR                  R                  (       + S9nUR                  X /SS/5        UR                  R                  (       aG  UR                  5       nUR                  U5        SU ;   a  U S   R                   R                  U5        g g U?SUl        UR                  c	  U?S	Ul        UR                  (       d\  UR                  (       dJ  UR                   (       d8  UR"                  (       d&  UR                  S:  a  UR                  (       d  U S	 g g g g g g )
NGDEFi  GPOSz"Instantiating GDEF and GPOS tableszInstantiating GDEF tabler   )deleteVariationsi  i   )r   Versionrr  r   r   r   r  r   r  r  mergeTablesr  remap_device_varidxesMarkGlyphSetsDefLigCaretListMarkAttachClassDefGlyphClassDef
AttachList)	r   r   msggdefrF  r   re  mergerr  s	            r1   instantiateOTLrB    s    	g6?  ((:5v$$--2(HHSM6?  D}}Hv##H1(jQM h6L6L6S6S2SF w	FF+;<$$"++-""?3WFO!!77H  M!  (%%DL &&!!
*t/D/D 0E  " ' r3   c                 8   U(       d  g1 SkR                  UR                  5       5      (       d  [        R                  SU  S35        gS n[	        UR                  5       5       H3  u  p4Ub)  X$:  a$  [        R                  SU SU SU  S	U S
3	5          gUnM5     g)NT>   r   r   r   r   r   r   z)Invalid avar SegmentMap record for axis 'zH': does not include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}FzInvalid avar AxisValueMap(r[   z) record for axis 'zX': the toCoordinate value must be >= to the toCoordinate value of the preceding record (z).)issubsetr   r   r  r,  )r   
segmentMappreviousValue	fromCoordtoCoords        r1   _isValidAvarSegmentMaprL  =  s    -66z7G7G7IJJ7y AK K	
 M$Z%5%5%78	$)@KK,YKr' C$I &CCP/QSU
  9 r3   c                    U S   n[        USS5      S:  a&  UR                  R                  (       a  [        S5      eUR                  n[        UR                  5       5      nUR                  U5      (       a  [        R                  S5        U S	 g [        R                  S5        U H  nXS;   d  M
  X5	 M     UR                  U SS	9n0 nUR                  5        GH\  u  p[        X5      (       d  M  U	(       Ga8  X;   Ga2  Xh   n
[        [        U
R                  U	5      S
5      n[        [        U
R                   U	5      S
5      n[        [        U
R"                  U	5      S
5      n[%        UUUU
R&                  U
R(                  5      n0 nU	R                  5        Hy  u  nnUU
R                  :  d  UU
R"                  :  a  M(  U
R+                  U5      nUUs=::  a  U::  d   e   eUR+                  U5      n[        US
5      n[        US
5      nUUU'   M{     UR-                  SSSS.5        XU'   GMX  XU'   GM_     Xrl        g )Nr   majorVersionr   r'   z)avar table with VarStore is not supportedzDropping avar tablezInstantiating avar tableF)r      r           r   )r   rP  r   )rK   r   rr  r  r   r   r   r  r   r   r   r   rL  r   r   r/   r<   r0   r   r   r   r   update)r   r   r   r   r  r  normalizedRangesnewSegmentsr   r  	axisRange	mappedMin	mappedDef	mappedMaxmappedAxisLimitr  rJ  rK  s                     r1   instantiateAvarrY  S  s1    6?Dt^Q'1,1D1D!"MNN}}H Z..01JX&&&'FOHH'(  "++Gu+EK$NN,%g77w2(1I+"9#4#4g>I ,"9#4#4g>I ,"9#4#4g>I ?****O J&-mmo"	7y000I	@Q@Q4Q%66yA	 G8y88888)::7C/	2>	-gr:(/
9% '6 T#>?#- #* I -J  Mr3   c                     U R                  5        H0  u  p#X!;   d  M  X   nX4R                  :  d  X4R                  :  d  M0    g   g)NFT)r   r/   r0   )r  
axisRangesr   coordrT  s        r1   isInstanceWithinAxisRangesr]    sB    "..* "+I(((E4E4E,E	 +
 r3   c                   ^	 UR                  5       nU S   n[        U5      R                  S UR                   5       5      (       a  [        R                  S5        U S	 g [        R                  S5        / nUR                   Hu  nUR                  nXb;   a  M  Xa;   aI  X   nUR                  c#  UR                  UR                  UR                  4nUu  Ul        Ul	        Ul        UR                  U5        Mw     XCl        / nUR                   Hq  m	[        U	4S jUR!                  5        5       5      (       a  M-  U H  nT	R"                  U	 M     [%        T	R"                  U5      (       d  M`  UR                  T	5        Ms     Xl        g )Nr   c              3   8   #    U  H  oR                   v   M     g 7frH   r   r  s     r1   rc   "instantiateFvar.<locals>.<genexpr>  s     Cr   zDropping fvar tablezInstantiating fvar tablec              3   L   >#    U  H  u  pTR                   U   U:g  v   M     g 7frH   r!  )ra   r  r  instances      r1   rc   r`    s%     WFV{tx##D)U2FVs   !$)r   r   r  r   r   r   r   r<   r/   r   r0   r   r   r3  	instancesr  r   r"  r]  )
r   r   r  r   r   r  r   r   rc  rb  s
            @r1   instantiateFvarrd    sQ    ((*H6?D 8}CCCC&'FOHH'(D		,, (F~~% ..$*;*;V^^L>D;DM4,dmD  I INNWhnnFVWWWG$$W-  )(*>*>
KK" # Nr3   c                 P   U S   R                   nUR                  (       a,  UR                  (       a  UR                  R                  (       d  g [        R                  S5        [        X!5      n[        U5      Ul        UR                  (       a  X2R                  l        g S Ul        g )NSTATzInstantiating STAT table)	r   DesignAxisRecordAxisValueArray	AxisValuer   r   axisValuesFromAxisLimitsrQ   AxisValueCount)r   r   statnewAxisValueTabless       r1   instantiateSTATrn    sy     6?  D   3 3 = =HH'(1$C01D(:%"r3   c                 2  ^ U4S jnU R                   R                  n/ nU R                  R                   H  nUR                  nUS;   aG  X5R
                     R                  nUS:X  a  UR                  nOUR                  nU" Xx5      (       a  M[  OpUS:X  aT  Sn	UR                   H8  n
X:R
                     R                  nU
R                  nU" Xx5      (       d  M6  Sn	  O   U	(       a  M  O[        R                  SU5        UR                  U5        M     U$ )Nc                 Z   > U T;   a$  TU    nXR                   :  d  XR                  :  a  gg)NTFr.   )r   	axisValuer   r   s      r1   isAxisValueOutsideLimits:axisValuesFromAxisLimits.<locals>.isAxisValueOutsideLimits  s.    j (F>>)Y-Gr3   )r   r'   rm   r'   r   FTz,Unknown AxisValue table format (%s); ignored)rg  Axisrh  ri  Formatr
  AxisTagNominalValueValueAxisValueRecordr   r  r3  )rl  r   rr  
designAxesrm  axisValueTableaxisValueFormatr   rq  dropAxisValueTabler  s    `         r1   rj  rj    s    &&++J--77(//i' !9!9:BBG!#*77	*00	';; <! "'%55$]]3;;II	+G??)-& 6 " " KKFX!!.11 82 r3   c                 >   [         R                  n[         R                  nU R                  5        Hi  nX   nUR	                  5       (       a$  UR
                  S   =R                  U-  sl        M@  UR                  S:  d  MR  UR                  S==   U-  ss'   Mk     g rB  )r   OVERLAP_COMPOUNDflagOverlapSimpler   r  
componentsflagsnumberOfContours)	glyfTableflagOverlapCompoundr  r  glyphs        r1   setMacOverlapFlagsr    s    "33 22^^%	$Q%%)<<%##a'KKN//N &r3   c                 T    [        X5      n U(       a  [        X5      n [        U S5      $ )NrO  )r   r   r   )r  r   r   s      r1   r   r     s&    5)E"56ub))r3   c                 V    SU ;  a  [        S5      eSU ;   a  SU ;  a  [        S5      eg g )Nr   zMissing required table fvarr  r  zCan't have gvar without glyf)r@   )r   s    r1   sanityCheckVariableTablesr    s<    W677 ;<< ! r3   )downgradeCFF2c                   [        [        U5      5      n[        U 5        [        U5      R	                  U 5      n[
        R                  SU5        UR                  U 5      n[
        R                  SU5        U(       d  [        U 5      n SU ;   a  U S	 U(       a+  [
        R                  S5        [        R                  " X5        SU ;   a  [        X5        SU ;   a
  [        XUS9  SU ;   a
  [        XUS	9  S
U ;   a  [        X5        SU ;   a  [        X5        SU ;   a  [!        X5        SU ;   a  [#        X5        [%        X5        ['        X5        SU ;   a  [)        X5        [        R*                  " U 5         SU ;   a  [-        X5        [/        X5        SSS5        SU ;  a  SU ;   az  U[         R0                  :X  a  [3        U S   5        OWU[         R4                  [         R6                  4;   a3  SSKJn  [
        R                  S5        U" U U[         R6                  :H  S9  SU ;   a  U S   R=                  U 5        [>        R@                  " XRC                  5       S9  U(       a  [E        U 5        U $ ! , (       d  f       N= f)a
  Instantiate variable font, either fully or partially.

Depending on whether the `axisLimits` dictionary references all or some of the
input varfont's axes, the output font will either be a full instance (static
font) or a variable font with possibly less variation data.

Args:
    varfont: a TTFont instance, which must contain at least an 'fvar' table.
    axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
        along one or more axes where the desired instance will be located.
        If the value is `None`, the default coordinate as per 'fvar' table for
        that axis is used.
        The limit values can also be (min, max) tuples for restricting an
        axis's variation range. The default axis value must be included in
        the new range.
    inplace (bool): whether to modify input TTFont object in-place instead of
        returning a distinct object.
    optimize (bool): if False, do not perform IUP-delta optimization on the
        remaining 'gvar' table's deltas. Possibly faster, and might work around
        rendering issues in some buggy environments, at the cost of a slightly
        larger file size.
    overlap (OverlapMode): variable fonts usually contain overlapping contours, and
        some font rendering engines on Apple platforms require that the
        `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
        force rendering using a non-zero fill rule. Thus we always set these flags
        on all glyphs to maximise cross-compatibility of the generated instance.
        You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
        If you want to remove the overlaps altogether and merge overlapping
        contours and components, you can pass OverlapMode.REMOVE (or
        REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
        requires the skia-pathops package (available to pip install).
        The overlap parameter only has effect when generating full static instances.
    updateFontNames (bool): if True, update the instantiated font's name table using
        the Axis Value Tables from the STAT table. The name table and the style bits
        in the head and OS/2 table will be updated so they conform to the R/I/B/BI
        model. If the STAT table is missing or an Axis Value table is missing for
        a given axis coordinate, a ValueError will be raised.
    downgradeCFF2 (bool): if True, downgrade the CFF2 table to CFF table when possible
        ie. full instancing of all axes. This is useful for compatibility with older
        software that does not support CFF2. Defaults to False. Note that this
        operation also removes overlaps within glyph shapes, as CFF does not support
        overlaps but CFF2 does.
zRestricted limits: %szNormalized limits: %sDSIGzUpdating name tabler   r?  )r=  r  r  r  r  HVARr  r   rf  Nr   r  r   )removeOverlapsz!Removing overlaps from glyf table)ignoreErrorsr  )r  )#r   ro   r  r   r   r   r   r   r   r   updateNameTabler  r  r  r  r  r  r  rB  r   rY  pruningUnusedNamesrn  rd  r   r  r   r   fontTools.ttLib.removeOverlapsr  recalcAvgCharWidthr   set_default_weight_width_slantr   setRibbiBits)	r   r   inplacer  overlapupdateFontNamesr  r   r  s	            r1   instantiateVariableFontr  #  s   l #g,'Gg&J'DDWMJHH$j1!++G4HH$&677#FO&'g22]KHE22227- ;,		!	!'	*WG0,	 
+ WW+888"76?3[//1U1UVVI<=")[-Q-Q"Q
 **73
))446  	WN? 
+	*s   6I11
I?c                    U S   R                  [        R                  R                  SSS5      nUc  gUR	                  5       R                  5       nUS;  a  gUS:X  a  SU S   l        O!US	:X  a  SU S   l        OUS
:X  a
  SU S   l        U S   R                  nUS-  nUS-  nUS-  nUS:X  a  US-  nO(US:X  a  US-  nOUS
:X  a  US-  nOUS	:X  a
  US-  nUS-  nX0S   l        g)zHSet the `head.macStyle` and `OS/2.fsSelection` style bits
appropriately.rL   rm   r   i	  N>   bolditalicregularbold italicr  headr  r  r'   r  iir  @       )getNamer   NameIDSUBFAMILY_NAMEtoStrr   macStylefsSelection)fontenglish_ribbi_stylestyleMapStyleName	selections       r1   r  r    s    v,..u||/J/JAqRWX"+11399; LLF" $V	m	+ $V	h	& $VV((IIIII%V		f	$V		h	&V		m	+V	V	(Lr3   limitsrj   c                    0 nU  H  n[         R                  " SU5      nU(       d  [        SU-  5      eUR                  S5      R	                  S5      nUR                  S5      (       a  S X'   Mk  UR                  SSS5      nUS   c  US   US   US   4nOUS   c  US   S US   4n[        S	 U 5       5      n[        U6 X'   M     U$ )
Nz@^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$zinvalid location format: %rr   r   r'   rm      r   c              3   H   #    U  H  o(       a  [        U5      OS v   M     g 7frH   )rp   r`   s     r1   rc   parseLimits.<locals>.<genexpr>  s     ?11uQx$.s    ")rematchr@   groupljusttupler-   )r  resultlimitStringr  r  r   s         r1   parseLimitsr    s    FO
 :[HIIkk!n""1%;;q>>FKQ1%!9QiF1I6FAYQivay1F??? &)- 0 Mr3   c                    SSK Jn  SSKnUR                  SSS9nUR	                  SSS	S
9  UR	                  SSSSS9  UR	                  SSSSSS9  UR	                  SSSSS9  UR	                  SSSSS9  UR	                  SSSS S9  UR	                  S!S"SS#S9  UR	                  S$SS%S&9  UR	                  S'SS(S&9  UR	                  S)S*SS+S9  UR	                  S,S-SS.S9  UR                  S/S09nUR	                  S1S2SS3S&9  UR	                  S4S5SS6S&9  UR                  U 5      nUR                  (       a=  UR                  (       a  [        R                  Ul        O9[        R                  Ul        O#[        [        UR                  5      5      Ul        UR                  n[        R                   R#                  U5      (       d   UR%                  S7R'                  U5      5        U" UR(                  (       a  S8OUR*                  (       a  S9OS:S;9   [-        UR.                  5      n[5        W5      [5        UR.                  5      :w  a  UR%                  S<5        XgU4$ ! [0         a$  nUR%                  [3        U5      5         SnAN`SnAff = f)=a  Parse argv.

Returns:
    3-tuple (infile, axisLimits, options)
    axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
    to specific coordinates along those axes (with `None` as a placeholder for an
    axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
    axis to min/max range.
    Axes locations are in user-space coordinates, as defined in the "fvar" table.
r   )configLoggerNzfonttools varLib.instancer%Partially instantiate a variable font)descriptioninputz	INPUT.ttfzInput variable TTF file.)metavarhelplocargszAXIS=LOC*a7  List of space separated locations. A location consists of the tag of a variation axis, followed by '=' and the literal, string 'drop', or colon-separated list of one to three values, each of which is the empty string, or a number. E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: or wght=drop)r  nargsr  z-oz--outputz
OUTPUT.ttfz7Output instance TTF file (default: INPUT-instance.ttf).)r  r<   r  z--no-optimizer  store_falsezDDon't perform IUP optimization on the remaining gvar TupleVariations)destactionr  z--no-overlap-flagr  zfDon't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable when generating a full instance)z--remove-overlapsremove_overlaps
store_truezrMerge overlapping contours and components (only applicable when generating a full instance). Requires skia-pathopsz--ignore-overlap-errorsignore_overlap_errorszCDon't crash if the remove-overlaps operation fails for some glyphs.z--update-name-tablezeUpdate the instantiated font's `name` table. Input font must have a STAT table with Axis Value Tables)r  r  z--downgrade-cff2z:If all axes are pinned, downgrade CFF2 to CFF table formatz--no-recalc-timestamprecalc_timestampz:Don't set the output font's timestamp to the current time.z--no-recalc-boundsrecalc_boundsz%Don't recalculate font bounding boxesF)requiredz-vz	--verbosezRun more verbosely.z-qz--quietzTurn verbosity off.zNo such file '{}'DEBUGERRORINFO)levelz+Specified multiple limits for the same axis)	fontToolsr  argparseArgumentParseradd_argumentadd_mutually_exclusive_group
parse_argsr  r  r   r   r  r   ro   r  ospathisfileerrorr_   verbosequietr  r  r@   r   rQ   )	r   r  r  parserloggingGroupoptionsinfiler   rt   s	            r1   	parseArgsr    s    '$$$; % F ;UV
	  
 F   S	   +	   B	   !$R	   .   I  
 I	   4	   666FLk,5J   i3H   %G(()BBGO)00GO%c'//&:;]]F77>>&!!(//78!//w'--wV 1
 :#goo..BC((  SVs   I 
J'JJc           
         [        U 5      u  pn[        R                  SU5        [        R                  S5        [        UUR                  UR
                  S9nUR                  5        VVs1 s H  u  pVUb  US   US   :X  d  M  UiM     snnR                  S US   R                   5       5      n[        UUS	UR                  UR                  UR                  UR                  S
9  U(       a  SOSnUR                  (       d  [        US	US9OUR                  n	[        R                  SU(       a  SOSU	5        UR!                  U	5        gs  snnf )r  zRestricting axes: %szLoading variable font)recalcTimestamprecalcBBoxesNr   r'   c              3   8   #    U  H  oR                   v   M     g 7frH   r   r  s     r1   rc   main.<locals>.<genexpr>y  s     ?*>$*>r   r   T)r  r  r  r  r  z	-instancez-partial)	overWritesuffixzSaving %s font %srb  zpartial variable)r  r   r   r   r  r  r   r  r   r  r  r  update_name_tabledowngrade_cff2outputr   save)
r   r  r   r  r   r   limitisFullInstancer  outfiles
             r1   mainr  i  s:   "+D/FHH#Z0HH$%00**G )..00NG=E!Ha0 	0 j?'&/*>*>??	  !!11,, +[
F ~~ 	6T&A^^  HH$
*<
 LL9s   ,EE)NNr   rH   )nr   fontTools.misc.fixedToolsr   r   r   fontTools.varLib.modelsr   r   fontTools.ttLibr   r	   %fontTools.ttLib.tables.TupleVariationr
   fontTools.ttLib.tablesr   r  r   r   fontTools.cffLibr   fontTools.cffLib.specializerr   r   r   r   fontTools.varLibr   fontTools.varLib.mvarr   fontTools.varLib.mergerr   fontTools.varLib.instancerr   featureVarsr   fontTools.misc.cliToolsr   r   fontTools.ttLib.tables.otTablesr   r  rI   
contextlibr   copyr   enumr   loggingr  r  typingr   r    r!   r"   r#   r$   r%   r*   	getLoggerr   r2   r6   	dataclassr-   r5   r   r   r   r   r   r   r  r*  r  r.  r:  r  r  r  r  r  r  r  r  r  r  r  r  r  r>   r  r  rB  rL  rY  r]  rd  rn  rj  r  r   r  r   r  r  r  r  r  r}   r3   r1   <module>r     s  cJ 
 G , @ +   2  % . 1 , 5 6 - =   %    	 	 L L L  45.8 d$U;l5 l5 <l5^ d$U;:  <" d$U;<*z <* <<*~Qgc:o. Q2O6 O6d
? 
!' !!PJ 59:Dz#T z&| EI/Gd	>%" !6 !6H&M BG CLFFUF Up&R8 v,D N&R#$%P
0*= **G GT")J $sHZ4H/H*I :w)t(r3   