
    ^j=                       d Z ddlmZ ddlmZ ddlmZ ddlZddlZddl	Z	ddl
mZ ddlZddlmZmZ dd	lmZ dd
lmZ e	j*                  r"ddlmZ ddlmZ ddlmZ ddlmZmZmZ ddlmZ dddZ ej@                  d      d        Z! G d de	jD                        Z#	 	 	 	 	 	 d dZ$d Z% G d d      Z& G d d      Z' G d de      Z(y)!z7
Common functionality between the PDF and PS backends.
    )annotations)contextmanager)BytesION)subset   )font_managerft2font)AFM)RendererBase)	Generator)AbstractContextManager   )FontPath)CharacterCodeTypeFT2FontGlyphIndexType)TTFont   i   )   *   2   c                \    t        | d      5 }t        |      cd d d        S # 1 sw Y   y xY w)Nrb)openr
   )fnamefhs     n/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/matplotlib/backends/_backend_pdf_ps.py_cached_get_afm_from_fnamer   $   s*    	eT	 b2w  s   "+c                  8    e Zd ZU dZded<   ded<   edd       Zy)	SubsetResultsa  
    The results of a subsetting operation on a font.

    Attributes
    ----------
    font : TTFont
        An open font object representing the subset.
    glyph_index_map : dict
        Mapping of requested glyph indices to actual subset glyph indices.
    r   fontz$dict[GlyphIndexType, GlyphIndexType]glyph_index_mapc              #  V   K   | j                   5  |  d d d        y # 1 sw Y   y xY wwN)r!   selfs    r   _as_cmzSubsetResults._as_cm9   s&     YY 	J	 	 	s   )	)&)N)returnz$Generator[SubsetResults, None, None])__name__
__module____qualname____doc____annotations__r   r'        r   r    r    *   s&    	 L99 r/   r    c                f   t        j                  dd      }|xj                  g dz  c_        | j                  |_        t        j
                  | |      }t        j                  |      }|j                  |       |j                  |       t        ||j                        j                         S )ab  
    Subset a TTF font.

    Reads the named fontfile and restricts the font to the glyphs.

    Parameters
    ----------
    fontfile : FontPath
        Path to the font file
    glyphs : set[GlyphIndexType]
        Set of glyph indices to include in subset.

    Returns
    -------
    SubsetResults
        The font and new glyph index mapping.
    T)glyph_namesrecommended_glyphs)FFTMPfEdBDFmetaMERGTSIVZapfbdatbloccidgfdscfeatfmtxfondjustkerxltagmorxtrakxref)options)gids)r   Optionsdrop_tables
face_indexfont_number	load_font	Subsetterpopulater    r"   r'   )fontfileglyphsrG   r!   	subsetters        r   get_glyphs_subsetrS   ?   s    ( nn$GG   . #--GHg.D  1IF#Ty889@@BBr/   c                @    t               }| j                  |d       |S )z
    Convert a TTFont object into a file-like object.

    Parameters
    ----------
    font : fontTools.ttLib.ttFont.TTFont
        A font object

    Returns
    -------
    BytesIO
        A file object with the font saved into it
    F)reorderTables)r   save)r!   r   s     r   font_as_filerW   v   s      
BIIbI&Ir/   c                  H    e Zd ZdZddZ	 	 	 	 ddZ	 	 	 	 d	dZ	 	 	 	 d
dZy)GlyphMapa  
    A two-way glyph mapping.

    The forward glyph map is from (character string, glyph index)-pairs to
    (subset index, subset character code)-pairs.

    The inverse glyph map is from to (subset index, subset character code)-pairs to
    (character string, glyph index)-pairs.
    c                     i | _         i | _        y r$   _forward_inverser%   s    r   __init__zGlyphMap.__init__   s    =? 	 IK 	r/   c                <    | j                   j                  ||f      S )z
        Get the forward mapping from a (character string, glyph index)-pair.

        This may return *None* if the pair is not currently mapped.
        )r\   get)r&   	charcodesglyph_indexs      r   r`   zGlyphMap.get   s     }}  )[!9::r/   c                $    | j                   ||f   S )z>Get the inverse mapping from a (subset, subset charcode)-pair.)r]   )r&   r   subset_charcodes      r   igetzGlyphMap.iget   s     }}fo677r/   c                P    ||f| j                   ||f<   ||f| j                  ||f<   y)a  
        Add a mapping to this instance.

        Parameters
        ----------
        charcode : CharacterCodeType
            The character code to record.
        glyph_index : GlyphIndexType
            The corresponding glyph index to record.
        subset : int
            The subset in which the subset character code resides.
        subset_charcode : CharacterCodeType
            The subset character code within the above subset.
        Nr[   )r&   charcoderb   r   rd   s        r   addzGlyphMap.add   s4      39/1Jx-.4<k3Jv/0r/   N)r(   None)ra   strrb   r   r(   z$tuple[int, CharacterCodeType] | None)r   intrd   r   r(   ztuple[str, GlyphIndexType])
rg   rj   rb   r   r   rk   rd   r   r(   ri   )r)   r*   r+   r,   r^   r`   re   rh   r.   r/   r   rY   rY      sO    K;';,P;8/84N8
K.K37Kr/   rY   c                  R    e Zd ZdZdddZ	 	 d		 	 	 	 	 d
dZ	 	 	 	 ddZ	 	 	 	 ddZy)CharacterTrackera}  
    Helper for font subsetting by the PDF and PS backends.

    Maintains a mapping of font paths to the set of characters and glyphs that are being
    used from that font.

    Attributes
    ----------
    subset_size : int
        The size at which characters are grouped into subsets.
    used : dict
        A dictionary of font files to character maps.

        The key is a font filename.

        The value is a list of dictionaries, each mapping at most *subset_size*
        character codes to glyph indices. Note this mapping is the inverse of FreeType,
        which maps glyph indices to character codes.

        If *subset_size* is not set, then there will only be one subset per font
        filename.
    glyph_maps : dict
        A dictionary of font files to glyph maps. You probably will want to use the
        `.subset_to_unicode` method instead of this attribute.
    c                .    i | _         i | _        || _        y)z
        Parameters
        ----------
        subset_size : int, optional
            The maximum size that is supported for an embedded font. If provided, then
            characters will be grouped into these sized subsets.
        N)used
glyph_mapssubset_size)r&   rq   s     r   r^   zCharacterTracker.__init__   s     OQ	/1&r/   Nc                    |j                  |t        j                  j                  ||      D cg c]3  }| j	                  |j
                  |j                  |j                        5 c}S c c}w )a  
        Record that string *s* is being typeset using font *font*.

        Parameters
        ----------
        font : FT2Font
            A font that is being used for the provided string.
        s : str
            The string that should be marked as tracked by the provided font.
        features : tuple[str, ...], optional
            The font feature tags to use for the font.

            Available font feature tags may be found at
            https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist
        language : str, optional
            The language of the text in a format accepted by libraqm, namely `a BCP47
            language code <https://www.w3.org/International/articles/language-tags/>`_.

        Returns
        -------
        list[tuple[int, CharacterCodeType]]
            A list of subset and character code pairs corresponding to the input string.
            If a *subset_size* is specified on this instance, then the character code
            will correspond with the given subset (and not necessarily the string as a
            whole). If *subset_size* is not specified, then the subset will always be 0
            and the character codes will be returned from the string unchanged.
        )featureslanguage)_layoutr	   	LoadFlags
NO_HINTINGtrack_glyph	ft_objectcharrb   )r&   r!   srs   rt   	raqm_items         r   trackzCharacterTracker.track   sh    B "\\!W->->-I-I3;h * P
 Y00)..)BWBWX
 	
 
s   8A+c                   t        |t              rt        |d         }n|}t        |      }t	        j
                  |j                  |j                        }| j                  j                  |t                     }|j                  ||      x}r|S | j                  j                  |i g      }t        |      dkD  xs) | j                  dk7  xr || j                  k\  xs ||d   v }	|	rWt        |      dk(  st        |d         | j                  k(  r|j                  i        t        |      dz
  }
t        |d         }nd}
|}|||
   |<   |j!                  |||
|       |
|fS )a  
        Record character code *charcode* at glyph index *glyph* as using font *font*.

        Parameters
        ----------
        font : FT2Font
            A font that is being used for the provided string.
        chars : str or CharacterCodeType
            The character(s) to record. This may be a single character code, or multiple
            characters in a string, if the glyph maps to several characters. It will be
            normalized to a string internally.
        glyph : GlyphIndexType
            The corresponding glyph index to record.

        Returns
        -------
        subset : int
            The subset in which the returned character code resides. If *subset_size*
            was not specified on this instance, then this is always 0.
        subset_charcode : CharacterCodeType
            The character code within the above subset. If *subset_size* was not
            specified on this instance, then this is just *charcode* unmodified.
        r   r   )
isinstancerj   ordchrr   r   r   rK   rp   
setdefaultrY   r`   ro   lenrq   appendrh   )r&   r!   charsglyphrg   	font_path	glyph_mapresultsubset_mapsuse_next_charmapr   rd   s               r   rx   zCharacterTracker.track_glyph  sd   2 eS!58}HHJE ))$**dooF	OO..y(*E	]]5%0060Mii**9rd; JN ! 	
 D,,, . {1~- 	 ;1$KO(<@P@P(P""2&%)F!+b/2OF&O/4FO,eUFO<((r/   c                F    | j                   |   j                  ||      d   S )a  
        Map a subset index and character code to a Unicode character code.

        Parameters
        ----------
        fontname : str
            The name of the font, from the *used* dictionary key.
        subset : int
            The subset index within a font.
        subset_charcode : CharacterCodeType
            The character code within a subset to map back.

        Returns
        -------
        str
            The Unicode character(s) corresponding to the subsetted character code.
        r   )rp   re   )r&   fontnamer   rd   s       r   subset_to_unicodez"CharacterTracker.subset_to_unicodeH  s%    & x(--foFqIIr/   )r   )rq   rk   )NN)
r!   r   r{   rj   rs   ztuple[str, ...] | Nonert   z-str | tuple[tuple[str, int, int], ...] | Noner(   z#list[tuple[int, CharacterCodeType]])r!   r   r   zstr | CharacterCodeTyper   r   r(   ztuple[int, CharacterCodeType])r   rj   r   rk   rd   r   r(   rj   )r)   r*   r+   r,   r^   r}   rx   r   r.   r/   r   rm   rm      sb    4
' 26HL#
.#
E#
 7#
J>))>).K>)@J+<JADJr/   rm   c                  R     e Zd Z fdZd Zd Zd Zd Zd Z fdZ	d Z
d	 Z xZS )
RendererPDFPSBasec                >    t         |           || _        || _        y r$   )superr^   widthheight)r&   r   r   	__class__s      r   r^   zRendererPDFPSBase.__init__c  s    
r/   c                     y)NFr.   r%   s    r   flipyzRendererPDFPSBase.flipyh  s    r/   c                     y)NTr.   r%   s    r   option_scale_imagez$RendererPDFPSBase.option_scale_imagel  s    r/   c                *    t         j                  d    S )Nzimage.composite_image)mplrcParamsr%   s    r   option_image_nocompositez*RendererPDFPSBase.option_image_nocompositep  s     << 7888r/   c                >    | j                   dz  | j                  dz  fS )Ng      R@)r   r   r%   s    r   get_canvas_width_heightz)RendererPDFPSBase.get_canvas_width_heightu  s    zzD $++"444r/   c                    t         j                  | j                     sy| j                  |      }|j	                         dz  }|j                         |z  }|j                          |z  }||z   dz  }|||fS )a  
        Return the ascent, descent, and line gap for font described by *prop*.

        TODO: This is a temporary method until we design a proper API for the backends.

        Parameters
        ----------
        prop : `.font_manager.FontProperties`
            The properties describing the font to measure.

        Returns
        -------
        ascent, descent, line_gap : float or None
            The ascent, descent and line gap of the determined font, or None to fall
            back to normal measurements.
        )NNN  g?)r   r   _use_afm_rc_name_get_font_afmget_size_in_pointsget_ascenderget_descender)r&   propr!   scaleadgs          r   _get_font_height_metricsz*RendererPDFPSBase._get_font_height_metricsy  s}    " ||D112#!!$''')D0%'!!E)UcM!Qwr/   c                   |dk(  rt         |   |||      S |rJ| j                  j                  j	                  |d|      }|j
                  |j                  |j                  fS t        j                  | j                     rO| j                  |      }|j                  |      \  }}}}	}
|j                         dz  }||z  }|	|z  }	|
|z  }
||	|
fS | j                  |      }|j                  |dt         j"                  j$                         |j'                         \  }}	|j)                         }
d}||z  }|	|z  }	|
|z  }
||	|
fS )NTeXH   r   g        )flagsg      ?)r   get_text_width_height_descent
_text2pathmathtext_parserparser   r   depthr   r   r   r   get_str_bbox_and_descentr   _get_font_ttfset_textr	   rv   rw   get_width_heightget_descent)r&   r{   r   ismathr   r!   lbwhr   r   r   s               r   r   z/RendererPDFPSBase.get_text_width_height_descent  sF   U?78D&IIOO3399!RFE;;ekk99\\$//0%%d+D 99!<MAq!Q++-4EJAJAJAa7N%%d+DMM!S(9(9(D(DME((*DAq  "AEJAJAJAa7Nr/   c                \    t        j                  |d| j                        }t        |      S )Nafm)fontext	directory)r   findfont_afm_font_dirr   )r&   r   r   s      r   r   zRendererPDFPSBase._get_font_afm  s*    %%%4+=+=?)%00r/   c                >   t         j                  j                  |      }	 t        j                  |      }|j	                          |j                  |j                         d       |S # t        $ r+ t        j                  t              j                  d|        w xY w)Nr   zMThe PostScript/PDF backend does not currently support the selected font (%s).)r   fontManager_find_fonts_by_propsget_fontclearset_sizer   RuntimeErrorlogging	getLoggerr)   warning)r&   r   fnamesr!   s       r   r   zRendererPDFPSBase._get_font_ttf  s    ))>>tD		((0DJJLMM$113R8K 	h'//239; 		s   AA( (4B)r)   r*   r+   r^   r   r   r   r   r   r   r   r   __classcell__)r   s   @r   r   r   ^  s0    

9
5441
r/   r   )rP   r   rQ   zset[GlyphIndexType]r(   z%AbstractContextManager[SubsetResults]))r,   
__future__r   
contextlibr   ior   	functoolsr   typing	fontToolsr   
matplotlibr    r   r	   _afmr
   backend_basesr   TYPE_CHECKINGcollections.abcr   r   r   r   r   r   fontTools.ttLibr   _FONT_MAX_GLYPH	lru_cacher   
NamedTupler    rS   rW   rY   rm   r   r.   r/   r   <module>r      s    # %       $  ( 
)1&CC&  R 
F%% *4C4C 34C*4Cn&0K 0Kf_J _JD_ _r/   