o
    gҠ                     @   sR  d dl 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Zd dlZd dl	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 d dlZd dlmZmZmZ d dlmZmZmZmZmZmZmZ d dl m!Z! d dl"m#Z#m$Z$ d d	l%m&Z& d d
l'm(Z( d dl)m*Z* e+e,Z-dd Z.dd Z/dZ0de0 Z1dZ2de2 Z3dZ4e
5e4d Z6e7e
5e4d j8dZ9e7e
5e4d j8dZ:dd Z;dd Z<dd Z=dd  Z>d!d" Z?G d#d$ d$e@ZAG d%d& d&ZBeCd'd(d) ZDG d*d+ d+eZEejFd,d-d.G d/d0 d0eZGeFd1G d2d3 d3ZHG d4d5 d5eZIeZJejKG d6d7 d7eZLG d8d9 d9ZMdS ):    N)BytesIO)TemporaryDirectory)Image)_apicbookfont_manager)_Backend_check_savefig_extra_argsFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase_no_output_draw)MixedModeRenderer)_create_pdf_info_dict_datetime_to_pdf)Path)Figure)Gcfc                  C   s   g } t jd }|dkr| d |dkrCt jd rCg d}g d}t||D ]\}}tt|}| d||j|j	
 d f  q&d	| S )
z Build fontspec preamble from rc.pgf.texsystempdflatexz\usepackage{fontspec}zpgf.rcfonts)serifzsans\-serif	monospace)setmainfontsetsansfontsetmonofontz\%s{%s}[Path=\detokenize{%s}]/
)mplrcParamsappendzippathlibr   fmfindfontnameparentas_posixjoin)latex_fontspec
texcommandfamiliescommandsfamilycommandpath r0   ]/home/ubuntu/cloudmapper/venv/lib/python3.10/site-packages/matplotlib/backends/backend_pgf.pyget_fontspec'   s   



r2   c                   C   s
   t jd S )zGet LaTeX preamble from rc.zpgf.preambler   r   r0   r0   r0   r1   get_preamble<   s   
r4   gRhV?      ?gqq?z(?<!\\)(?:\\\\)*z\$z
(?=[_^$%])z\\z(\\mathdefault) c                 C   s\   t | } | dd} t| }t|D ]\}}|d s t|}nd| }|||< qd|S )aX  
    Do some necessary and/or useful substitutions for texts to be included in
    LaTeX documents.

    This distinguishes text-mode and math-mode by replacing the math separator
    ``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``)
    are ignored.

    The following characters are escaped in text segments: ``_^$%``
    u   −z\ensuremath{-}   z\(\displaystyle %s\)r6   )_replace_mathdefaultreplace
re_mathsepsplit	enumerate_replace_escapetextr(   )textpartsisr0   r0   r1   common_texificationZ   s   



rB   c                 C   s   |  | |  d d S )Nz%
)write)fhliner0   r0   r1   writelnv   s   
rF   c                    s   g }ddddd}|   d   |v r||   n"t fddtjjD r7tjd d	kr7|d
   nt	d  | 
 }|d||d f  dddd}|||    g d}|  |v rj|d |d d|S )Nz	\rmfamilyz	\sffamilyz	\ttfamily)r   sansz
sans-serifr   r   c                 3   s    | ]}|j  kV  qd S N)r%   ).0fontr-   r0   r1   	<genexpr>   s    z'_font_properties_str.<locals>.<genexpr>r   r   z\setmainfont{%s}\rmfamilyzIgnoring unknown font: %sz\fontsize{%f}{%f}g333333?r6   z\itshapez\slshape)normalitalicoblique)semibolddemibolddemiboldheavyz
extra boldblackz	\bfseriesz\selectfont)
get_familyr    anyr#   fontManagerttflistr   r   _logwarningget_size_in_points	get_style
get_weightr(   )propr,   r+   sizestyles
boldstylesr0   rK   r1   _font_properties_str}   s(   


rc   c                 C   sD   t |tjrt|}n| dkr|jd}nt|}|  d| dS )z;Convert metadata key/value to a form that hyperref accepts.Trappedasciiz={})
isinstancedatetimer   r%   decodestr)keyvaluer0   r0   r1   _metadata_to_str   s   
rm   c                     sP   t drdd } | S ztd W n tjy   Y tdw  fdd}|S )z9Return a function that converts a pdf file to a png file.
pdftocairoc              	   S   s6   ddddd| | t j|d g}tj|tjd d S )Nrn   z-singlefilez-pngz-rz%dr   stderr)osr/   splitext
subprocesscheck_outputSTDOUTpdffilepngfiledpicmdr0   r0   r1   cairo_convert   s   z0make_pdf_to_png_converter.<locals>.cairo_convertgsc                    s>    j ddddddddd	d
d| d| | g}tj|tjd d S )Nz-dQUIETz-dSAFERz-dBATCHz	-dNOPAUSEz
-dNOPROMPTz-dUseCIEColorz-dTextAlphaBits=4z-dGraphicsAlphaBits=4z-dDOINTERPOLATEz-sDEVICE=png16mz-sOutputFile=%sz-r%dro   )
executablers   rt   ru   rv   gs_infor0   r1   
gs_convert   s   
z-make_pdf_to_png_converter.<locals>.gs_convertz&No suitable pdf to png renderer found.)shutilwhichr   _get_executable_infoExecutableNotFoundErrorRuntimeError)r{   r   r0   r~   r1   make_pdf_to_png_converter   s   
r   c                       s&   e Zd Zd fdd	Zdd Z  ZS )
LatexErrorr6   c                    s   t  | || _d S rH   )super__init__latex_output)selfmessager   	__class__r0   r1   r      s   
zLatexError.__init__c                 C   s    | j \}| jr|d| j 7 }|S Nr   )argsr   r   rA   r0   r0   r1   __str__   s   zLatexError.__str__)r6   )__name__
__module____qualname__r   r   __classcell__r0   r0   r   r1   r      s    r   c                   @   s   e Zd ZdZedd Zedd Zee	ddd Z
d	d
 Zdd Zdd Zdd Zdd Zeddd Zdd ZdS )LatexManagerz
    The LatexManager opens an instance of the LaTeX application for
    determining the metrics of text elements. The LaTeX environment can be
    modified by setting fonts and/or a custom preamble in `.rcParams`.
    c                  C   s6   t  } t }ddtjd  d| |dddg}d|S )	Nz\documentclass{minimal}z% !TeX program = r   z\usepackage{graphicx}z\begin{document}ztext $math \mu$z!\typeout{pgf_backend_query_start}r   )r4   r2   r   r   r(   )latex_preambler)   latex_headerr0   r0   r1   _build_latex_header   s   
z LatexManager._build_latex_headerc                 C   s   |  |  S )z
        Return the previous LatexManager if the header and tex system did not
        change, or a new instance otherwise.
        )_get_cached_or_new_implr   clsr0   r0   r1   _get_cached_or_new   s   zLatexManager._get_cached_or_new   c                 C   s   |  S rH   r0   )r   headerr0   r0   r1   r         z$LatexManager._get_cached_or_new_implc                 C   s>   | j d u r	|   | j j| | j jd | j j  d S r   )latex_setup_latex_processstdinrC   flushr   r0   r0   r1   _stdin_writeln   s
   
zLatexManager._stdin_writelnc                 C   sn   t |}g }	 | jjd}|| |t| d  |krn|s1| j  d | _tdd|qd|S )NTr   zLaTeX process haltedr6   )	listr   stdoutreadr    lenkillr   r(   )r   rA   charscr0   r0   r1   _expect   s   


	zLatexManager._expectc                 C   s
   |  dS )Nz
*)r   r   r0   r0   r1   _expect_prompt
  s   
zLatexManager._expect_promptc              
   C   s   t  | _| jj| _t| | jj| _tj	d | _
t | _d}ztj| j
dgtjtjd| jd}W n( tyF } z	t| j
 d|d }~w tyY } ztd| j
 |d }~ww | j| }||\}}|jdkrptd	|d | _i | _d S )
Nr   z
\makeatletter
\@@end
-halt-on-errorutf-8r   r   encodingcwdz_ not found.  Install it or change rcParams['pgf.texsystem'] to an available TeX implementation.zError starting process %rr   zDLaTeX returned an error, probably missing font or error in preamble.)r   _tmpdirr%   tmpdirweakreffinalizecleanup_finalize_tmpdirr   r   r*   r   r   r   rs   PopenPIPEFileNotFoundErrorr   OSErrorcommunicate
returncoder   r   	str_cache)r   	latex_endr   err
test_inputr   rp   r0   r0   r1   r     sF   






zLatexManager.__init__c                 C   s`   t j| jdgt jt jd| jd| _dd }t| || j| _| 	| 
  | d |   d S )Nr   r   r   c                 S   s   |    |   d S rH   )r   r   )r   r0   r0   r1   finalize_latex7  s   z9LatexManager._setup_latex_process.<locals>.finalize_latexz*pgf_backend_query_start)rs   r   r*   r   r   r   r   r   _finalize_latexr   r   r   r   )r   r   r0   r0   r1   r   -  s   
z!LatexManager._setup_latex_process3.3c                 C   s   | j jS rH   )r   r   r   r0   r0   r1   latex_stdin_utf8C  s   zLatexManager.latex_stdin_utf8c              
   C   sN  t |}d||f }|| jv r| j| S | | z|   W n ty5 } z
td||j|d}~ww | d z|  }W n tyW } z
td||j|d}~ww z| d 	d\}}}	W n t
y{ }
 z	td|||
d}
~
ww t|dd t|dd t|	dd }}}||| |f| j|< ||| |fS )zv
        Get the width, total height and descent for a text typeset by the
        current LaTeX environment.
        z\sbox0{%s %s}z&Error processing '{}'
LaTeX Output:
{}Nz$\typeout{\the\wd0,\the\ht0,\the\dp0}r   ,)rc   r   r   r   r   
ValueErrorformatr   
splitlinesr;   	Exceptionfloat)r   r>   r_   	prop_cmdstextboxeanswerwidthheightoffsetr   whor0   r0   r1   get_width_height_descentG  sN   





4z%LatexManager.get_width_height_descentN)r   r   r   __doc__staticmethodr   classmethodr   	functools	lru_cacher   r   r   r   r   r   r   
deprecatedr   r   r0   r0   r0   r1   r      s"    

 
r   r   c                  C   sN   t  } | dtd   z|  }W dS  ty&   t j	  Y dS w )Nz&\includegraphics[interpolate=true]{%s}zimages/matplotlib.pngz\includegraphicsz	\pgfimage)
r   r   r   r   _get_data_pathr'   r   r   r   cache_clear)manpromptr0   r0   r1   _get_image_inclusion_commandt  s   
r   c                       s   e Zd Zeddd' fdd	Z	d(ddZd(d	d
Zdd Zdd Z	d(ddZ
d)ddZdd Zdd Zd(ddZd*ddZd+ddZdd  Zd!d" Zd#d$ Zd%d& Z  ZS ),RendererPgfr   dummyFc                    sT   t    |j| _|| _|| _d| _|r&tjD ]}|dr%dd | j|< qdS dS )a  
        Create a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        r   draw_c                  _   s   d S rH   r0   )r   kwargsr0   r0   r1   <lambda>  s    z&RendererPgf.__init__.<locals>.<lambda>N)	r   r   ry   rD   figureimage_counterr   __dict__
startswith)r   r   rD   r   mr   r0   r1   r     s   


zRendererPgf.__init__Nc                 C   s(  t | jd d| j }| | | || || \}}	|d | |d | |	d | |	d | f}
t | jd|
  | d || | j|	 dk|d ud t | jd |j
|d	d
D ]-\}}|d | |d | }}t | jd t | jd||f  t | jd t | jd q^t | jd d S )N\begin{pgfscope}r5   r   r   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{        strokefillrf   F)simplify"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}\end{pgfscope})rF   rD   ry   _print_pgf_clip_print_pgf_path_stylesget_extents
get_points_print_pgf_path_pgf_path_drawget_linewidthiter_segments)r   gcmarker_pathmarker_transr/   transrgbFacefbltrcoordspointcodexyr0   r0   r1   draw_markers  s.   

,zRendererPgf.draw_markersc                 C   s  t | jd | | | || | |||| | j| dk|d ud t | jd | rt | jd | || | | | |||| t | jd t | jd t | jd t | jd t | jd tj	
 | j}| d | | | jdd	 t | jd t | jd
 d| j }|| \\}}\}	}
|| ||	 }}	|| ||
 }}
t|	| t|
| }}t | jd||f  t|D ]#}t|D ]}t | jd t | jd qt | jd|  t | jd qt | jd d S d S )Nr   r   r   r   \pgfusepath{clip}zN\pgfsys@defobject{currentpattern}{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{z=\pgfpathrectangle{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}T)r   rf   r5   r   z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})rF   rD   r   r   r   r   r   	get_hatchr   
transformsAffine2Dscalery   get_hatch_pathr   r   mathceilrange)r   r  r/   	transformr  r  r  xminyminxmaxymaxrepxrepyiyixr0   r0   r1   	draw_path  sX   



zRendererPgf.draw_pathc                 C   s   d| j  }| }|r7| \}}|| \}}|d | |d | || || f}t| jd|  t| jd | \}	}
|	d urP| ||	|
 t| jd d S d S )Nr5   r   r   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}r  )ry   get_clip_rectangler   rF   rD   get_clip_pathr   )r   r  r  bboxp1p2r   r   r	  clippathclippath_transr0   r0   r1   r     s"   
$zRendererPgf._print_pgf_clipc                 C   s~  dddd}t | j||   dddd}t | j||   |d u}| r/|  }}n| d	 }|rAt|d	krA|d	 nd
}|rYt | jdt|d d	   t | jd |rg|d
krgt | jd|  |	 t
 t }| }	t | jd|  t | jd|	d d	   t | jd |d
krt | jd|  | \}
}|d u rt | jd d S t | jdddd |D |
f  d S )Nz\pgfsetbuttcapz\pgfsetroundcapz\pgfsetrectcap)buttround
projectingz\pgfsetmiterjoinz\pgfsetroundjoinz\pgfsetbeveljoin)miterr*  bevel   r5   z(\definecolor{currentfill}{rgb}{%f,%f,%f}z\pgfsetfillcolor{currentfill}\pgfsetfillopacity{%f}z\pgfsetlinewidth{%fpt}z*\definecolor{currentstroke}{rgb}{%f,%f,%f}z!\pgfsetstrokecolor{currentstroke}\pgfsetstrokeopacity{%f}z\pgfsetdash{}{0pt}z\pgfsetdash{%s}{%fpt}r6   c                 s   s    | ]}d | V  qdS )z{%fpt}Nr0   )rI   dashr0   r0   r1   rL   ;  s    z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>)rF   rD   get_capstyleget_joinstyleget_forced_alpha	get_alphaget_rgbr   tupler   mpl_pt_to_inlatex_in_to_pt
get_dashesr(   )r   r  r  	capstyles
joinstyleshas_fillfillopacitystrokeopacitylwstroke_rgbadash_offset	dash_listr0   r0   r1   r     sZ   
z"RendererPgf._print_pgf_path_stylesc                 C   s  d| j  }|r| nd }|r(|d u r(| \}}|d |d |d |d f}	nd }	|j||	dD ]\}
}|tjkrOt|
\}}t| jd|| || f  q1|tj	kr[t| jd q1|tj
krut|
\}}t| jd|| || f  q1|tjkrt|
\}}}}|| || || || f}t| jd|  q1|tjkrt|
\}}}}}}|| || || || || || f}t| jd	|  q1d S )
Nr5   r   r   )clipz&\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}z\pgfpathclosez&\pgfpathlineto{\pgfqpoint{%fin}{%fin}}zH\pgfpathquadraticcurveto{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}zW\pgfpathcurveto{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}})ry   r"  r   r   r   MOVETOr7  rF   rD   	CLOSEPOLYLINETOCURVE3CURVE4)r   r  r/   r  r  r  r$  r%  r&  rD  pointsr  r  r  cxcypxpyr	  c1xc1yc2xc2yr0   r0   r1   r   >  sR   





(zRendererPgf._print_pgf_pathTc                 C   s:   g }|r	| d |r| d t| jdd|  d S )Nr   r   z\pgfusepath{%s}r   )r    rF   rD   r(   )r   r   r   actionsr0   r0   r1   r   f  s   

zRendererPgf._pgf_path_drawc                 C      dS )NTr0   r   r0   r0   r1   option_scale_imagen     zRendererPgf.option_scale_imagec                 C   s   t jd  S )Nzimage.composite_imager3   r   r0   r0   r1   option_image_nocompositer  s   z$RendererPgf.option_image_nocompositec              
   C   s  |j d d \}}|dks|dkrd S tjt| jdds"tdt| jj	}d|j
| jf }	t|d d d |j|	  |  jd7  _t| jd	 | | d
| j }
|d u rtt| jd||
 ||
 f  ||
 ||
 }}n.|  \}}}}}}t| jd||
 ||
 ||
 ||
 || |
 || |
 f  d }}t|d u  }t| jdt ||||	f  t| jd d S )Nr7   r   r%   r6   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionz%s-img%d.pngr   r   r5   r   z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zD\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}r   )shaperq   r/   existsgetattrrD   r   r"   r   r%   stemr   r   	fromarraysaver&   rF   r   ry   frozen	to_valuesrj   lowerr   )r   r  r  r  imr  r   r   r/   	fname_imgr  tr1tr2tr3tr4tr5tr6interpr0   r0   r1   
draw_imagev  sJ    

zRendererPgf.draw_imageTeX!c	           	   
   C   s   |  |||||||| d S rH   )	draw_text)	r   r  r  r  rA   r_   angleismathmtextr0   r0   r1   draw_tex  s   zRendererPgf.draw_texc	                 C   s  t |}t|}	d|	|f }t| jd | }
|
dkr,t| jd|
  t| jd|
  t| d d }t| jd|  t| jd t| jd	 d
| }| jj}g }|r|dks`|	 dkr|
 dkr| }| |\}}dddd}ddddd}|d|| ddd|| dd||  ||
  g n|d|| dd|| dd |dkr|d|  t| jdd||f  t| jd d S ) Nz%s %sr   r5   r/  r0  r.  z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   anchorcenter_baselineleftrightr6   )rt  ru  centertopbottombase)rw  rx  baselinerv  zx=r  inzy=zin, y=zin, left, basez	rotate=%fz\pgftext[%s]{%s}r   r   )rB   rc   rF   rD   r5  r7  r6  r   ry   get_rotation_modeget_verticalalignmentget_unitless_positionget_transformr  extendget_horizontalalignmentr    r(   )r   r  r  r  rA   r_   rn  ro  rp  r   alphargbry   	text_argsposhalignvalignr0   r0   r1   rm    sH   

$zRendererPgf.draw_textc                 C   s>   t |}t ||\}}}t| j }|| || || fS rH   )rB   r   r   r   r8  ry   )r   rA   r_   ro  r   r   dr  r0   r0   r1   get_text_width_height_descent  s   
z)RendererPgf.get_text_width_height_descentc                 C   rT  )NFr0   r   r0   r0   r1   flipy  rV  zRendererPgf.flipyc                 C   s    | j  | j | j  | j fS rH   )r   get_figwidthry   get_figheightr   r0   r0   r1   get_canvas_width_height  s   z#RendererPgf.get_canvas_width_heightc                 C   s   |t  | j S rH   )r8  ry   )r   rJ  r0   r0   r1   points_to_pixels  s   zRendererPgf.points_to_pixels)FrH   )TF)rl  N)FN)r   r   r   r   delete_parameterr   r  r!  r   r   r   r   rU  rW  rk  rq  rm  r  r  r  r  r   r0   r0   r   r1   r     s&    


"5
3
(

)
1r   r   r   )alternativec                   @   s   e Zd ZdS )GraphicsContextPgfN)r   r   r   r0   r0   r0   r1   r    s    r  3.4c                   @   s\   e Zd Ze Zejeddd Ze	eddd Z
e	edejdd ZdS )	TmpDirCleanerr  c                 C      | j S rH   )_remaining_tmpdirsr   r0   r0   r1   remaining_tmpdirs  r   zTmpDirCleaner.remaining_tmpdirsc                 C   s   t j|  d S rH   )r  r  addr   r0   r0   r1   r    s   zTmpDirCleaner.addc                     s0   t jD ]} d|  tj|  fddd qd S )Nzerror deleting tmp directory {}c                     s
   t  S rH   )rZ   error)r   error_messager0   r1   r     s   
 z9TmpDirCleaner.cleanup_remaining_tmpdirs.<locals>.<lambda>)onerror)r  r  r   r   rmtreer  r0   r  r1   cleanup_remaining_tmpdirs  s   


z'TmpDirCleaner.cleanup_remaining_tmpdirsN)r   r   r   setr  r   classpropertyr   r  r   r  atexitregisterr  r0   r0   r0   r1   r    s    r  c                       sh   e Zd ZddddZdd Zeddd	d
Zdd ZddddZdd Z	dd Z
 fddZ  ZS )FigureCanvasPgfzLaTeX PGF picturezLaTeX compiled PGF picturezPortable Network Graphics)pgfpdfpngc                 C   rT  )Nr  r0   r   r0   r0   r1   get_default_filetype     z$FigureCanvasPgf.get_default_filetypeNbbox_inches_restorec          
      C   s  d}dg}t   D ]	}|d|  q
t  D ]	}|d|  q|d d|}| j | j }}| j }|	| |	| |	d t
|d t
|d t
|d t
|d	||f  t
|d
 t| j|||t| j||d}	| j|	 t
|d t
|d t
|d d S )Na  %% Creator: Matplotlib, PGF backend
%%
%% To include the figure in your LaTeX document, write
%%   \input{<filename>.pgf}
%%
%% Make sure the required packages are loaded in your preamble
%%   \usepackage{pgf}
%%
%% Figures using additional raster images can only be included by \input if
%% they are in the same directory as the main LaTeX file. For loading figures
%% from other directories you can use the `import` package
%%   \usepackage{import}
%%
%% and then include the figures with
%%   \import{<path to file>}{<filename>.pgf}
%%
z)%% Matplotlib used the following preamblez%%   z%%r   z\begingroupz\makeatletterz\begin{pgfpicture}z:\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}z&\pgfusepath{use as bounding box, clip}r  z\end{pgfpicture}z\makeatotherz	\endgroup)r4   r   r    r2   r(   r   r  r  get_dpirC   rF   r   r   draw)
r   rD   r  header_textheader_info_preamblerE   r   r   ry   rendererr0   r0   r1   _print_pgf_to_fh  s<   












z FigureCanvasPgf._print_pgf_to_fhc                 O   sf   t j|ddd!}t |std|}| j|g|R i | W d   dS 1 s,w   Y  dS )zy
        Output pgf macros for drawing the figure so it can be included and
        rendered in latex documents.
        r   r   r   N)r   open_file_cmfile_requires_unicodecodecs	getwriterr  )r   fname_or_fhr   r   filer0   r0   r1   	print_pgfN  s
   
"zFigureCanvasPgf.print_pgf)metadatac             
   O   sN  | j  | j  }}td|pi }ddd | D }t |}	t|	}
| j	|
d g|R i | d|||t
 t f }|
d j|dd	 tjd
 }tj|dddgt|	d |
d d$}t|d}t|| W d   n1 syw   Y  W d   n1 sw   Y  W d   dS W d   dS 1 sw   Y  dS )z3Use LaTeX to compile a pgf generated figure to pdf.r  r   c                 s       | ]
\}}t ||V  qd S rH   rm   rI   kvr0   r0   r1   rL   ]      
z,FigureCanvasPgf.print_pdf.<locals>.<genexpr>z
figure.pgfa  
\PassOptionsToPackage{pdfinfo={%s}}{hyperref}
\RequirePackage{hyperref}
\documentclass[12pt]{minimal}
\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry}
%s
%s
\usepackage{pgf}

\begin{document}
\centering
\input{figure.pgf}
\end{document}z
figure.texr   r  r   -interaction=nonstopmoder   r   
figure.pdfrbwbN)r   r  r  r   r(   itemsr   r"   r   r  r4   r2   
write_textr   r   r   _check_and_log_subprocessrZ   openr  r   copyfileobj)r   r  r  r   r   r   r   	info_dicthyperref_optionsr   tmppath	latexcoder*   origdestr0   r0   r1   	print_pdfX  s<   



 "zFigureCanvasPgf.print_pdfc              
   O   s   t  }t d}t|}|d }|d }| j|g|R i | |||| jjd |d$}	t	|d}
t
|	|
 W d   n1 sFw   Y  W d   n1 sUw   Y  W d   dS W d   dS 1 smw   Y  dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.r  z
figure.png)ry   r  r  N)r   r   r"   r   r  r   ry   r  r   r  r   r  )r   r  r   r   	converterr   r  pdf_pathpng_pathr  r  r0   r0   r1   	print_png~  s$   

 "zFigureCanvasPgf.print_pngc                 C   s   t | jd S rH   )r   r   r   r0   r0   r1   get_renderer     zFigureCanvasPgf.get_rendererc                    s   t | j t  S rH   )r   r   r   r  r   r   r0   r1   r    s   

zFigureCanvasPgf.draw)r   r   r   	filetypesr  r	   r  r  r  r  r  r  r   r0   r0   r   r1   r    s    6
&r  c                   @   s   e Zd ZeZdS )_BackendPgfN)r   r   r   r  FigureCanvasr0   r0   r0   r1   r    s    r  c                   @   st   e Zd ZdZdZededd Zdddd	d
Z	dd Z
dd Zdd Zdd Zdd ZdddZdd ZdS )PdfPagesa  
    A multi-page PDF file using the pgf backend

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> # Initialize:
    >>> with PdfPages('foo.pdf') as pdf:
    ...     # As many times as you like, create a figure fig and save it:
    ...     fig = plt.figure()
    ...     pdf.savefig(fig)
    ...     # When no figure is specified the current figure is saved
    ...     pdf.savefig()
    )_output_name
keep_empty
_n_figures_file
_info_dict	_metadatar   c                 C   r  rH   )r  r   r0   r0   r1   r     s    zPdfPages.<lambda>TN)r  r  c                C   s   || _ d| _|| _|pi  | _|rA|D ],}ddd| |  }||kr@tj	dd| d| dd	 | j
|| j|< qtd
| j| _t | _dS )a<  
        Create a new PdfPages object.

        Parameters
        ----------
        filename : str or path-like
            Plots using `PdfPages.savefig` will be written to a file at this
            location. Any older file with the same name is overwritten.

        keep_empty : bool, default: True
            If set to False, then empty pdf files will be deleted automatically
            when closed.

        metadata : dict, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.

            Note that some versions of LaTeX engines may ignore the 'Producer'
            key and set it to themselves.
        r   CreationDateModDate)creationdatemoddater   z|Support for setting PDF metadata keys case-insensitively is deprecated since %(since)s and will be removed %(removal)s; set z instead of .)r   r  N)r  r  r  copyr  getra  titler   warn_deprecatedpopr   r  r   r  )r   filenamer  r  rk   	canonicalr0   r0   r1   r     s.   zPdfPages.__init__c                 C   sP   d dd | j D }t }t }dj|||||d}| j|d d S )Nr   c                 s   r  rH   r  r  r0   r0   r1   rL     r  z)PdfPages._write_header.<locals>.<genexpr>aC  \PassOptionsToPackage{{
  pdfinfo={{
    {metadata}
  }}
}}{{hyperref}}
\RequirePackage{{hyperref}}
\documentclass[12pt]{{minimal}}
\usepackage[
    paperwidth={width}in,
    paperheight={height}in,
    margin=0in
]{{geometry}}
{preamble}
{fontspec}
\usepackage{{pgf}}
\setlength{{\parindent}}{{0pt}}

\begin{{document}}%%
)r   r   preamblefontspecr  r   )	r(   r  r  r4   r2   r   r  rC   encode)r   width_inchesheight_inchesr  r   r)   r   r0   r0   r1   _write_header  s   
zPdfPages._write_headerc                 C   s   | S rH   r0   r   r0   r0   r1   	__enter__  r  zPdfPages.__enter__c                 C   s   |    d S rH   )close)r   exc_typeexc_valexc_tbr0   r0   r1   __exit__  r  zPdfPages.__exit__c                 C   sD   | j d | jdkr|   n| jrt| jd  | j   dS )z
        Finalize this object, running LaTeX in a temporary directory
        and moving the final pdf file to *filename*.
        s   \end{document}\nr   r  N)r  rC   r  
_run_latexr  r  r  r  r   r0   r0   r1   r  
  s   

zPdfPages.closec                 C   s~   t jd }t -}t|d}|| j  tj	|dd|gt
|d t|d| j W d    d S 1 s8w   Y  d S )Nr   zpdf_pages.texr  r   r  z.pdf)r   r   r   r"   r   write_bytesr  getvaluer   r  rZ   r   movewith_suffixr  )r   r*   r   
tex_sourcer0   r0   r1   r    s   
"zPdfPages._run_latexc                 K   s   t |ts"|du rt }nt|}|du rtd||jj}z=|j}t	||_|
 \}}| jdkr=| || n
| jd||f  |j| jfddi| |  jd7  _W ||_dS ||_w )a  
        Save a `.Figure` to this file as a new page.

        Any other keyword arguments are passed to `~.Figure.savefig`.

        Parameters
        ----------
        figure : `.Figure` or int, optional
            Specifies what figure is saved to file. If not specified, the
            active figure is saved. If a `.Figure` instance is provided, this
            figure is saved. If an int is specified, the figure instance to
            save is looked up by number.
        NzNo figure {}r   s   \newpage\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%ain\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%ain%%
r   r  r   )rg   r   r   
get_activeget_fig_managerr   r   canvasr   r  get_size_inchesr  r  r  rC   savefig)r   r   r   managerorig_canvasr   r   r0   r0   r1   r  !  s*   




	zPdfPages.savefigc                 C   r  )z=Return the current number of pages in the multipage pdf file.)r  r   r0   r0   r1   get_pagecountQ  s   zPdfPages.get_pagecountrH   )r   r   r   r   	__slots__r   r   propertyr  r   r  r  r  r  r  r  r  r0   r0   r0   r1   r    s    /!
0r  )Nr  r  rh   r   ior   loggingr  rq   r"   rer   rs   tempfiler   r   PILr   
matplotlibr   r   r   r   r#   matplotlib.backend_basesr   r	   r
   r   r   r   r   !matplotlib.backends.backend_mixedr   matplotlib.backends.backend_pdfr   r   matplotlib.pathr   matplotlib.figurer   matplotlib._pylab_helpersr   	getLoggerr   rZ   r2   r4   latex_pt_to_inr9  r8  mpl_in_to_pt	NO_ESCAPEcompiler:   partialsubr=   r8   rB   rF   rc   rm   r   r   r   r   r   r   r   r   r  r  r  FigureManagerPgfexportr  r  r0   r0   r0   r1   <module>   sz    $
	 *
  o 