
    h4A                        S r SSKJr  SSKrSSKrSSKJr  \R                  " \5      r	S r
S rS rS	 rS
 rS rS r\" SS5      rS\l         S\R$                  l         S\R&                  l         S\R(                  l         S rS r\" SS5      rS\l         S\R&                  l         S\R0                  l         S\R2                  l         S rS r " S S5      rg)aL  
A python interface to Adobe Font Metrics Files.

Although a number of other Python implementations exist, and may be more
complete than this, it was decided not to go with them because they were
either:

1) copyrighted or used a non-BSD compatible license
2) had too many dependencies and a free standing lib was needed
3) did more than needed and it was easier to write afresh rather than
   figure out how to get just what was needed.

It is pretty easy to use, and has no external dependencies:

>>> import matplotlib as mpl
>>> from pathlib import Path
>>> afm_path = Path(mpl.get_data_path(), 'fonts', 'afm', 'ptmr8a.afm')
>>>
>>> from matplotlib.afm import AFM
>>> with afm_path.open('rb') as fh:
...     afm = AFM(fh)
>>> afm.string_width_height('What the heck?')
(6220.0, 694)
>>> afm.get_fontname()
'Times-Roman'
>>> afm.get_kern_dist('A', 'f')
0
>>> afm.get_kern_dist('A', 'y')
-92.0
>>> afm.get_bbox_char('!')
[130, -9, 238, 676]

As in the Adobe Font Metrics File Format Specification, all dimensions
are given in units of 1/1000 of the scale factor (point size) of the font
being used.
    )
namedtupleN   )	uni2type1c                 *    [        [        U 5      5      $ N)intfloatxs    A/var/www/html/env/lib/python3.13/site-packages/matplotlib/_afm.py_to_intr   0   s     uQx=    c                     [        U [        5      (       a  U R                  S5      n [        U R	                  SS5      5      $ )Nzlatin-1,.)
isinstancebytesdecoder	   replacer
   s    r   	_to_floatr   9   s7     !U HHY3$%%r   c                 $    U R                  S5      $ )Nutf8)r   r
   s    r   _to_strr   D   s    88Fr   c                     U R                  SS5      n U R                  5        Vs/ s H  n[        U5      PM     sn$ s  snf )N   ,    )r   splitr   svals     r   _to_list_of_intsr!   H   s4    			$A$%GGI.ISGCLI...s   =c                 `    U R                  5        Vs/ s H  n[        U5      PM     sn$ s  snf r   )r   r   r   s     r   _to_list_of_floatsr#   M   s$    &'ggi0isIcNi000s   +c                 J    U R                  5       R                  5       S;   a  gg)N)s   false   0s   noFT)lowerstrip)r   s    r   _to_boolr(   Q   s    wwy33r   c                    0 S[         _S[        _S[        _S[        _S[        _S[         _S[        _S[        _S	[         _S
[         _S[        _SS _S[        _S[         _S[         _S[         _S[         _[         [         [         [        [        [        S.En0 nSnU  H  nUR                  5       nUR                  S5      (       a  M+  UR                  SS5      nUS   nU(       a  US:w  a  [        S5      eSn[        U5      S:X  a  US   nOSn X   n U" U5      X&'   US:X  d  M    U$    [        S 5      e! [         a    [        R                  SU5         M  f = f! [         a    [        R                  SXg5         M  f = f)!a  
Read the font metrics header (up to the char metrics) and returns
a dictionary mapping *key* to *val*.  *val* will be converted to the
appropriate python type as necessary; e.g.:

    * 'False'->False
    * '0'->0
    * '-168 -218 1000 898'-> [-168, -218, 1000, 898]

Dictionary keys are

  StartFontMetrics, FontName, FullName, FamilyName, Weight,
  ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,
  UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,
  XHeight, Ascender, Descender, StartCharMetrics
s   StartFontMetrics   FontName   FullName
   FamilyName   Weight   ItalicAngles   IsFixedPitchs   FontBBoxs   UnderlinePosition   UnderlineThicknesss   Versions   Noticec                     U $ r    r
   s    r   <lambda>_parse_header.<locals>.<lambda>x   s    Qr   s   EncodingScheme	   CapHeights	   Capheight   XHeights   Ascender)s	   Descender   StdHW   StdVW   StartCharMetricss   CharacterSets
   CharactersTs   Commentr   r   r   zNot an AFM fileF   r   z/Found an unknown keyword in AFM header (was %r)z)Value error parsing header in AFM: %s, %sr8   	Bad parse)r   r   r(   r!   r   rstrip
startswithr   RuntimeErrorlenKeyError_logerror
ValueError)	fhheader_convertersd
first_linelinelstkeyr    	converters	            r   _parse_headerrK   X   s   "YW 	W 	w	
 	7 		 	 	% 	i 	y 	G 	;  	7!" 	i#$ 	i%& 	I'( 	Y)*  $ 58 	AJ{{}??:&&jjq!!f ))"#455Js8q=a&CC	).I	s^AF %% HC @ ;''  	JJH#N	
  	JJBCM	s$   D9
E 9 EE  FFCharMetricszwidth, name, bboxz
    Represents the character metrics of a single character.

    Notes
    -----
    The fields do currently only describe a subset of character metrics
    information defined in the AFM standard.
    zThe character width (WX).zThe character name (N).zK
    The bbox of the character (B) as a tuple (*llx*, *lly*, *urx*, *ury*).c                 $   1 Skn0 n0 nU  H  n[        UR                  5       5      nUR                  S5      (       a  X#4s  $ [        S UR	                  S5       5       5      nUR                  U5      (       d  [        SU-  5      e[        US   5      n[        US   5      nUS   n[        US	   5      n	[        [        [        U	5      5      n	[        XxU	5      n
US
:X  a  SnOUS:X  a  [        S5      nUS:w  a  XU'   XU'   M     [        S5      e)a  
Parse the given filehandle for character metrics information and return
the information as dicts.

It is assumed that the file cursor is on the line behind
'StartCharMetrics'.

Returns
-------
ascii_d : dict
     A mapping "ASCII num of the character" to `.CharMetrics`.
name_d : dict
     A mapping "character name" to `.CharMetrics`.

Notes
-----
This function is incomplete per the standard, but thus far parses
all the sample afm files tried.
>   BCNWXEndCharMetricsc              3   r   #    U  H-  o(       d  M  UR                  5       R                  S S5      v   M/     g7f) r   N)r'   r   ).0r   s     r   	<genexpr>&_parse_char_metrics.<locals>.<genexpr>   s)     J_+AGGIOOC++_s   
7'7;zBad char metrics line: %srO   rQ   rP   rN   Euro   minusu   −r:   )r   r;   r<   dictr   issubsetr=   r   r   r#   listmapr   rL   ord)rC   required_keysascii_dname_drG   valsnumwxnamebboxmetricss              r   _parse_char_metricsrk      s   ( *MGF t{{}%??+,,?"JTZZ_JJ%%d++:TABBd3i tDz"Cy!$s),CTN#b- 6>CW_&'C"9"CLt5 6 {
##r   c                    [        U 5      nUR                  S5      (       d  [        SU-  5      e0 nU  H  nUR                  5       nU(       d  M  UR                  S5      (       a  [        U 5        Us  $ UR	                  5       n[        U5      S:w  d	  US   S:w  a  [        SU-  5      e[        US   5      [        US	   5      [        US
   5      penXbXE4'   M     [        S5      e)z
Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
values are the kern pair value.  For example, a kern pairs line like
``KPX A y -50``

will be represented as::

  d[ ('A', 'y') ] = -50

s   StartKernPairsz Bad start of kern pairs data: %ss   EndKernPairs   r   s   KPXzBad kern pairs line: %sr   r9      zBad kern pairs parse)nextr<   r=   r;   r   r>   r   r   )rC   rG   rE   re   c1c2r    s          r   _parse_kern_pairsrr      s     8D??,--=DEE
A{{}???++HHzz|t9>T!W.84?@@d1g&Q(8)DG:L2(  -
..r   CompositePartzname, dx, dyzK
    Represents the information on a composite element of a composite char.zName of the part, e.g. 'acute'.z+x-displacement of the part from the origin.z+y-displacement of the part from the origin.c           
         0 nU  H  nUR                  5       nU(       d  M  UR                  S5      (       a  Us  $ UR                  S5      nUS   R                  5       nUS   [        US   5      pe/ nUSS  HL  nUR                  5       n	[	        U	S   [        U	S   5      [        U	S   5      5      n
UR                  U
5        MN     XqU'   M     [        S5      e)	aW  
Parse the given filehandle for composites information return them as a
dict.

It is assumed that the file cursor is on the line behind 'StartComposites'.

Returns
-------
dict
    A dict mapping composite character names to a parts list. The parts
    list is a list of `.CompositePart` entries describing the parts of
    the composite.

Examples
--------
A composite definition line::

  CC Aacute 2 ; PCC A 0 0 ; PCC acute 160 170 ;

will be represented as::

  composites['Aacute'] = [CompositePart(name='A', dx=0, dy=0),
                          CompositePart(name='acute', dx=160, dy=170)]

s   EndComposites   ;r   r   r9   r\   rn   zBad composites parse)r;   r<   r   r   rs   r   appendr=   )rC   
compositesrG   re   ccrh   
_num_partspccPartsr   pccparts              r   _parse_compositesr}     s    4 J{{}??+,,zz$!W]]_a5'"Q%.jaA'')C Q3q6):Ic!f<MNDOOD!  $4   -
..r   c                     [         [        S.n0 0 S.nU  HB  nUR                  5       nU(       d  M  UR                  5       S   nXA;   d  M6  X   " U 5      X$'   MD     US   US   4$ )a"  
Parse the optional fields for kern pair data and composites.

Returns
-------
kern_data : dict
    A dict containing kerning information. May be empty.
    See `._parse_kern_pairs`.
composites : dict
    A dict containing composite information. May be empty.
    See `._parse_composites`.
)   StartKernData   StartCompositesr   r   r   )rr   r}   r;   r   )rC   optionalrE   rG   rI   s        r   _parse_optionalr   F  sv     ,.
H
 	!A{{}jjl1o?]2&AF  "4 555r   c                       \ rS rSrS rSS jrS rS rS rSS jr	SS jr
S	 rSS
 jrS rS rS r\S 5       rS rS r\S 5       rS rS rS rS rS rS rS rSrg)AFMif  c                     [        U5      U l        [        U5      u  U l        U l        [        U5      u  U l        U l        g)z'Parse the AFM file in file object *fh*.N)rK   _headerrk   _metrics_metrics_by_namer   _kern
_composite)selfrC   s     r   __init__AFM.__init__h  s5    $R(/B2/F,t,&5b&9#
DOr   c                 X    U(       d  [        U5      nU R                  U   R                  $ r   ra   r   ri   r   cisords      r   get_bbox_charAFM.get_bbox_charn  s#    AA}}Q$$$r   c                    [        U5      (       d  gSnSnSnSnU Hh  nUS:X  a  M  U R                  [        U5         u  pxn	X'U R                  R	                  X84S5      -   -  nU	u  pp[        XK5      n[        X[U-   5      nUnMj     X%U-
  4$ )zV
Return the string width (including kerning) and string height
as a (*w*, *h*) tuple.
)r   r   r   N    eA
)r>   r   ra   r   getminmax)r   r   total_widthnamelastminymaxyr   rg   rh   ri   lbwhs                 r   string_width_heightAFM.string_width_heights  s    
 1vvADy!]]3q62NBd

/? CCCKJA!t<DtU#DH  4K''r   c                    [        U5      (       d  gSnSnSnSnSn[        U[        5      (       d  [        U5      nU H  nUS:X  a  M  [        R
                  " [        U5      S[        U5      S 35      n U R                  U   u  pnX)U R                  R                  X84S5      -   -  nUu  pp[        Xl5      n[        XM5      n[        X]U-   5      nUnM     XdX%U-
  U* 4$ ! [         a    SnU R                  U   u  pn Nzf = f)	z7Return the string bounding box and the maximal descent.)r   r   r   r   r   r   Nr   r   uni04Xquestion)r>   r   strr   r   r   ra   r   r?   r   r   r   )r   r   r   r   r   r   leftr   rh   rg   _ri   r   r   r   r   s                   r   get_str_bbox_and_descentAFM.get_str_bbox_and_descent  s   1vv !S!!
AADy==Q3s1vcl);<D:"33D9t 

/? CCCKJA!t<Dt<DtU#DH " ;tdU::  :!"33D9t:s   7C##DDc                 *    U R                  U5      SS $ )zReturn the string bounding box.Nrm   )r   )r   r   s     r   get_str_bboxAFM.get_str_bbox  s    ,,Q/33r   c                 X    U(       d  [        U5      nU R                  U   R                  $ )z8Get the name of the character, i.e., ';' is 'semicolon'.)ra   r   rh   r   s      r   get_name_charAFM.get_name_char  s#    AA}}Q$$$r   c                 X    U(       d  [        U5      nU R                  U   R                  $ )zD
Get the width of the character from the character metric WX field.
)ra   r   widthr   s      r   get_width_charAFM.get_width_char  s%     AA}}Q%%%r   c                 4    U R                   U   R                  $ )z;Get the width of the character from a type1 character name.)r   r   r   rh   s     r   get_width_from_char_nameAFM.get_width_from_char_name  s    $$T*000r   c                 ^    U(       d  [        U5      nU R                  U   R                  S   $ )z@Get the bounding box (ink) height of character *c* (space is 0).r\   r   r   s      r   get_height_charAFM.get_height_char  s(    AA}}Q$$R((r   c                 f    U R                  U5      U R                  U5      pCU R                  X45      $ )zH
Return the kerning pair distance (possibly 0) for chars *c1* and *c2*.
)r   get_kern_dist_from_name)r   rp   rq   name1name2s        r   get_kern_distAFM.get_kern_dist  s2     ))"-t/A/A"/Eu++E99r   c                 <    U R                   R                  X4S5      $ )zN
Return the kerning pair distance (possibly 0) for chars
*name1* and *name2*.
r   )r   r   )r   r   r   s      r   r   AFM.get_kern_dist_from_name  s    
 zz~~una00r   c                      U R                   S   $ )z*Return the font name, e.g., 'Times-Roman'.r*   r   r   s    r   get_fontnameAFM.get_fontname  s    ||K((r   c                 "    U R                  5       $ r   )r   r   s    r   postscript_nameAFM.postscript_name  s      ""r   c                 `    U R                   R                  S5      nUc  U R                   S   nU$ )z/Return the font full name, e.g., 'Times-Roman'.r+   r*   r   r   r   s     r   get_fullnameAFM.get_fullname  s.    ||,<<<,Dr   c                     U R                   R                  S5      nUb  U$ U R                  5       nSn[        R                  " USU5      $ )z+Return the font family name, e.g., 'Times'.r,   zY(?i)([ -](regular|plain|italic|oblique|bold|semibold|light|ultralight|extra|condensed))+$ )r   r   r   resub)r   rh   extrass      r   get_familynameAFM.get_familyname  sK    ||.K   ":vvfb$''r   c                 "    U R                  5       $ )z$The font family name, e.g., 'Times'.)r   r   s    r   family_nameAFM.family_name  s     ""$$r   c                      U R                   S   $ )z0Return the font weight, e.g., 'Bold' or 'Roman'.r-   r   r   s    r   
get_weightAFM.get_weight  s    ||I&&r   c                      U R                   S   $ )zReturn the fontangle as float.r.   r   r   s    r   	get_angleAFM.get_angle  s    ||N++r   c                      U R                   S   $ )zReturn the cap height as float.r4   r   r   s    r   get_capheightAFM.get_capheight  s    ||L))r   c                      U R                   S   $ )zReturn the xheight as float.r5   r   r   s    r   get_xheightAFM.get_xheight   s    ||J''r   c                      U R                   S   $ )z(Return the underline thickness as float.r/   r   r   s    r   get_underline_thicknessAFM.get_underline_thickness  s    ||122r   c                 :    U R                   R                  SS5      $ )z]
Return the standard horizontal stem width as float, or *None* if
not specified in AFM file.
r6   Nr   r   s    r   get_horizontal_stem_widthAFM.get_horizontal_stem_width      
 ||$//r   c                 :    U R                   R                  SS5      $ )z[
Return the standard vertical stem width as float, or *None* if
not specified in AFM file.
r7   Nr   r   s    r   get_vertical_stem_widthAFM.get_vertical_stem_width  r   r   )r   r   r   r   r   N)F)__name__
__module____qualname____firstlineno__r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   __static_attributes__r1   r   r   r   r   f  s    :%
(2;<4%&1):1) # #
( % %',*(300r   r   )__doc__collectionsr   loggingr   _mathtext_datar   	getLoggerr   r@   r   r   r   r!   r#   r(   rK   rL   r   rh   ri   rk   rr   rs   dxdyr}   r   r   r1   r   r   <module>r      s   #J #  	 % "&/
1Pf (;<  <   8   N   3$l/@ ?N;N B   L   L   +/\6@n0 n0r   