B
    ]t\                 @   sB  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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mZmZmZmZ d dlmZmZmZmZmZ d dlmZ d dlmZ d dl m!Z! d dl"m#Z# d dl$m%Z% e&e'Z(e)d	d
d Z*dd Z+dd Z,dZ-de- Z.dZ/de/ Z0dZ1e2e1d Z3e2e1d Z4dd Z5e2e1d Z6dd Z7dd Z8dd Z9dd Z:d d! Z;G d"d# d#e<Z=G d$d% d%Z>G d&d' d'Z?G d(d) d)eZ@G d*d+ d+eZAG d,d- d-ZBG d.d/ d/eZCG d0d1 d1eZDejEG d2d3 d3eZFd4d5 ZGe HeG G d6d7 d7ZIdS )8    N)_pngcbookfont_manager__version__rcParams)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)MixedModeRenderer)is_writable_file_like)Path)Figure)Gcfz3.0c              C   s"   dddg} t d }|| kr|S dS )zGet chosen TeX system from rc.ZxelatexZlualatexpdflatexzpgf.texsystem)r   )Ztexsystem_optionsZ	texsystem r   >lib/python3.7/site-packages/matplotlib/backends/backend_pgf.pyget_texcommand!   s    
r   c              C   s   g } t d }|dkr| d |dkrt d rdddg}dd	d
g}xFt||D ]8\}}tt|}| d||j|j	 d f  qNW d
| S )z Build fontspec preamble from rc.zpgf.texsystemr   z\usepackage{fontspec}zpgf.rcfontsserifzsans\-serif	monospaceZsetmainfontZsetsansfontZsetmonofontz\%s{%s}[Path=%s]/
)r   appendzippathlibr   fmZfindfontnameparentZas_posixjoin)latex_fontspec
texcommandfamiliescommandsfamilyZcommandpathr   r   r   get_fontspec)   s    


r&   c               C   s   d td S )zGet LaTeX preamble from rc.r   zpgf.preamble)r   r   r   r   r   r   get_preamble>   s    r'   gRhV?g      ?gqq?z(?<!\\)(?:\\\\)*z\$z([_^$%])c             C   s   d|  d S )N\   )group)mr   r   r   <lambda>R   s    r,   z(\\mathdefault)c             C   s   |  dd t|  d  S )Nr   r)   )r*   len)r+   r   r   r   r,   T   s    c             C   s\   t t| } t| }x:t|D ].\}}|d s>tt|}nd| }|||< q W d|S )zh
    Do some necessary and/or useful substitutions for texts to be included in
    LaTeX documents.
       z\(\displaystyle %s\) )	re_mathdefaultsubrepl_mathdefault
re_mathsepsplit	enumeratere_escapetextrepl_escapetextr   )textpartsisr   r   r   common_texificationW   s    
r<   c             C   s   |  | |  d d S )Nz%
)write)fhliner   r   r   writelno   s    
r@   c                s   g }ddddd}|   d   |kr6||   n6t fddtjjD rltd d	krl|d
   n |  }|d||d f  dddd}|||    dddddddg}| 	 |kr|d |d d
|S )Nz	\rmfamilyz	\sffamilyz	\ttfamily)r   Zsansz
sans-serifr   r   c             3   s   | ]}|j  kV  qd S )N)r   ).0Zfont)r$   r   r   	<genexpr>   s    z'_font_properties_str.<locals>.<genexpr>zpgf.texsystemr   z\setmainfont{%s}\rmfamilyz\fontsize{%f}{%f}g333333?r/   z\itshapez\slshape)ZnormalZitalicZobliqueZsemiboldZdemiboldZdemiZboldZheavyz
extra boldZblackz	\bfseriesz\selectfont)Z
get_familyr   anyr   ZfontManagerZttflistr   Zget_size_in_pointsZ	get_styleZ
get_weightr   )propr#   r"   sizeZstylesZ
boldstylesr   )r$   r   _font_properties_strv   s&    



rF   c                 s   g } y"t jddgt jd | d W n tk
r:   Y nX t \ } rV| d d| krjdd }|S d| kr fdd}|S td	d
S )zD
    Returns a function that converts a pdf file to a png file.
    
pdftocairoz-v)stderrgsc          	   S   s6   ddddd| | t j|d g}tj|tjd d S )NrG   z-singlefilez-pngz-rz%dr   )rH   )osr%   splitext
subprocesscheck_outputSTDOUT)pdffilepngfiledpicmdr   r   r   cairo_convert   s    z0make_pdf_to_png_converter.<locals>.cairo_convertc                s<    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%d)rH   )rL   rM   rN   )rO   rP   rQ   rR   )rI   r   r   
gs_convert   s    
z-make_pdf_to_png_converter.<locals>.gs_convertz&No suitable pdf to png renderer found.N)rL   rM   rN   r   OSErrormplZcheckdep_ghostscriptRuntimeError)Ztools_availableZverrS   rT   r   )rI   r   make_pdf_to_png_converter   s     
rX   c                   s   e Zd Zd fdd	Z  ZS )
LatexErrorr/   c                s   t  | || _d S )N)super__init__latex_output)selfmessager\   )	__class__r   r   r[      s    zLatexError.__init__)r/   )__name__
__module____qualname__r[   __classcell__r   r   )r_   r   rY      s   rY   c               @   s   e Zd ZdZedd ZdS )LatexManagerFactoryNc              C   sZ   t d } t }tj}|r<|j|kr<|j| kr<td |S td t }|t_|S d S )Nzpgf.texsystemzreusing LatexManagerzcreating LatexManager)	r   LatexManager_build_latex_headerrd   previous_instancelatex_headerr!   _logdebug)r!   rh   prevZnew_instr   r   r   get_latex_manager   s    


z%LatexManagerFactory.get_latex_manager)r`   ra   rb   rg   staticmethodrl   r   r   r   r   rd      s   rd   c               @   sh   e Zd ZdZe Zedd Zedd Z	dd Z
dd	 Zd
d Zdd Zdd Zdd Zdd ZdS )re   z
    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 custem preamble in the rc parameters.
    c              C   s&   t  } t }d| |dddg}d|S )Nz\documentclass{minimal}z\begin{document}ztext $math \mu$z!\typeout{pgf_backend_query_start}r   )r'   r&   r   )latex_preambler    rh   r   r   r   rf      s    z LatexManager._build_latex_headerc              C   s$   t tj} x| D ]}|  qW d S )N)listre   _unclean_instances_cleanup)Zunclean_instancesZlatex_managerr   r   r   _cleanup_remaining_instances   s    

z)LatexManager._cleanup_remaining_instancesc             C   s&   | j | | j d | j   d S )Nr   )latex_stdin_utf8r=   flush)r]   r;   r   r   r   _stdin_writeln   s    zLatexManager._stdin_writelnc             C   sf   | d}t }xJ| jjd}||7 }|t| d  |kr@P t|std|dqW |dS )Nutf8r)   zLaTeX process halted)encode	bytearraylatexstdoutreadr-   rY   decode)r]   r;   ZexpZbufbr   r   r   _expect   s    
zLatexManager._expectc             C   s
   |  dS )Nz
*)r~   )r]   r   r   r   _expect_prompt  s    zLatexManager._expect_promptc             C   s<  t j| _t| _tjdd| _tj	
|  td | _t | _d}y"tj| jdgtjtj| jd}W nB tk
r   td| j Y n" tk
r   td| j Y nX | j| }||d	\}}|jd
krtd| tj| jdgtjtj| jd}|| _td| jj| _| |   | d |    i | _!d S )NZmpl_pgf_lm_)prefixzpgf.texsystemz
\makeatletter
\@@end
z-halt-on-error)stdinrz   cwdzSLatex command not found. Install %r or change pgf.texsystem to the desired command.zError starting process %rzutf-8r   zGLaTeX returned an error, probably missing font or error in preamble:
%srv   z*pgf_backend_query_start)"rJ   r%   _os_pathshutil_shutiltempfilemkdtemptmpdirre   rp   addr   r!   rf   rh   rL   PopenPIPEFileNotFoundErrorrW   rU   communicaterw   
returncoderY   ry   codecs	getwriterr   rs   ru   r~   r   	str_cache)r]   Z	latex_endry   Z
test_inputrz   rH   r   r   r   r[     s@    





zLatexManager.__init__c             C   s   | j | jsd S y$| j  | j  | jj  W n tk
rJ   Y nX y| j	
| j tj|  W n& tk
r   tjd| j  Y nX d S )Nz error deleting tmp directory %s
)r   isdirr   ry   r   rs   closerz   	Exceptionr   rmtreere   rp   discardsysrH   r=   )r]   r   r   r   rq   3  s    

zLatexManager._cleanupc             C   s   t d |   d S )Nzdeleting LatexManager)ri   rj   rq   )r]   r   r   r   __del__B  s    
zLatexManager.__del__c          
   C   sP  t |}d||f }|| jkr(| j| S | | y|   W n4 tk
rr } ztd||jW dd}~X Y nX | d y|  }W n4 tk
r } ztd||jW dd}~X Y nX y| d 	d\}}}	W n   td||Y nX t
|dd t
|dd t
|	dd   }
}}|
|| |f| j|< |
|| |fS )zy
        Get the width, total height and descent for a text typesetted by the
        current LaTeX environment.
        z\sbox0{%s %s}z&Error processing '{}'
LaTeX Output:
{}Nz$\typeout{\the\wd0,\the\ht0,\the\dp0}r   ,)rF   r   ru   r   rY   
ValueErrorformatr\   
splitlinesr4   float)r]   r8   rD   	prop_cmdsZtextboxeZanswerwidthheightoffsetwhor   r   r   get_width_height_descentF  s0    



4z%LatexManager.get_width_height_descentN)r`   ra   rb   __doc__weakrefWeakSetrp   rm   rf   rr   ru   r~   r   r[   rq   r   r   r   r   r   r   re      s   -re   c               @   s   e Zd Zd'ddZd(ddZd)ddZd	d
 Zdd Zd*ddZd+ddZ	dd 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d%d& ZdS )/RendererPgfFc             C   s   t |  |j| _|| _|| _d| _t | _|r`dd }xZt	j
D ]}|drB|| j
|< qBW n6t|drxtj|jstjdtdd d	d | j
d
< dS )a  
        Creates 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   c              _   s   d S )Nr   )argskwargsr   r   r   r,     s    z&RendererPgf.__init__.<locals>.<lambda>Zdraw_r   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionr.   )
stacklevelc              _   s   d S )Nr   )r   r   r   r   r   r,     s    
draw_imageN)r   r[   rQ   r>   figureimage_counterrd   rl   latexManagerr   __dict__
startswithhasattrrJ   r%   existsr   warningswarnUserWarning)r]   r   r>   dummyZnopr+   r   r   r   r[   u  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 k	d t | jd xl|j
|d	d
D ]Z\}}|d | |d |  }}t | jd t | jd||f  t | jd t | jd qW t | jd d S )Nz\begin{pgfscope}g      ?r   r)   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{g        )strokefill}F)Zsimplifyz"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}z\end{pgfscope})r@   r>   rQ   _print_pgf_clip_print_pgf_path_stylesget_extents
get_points_print_pgf_path_pgf_path_drawget_linewidthiter_segments)r]   gcZmarker_pathZmarker_transr%   ZtransrgbFacefZblZtrcoordsZpointcodexyr   r   r   draw_markers  s(    

,zRendererPgf.draw_markersc             C   s  t | jd | | | || | |||| | j| dk|d k	d t | jd | rt | 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t|
|  }}t | jd||f  xZt|D ]N}x*t|D ]}t | jd t | jd qW t | jd|  t | jd qW t | jd d S )Nz\begin{pgfscope}g        )r   r   z\end{pgfscope}z\pgfusepath{clip}zN\pgfsys@defobject{currentpattern}{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{z=\pgfpathrectangle{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}T)r   r   g      ?z"\pgfsys@transformshift{%fin}{%fin}z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})r@   r>   r   r   r   r   r   Z	get_hatchrV   Z
transformsZAffine2DscalerQ   Zget_hatch_pathr   r   intmathZceilrange)r]   r   r%   	transformr   r   r   ZxminZyminZxmaxZymaxZrepxZrepyZiyZixr   r   r   	draw_path  sL    



&zRendererPgf.draw_pathc             C   s   d| j  }| }|rn| \}}|| \}}|d | |d | || || f}t| jd|  t| jd | \}	}
|	d k	r| ||	|
 t| jd d S )Ng      ?r   r)   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}z\pgfusepath{clip})rQ   get_clip_rectangler   r@   r>   Zget_clip_pathr   )r]   r   r   bboxp1p2r   r   r   ZclippathZclippath_transr   r   r   r     s    
$zRendererPgf._print_pgf_clipc             C   s  dddd}t | j||   dddd}t | j||   |d k	}| r^|  }}n(| d	 }|rt|d	kr|d	 nd
}|rt | jdt|d d	   t | jd |r|d
krt | jd|  |	 t
 t }| }	t | jd|  t | jd|	d d	   t | jd |d
kr4t | jd|  | \}
}|d krXt | jd n$t | jdddd |D |
f  d S )Nz\pgfsetbuttcapz\pgfsetroundcapz\pgfsetrectcap)ZbuttroundZ
projectingz\pgfsetmiterjoinz\pgfsetroundjoinz\pgfsetbeveljoin)Zmiterr   Zbevel   g      ?z(\definecolor{currentfill}{rgb}{%f,%f,%f}z\pgfsetfillcolor{currentfill}z\pgfsetfillopacity{%f}z\pgfsetlinewidth{%fpt}z*\definecolor{currentstroke}{rgb}{%f,%f,%f}z!\pgfsetstrokecolor{currentstroke}z\pgfsetstrokeopacity{%f}z\pgfsetdash{}{0pt}z\pgfsetdash{%s}{%fpt}r/   c             s   s   | ]}d | V  qdS )z{%fpt}Nr   )rA   Zdashr   r   r   rB   1  s    z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>)r@   r>   Zget_capstyleZget_joinstyleZget_forced_alpha	get_alphaget_rgbr-   tupler   mpl_pt_to_inlatex_in_to_ptZ
get_dashesr   )r]   r   r   Z	capstylesZ
joinstylesZhas_fillZfillopacityZstrokeopacityZlwZstroke_rgbaZdash_offsetZ	dash_listr   r   r   r     sH    

z"RendererPgf._print_pgf_path_stylesc             C   s  d| j  }|r| nd }|rP|d krP| \}}|d |d |d |d f}	nd }	x<|j||	dD ](\}
}|tjkrt|
\}}t| jd|| || f  qf|tj	krt| jd qf|tj
krt|
\}}t| jd|| || f  qf|tjkr:t|
\}}}}|| || || || f}t| jd|  qf|tjkrft|
\}}}}}}|| || || || || || f}t| jd	|  qfW d S )
Ng      ?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}})rQ   r   r   r   r   ZMOVETOr   r@   r>   Z	CLOSEPOLYZLINETOZCURVE3ZCURVE4)r]   r   r%   r   r   r   r   r   r   r   pointsr   r   r   ZcxZcyZpxpyr   Zc1xZc1yZc2xZc2yr   r   r   r   4  s>    





(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   r@   r>   r   )r]   r   r   Zactionsr   r   r   r   \  s    

zRendererPgf._pgf_path_drawc             C   s   dS )zA
        pgf backend supports affine transform of image.
        Tr   )r]   r   r   r   option_scale_imaged  s    zRendererPgf.option_scale_imagec             C   s
   t d  S )zl
        return whether to generate a composite image from multiple images on
        a set of axes
        zimage.composite_image)r   )r]   r   r   r   option_image_nocompositej  s    z$RendererPgf.option_image_nocompositec          
   C   sz  |j d d \}}|dks"|dkr&d S tj| jj}tjtj| jjd }	d|	| jf }
|  jd7  _t	
|d d d tj||
 t| jd | | d| j }|d krt| jd|| || f  || ||  }}n\|  \}}}}}}t| jd	|| || || || || | || | f  d }}t|d k }t| jd
||||
f  t| jd d S )Nr.   r   z%s-img%d.pngr)   z\begin{pgfscope}g      ?z"\pgfsys@transformshift{%fin}{%fin}z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zK\pgftext[left,bottom]{\pgfimage[interpolate=%s,width=%fin,height=%fin]{%s}}z\end{pgfscope})shaperJ   r%   dirnamer>   r   rK   basenamer   r   Z	write_pngr   r@   r   rQ   frozenZ	to_valuesstrlower)r]   r   r   r   Zimr   r   r   r%   fnameZ	fname_imgr   Ztr1Ztr2Ztr3Ztr4Ztr5Ztr6Zinterpr   r   r   r   q  s4     

zRendererPgf.draw_imageTeX!c	       	   
   C   s   |  |||||||| d S )N)	draw_text)	r]   r   r   r   r;   rD   angleismathmtextr   r   r   draw_tex  s    zRendererPgf.draw_texc	             C   s  t |}t|}	d|	|f }t| jd | }
|
dkrXt| jd|
  t| jd|
  t| d d }t| jd|  t| jd t| jd	 d
| }d| jj }g }|rT|dks|	 dkrT|
 dkrT| }| |\}}|d||   |d||   dddd}ddddd}|||   |||
   n8|d||   |d||   |d |d |dkr|d|  t| jdd||f  t| jd d S )Nz%s %sz\begin{pgfscope}g      ?z\pgfsetfillopacity{%f}z\pgfsetstrokeopacity{%f}r   z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   ZanchorZcenter_baselinezx=%finzy=%finleftrightr/   )r   r   centertopbottombase)r   r   Zbaseliner   z	rotate=%fz\pgftext[%s]{%s}r   z\end{pgfscope})r<   rF   r@   r>   r   r   r   r   rQ   Zget_rotation_modeZget_vaZget_unitless_positionZget_transformZtransform_pointr   Zget_har   )r]   r   r   r   r;   rD   r   r   r   r   ZalphaZrgbr   Z	text_argsposZhalignZvalignr   r   r   r     sH    



zRendererPgf.draw_textc             C   s<   t |}| j||\}}}t| j }|| || || fS )N)r<   r   r   r   rQ   )r]   r;   rD   r   r   r   dr   r   r   r   get_text_width_height_descent  s    
z)RendererPgf.get_text_width_height_descentc             C   s   dS )NFr   )r]   r   r   r   flipy  s    zRendererPgf.flipyc             C   s   | j  | j  fS )N)r   get_figwidthget_figheight)r]   r   r   r   get_canvas_width_height  s    z#RendererPgf.get_canvas_width_heightc             C   s   |t  | j S )N)r   rQ   )r]   r   r   r   r   points_to_pixels  s    zRendererPgf.points_to_pixelsc             C   s   t  S )N)GraphicsContextPgf)r]   r   r   r   new_gc  s    zRendererPgf.new_gc)F)N)N)N)TF)N)r   N)FN)r`   ra   rb   r[   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r   s  s"   
%

43
(

"

2r   c               @   s   e Zd ZdS )r   N)r`   ra   rb   r   r   r   r   r     s   r   c               @   s*   e Zd Ze Zedd Zedd ZdS )TmpDirCleanerc             C   s   t j|  d S )N)r  remaining_tmpdirsr   )r   r   r   r   r     s    zTmpDirCleaner.addc                  s*   x$t jD ] tj  fddd qW d S )Nc                 s   t d  tjdS )Nzerror deleting tmp directory %s)file)printr   rH   )r   )r   r   r   r,     s   z9TmpDirCleaner.cleanup_remaining_tmpdirs.<locals>.<lambda>)onerror)r  r  r   r   r   r   )r   r   cleanup_remaining_tmpdirs  s    z'TmpDirCleaner.cleanup_remaining_tmpdirsN)r`   ra   rb   setr  rm   r   r  r   r   r   r   r    s   r  c               @   s`   e Zd ZddddZ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 ZdS )FigureCanvasPgfzLaTeX PGF picturezLaTeX compiled PGF picturezPortable Network Graphics)pgfpdfZpngc             C   s   dS )Nr  r   )r]   r   r   r   get_default_filetype  s    z$FigureCanvasPgf.get_default_filetypeFN)dryrunbbox_inches_restorec            O   sJ  |r$t | jd dd}| j| d S d}dg}x t  D ]}	|d|	  q:W x t  D ]}	|d|	  q\W |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 )NT)r   a  %% 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)r   r   Zdrawr'   r   r   r&   r   r   r   Zget_dpir=   r@   r   )r]   r>   r  r  r   r   ZrendererZheader_textZheader_info_preambler?   r   r   rQ   r   r   r   _print_pgf_to_fh  s>    












z FigureCanvasPgf._print_pgf_to_fhc          	   O   s   | ddr | jd|| dS t|trXt|ddd}| j|f|| W dQ R X n2t|rtd|}| j|f|| ntddS )	z{
        Output pgf commands for drawing the figure so it can be included and
        rendered in latex documents.
        r  FNr   zutf-8)encodingzfilename must be a path)N)	getr  
isinstancer   openr   r   r   r   )r]   fname_or_fhr   r   r>   r   r   r   	print_pgf9  s    
zFigureCanvasPgf.print_pgfc             O   sF  | j  | j   }}z tjdd}tj|d}tj|d}tj|d}	| j|f|| t	 }
t
 }d|||
|f }t|j|dd td	 }|d
ddg}ytj|tj|d W n6 tjk
r } ztd||jf W d d }~X Y nX t|	d}t|| W d Q R X W d yt| W n   t| Y nX X d S )Nmpl_pgf_)r   z
figure.pgfz
figure.texz
figure.pdfz
\documentclass[12pt]{minimal}
\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry}
%s
%s
\usepackage{pgf}

\begin{document}
\centering
\input{figure.pgf}
\end{document}zutf-8)r  zpgf.texsystemz-interaction=nonstopmodez-halt-on-error)rH   r   z3%s was not able to process your file.

Full log:
%srb)r   r   r   r   r   rJ   r%   r   r  r'   r&   r   r   Z
write_textr   rL   rM   rN   CalledProcessErrorrW   outputr  r   copyfileobjr   r  r   )r]   r>   r   r   r   r   r   Z	fname_pgfZ	fname_tex	fname_pdfrn   r    Z	latexcoder!   cmdargsr   fh_srcr   r   r   _print_pdf_to_fhL  s6     z FigureCanvasPgf._print_pdf_to_fhc          	   O   s|   | ddr | jd|| dS t|trTt|d}| j|f|| W dQ R X n$t|rp| j|f|| ntddS )zE
        Use LaTeX to compile a Pgf generated figure to PDF.
        r  FNwbz-filename must be a path or a file-like object)N)r  r  r  r   r  r  r   r   )r]   r  r   r   r>   r   r   r   	print_pdf|  s    
zFigureCanvasPgf.print_pdfc       	      O   s   t  }zrtjdd}tj|d}tj|d}| j|f|| |||| jjd t	|d}t
|| W d Q R X W d yt
| W n   t| Y nX X d S )Nr  )r   z
figure.pdfz
figure.png)rQ   r  )rX   r   r   rJ   r%   r   r   r   rQ   r  r   r  r   r  r   )	r]   r>   r   r   Z	converterr   r  Z	fname_pngr  r   r   r   _print_png_to_fh  s    z FigureCanvasPgf._print_png_to_fhc          	   O   s|   | ddr | jd|| dS t|trTt|d}| j|f|| W dQ R X n$t|rp| j|f|| ntddS )zQ
        Use LaTeX to compile a pgf figure to pdf and convert it to png.
        r  FNr  z-filename must be a path or a file-like object)N)r  r  r  r   r  r!  r   r   )r]   r  r   r   r>   r   r   r   	print_png  s    
zFigureCanvasPgf.print_pngc             C   s   t | jd ddS )NT)r   )r   r   )r]   r   r   r   get_renderer  s    zFigureCanvasPgf.get_renderer)r`   ra   rb   Z	filetypesr  r  r  r  r   r!  r"  r#  r   r   r   r   r	    s   90r	  c               @   s   e Zd ZdS )FigureManagerPgfN)r`   ra   rb   r   r   r   r   r$    s   r$  c               @   s   e Zd ZeZeZdS )_BackendPgfN)r`   ra   rb   r	  ZFigureCanvasr$  ZFigureManagerr   r   r   r   r%    s   r%  c               C   s   t   t  d S )N)re   rr   r  r  r   r   r   r   _cleanup_all  s    r&  c               @   s^   e Zd ZdZ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()
    )	_outputfile
keep_empty_tmpdir	_basename
_fname_tex
_fname_pdf
_n_figures_filemetadataTN)r)  r0  c            C   sr   || _ d| _|| _|pi | _tjdd| _d| _tj	
| j| jd | _tj	
| j| jd | _t| jd| _dS )	a  
        Create a new PdfPages object.

        Parameters
        ----------

        filename : str
            Plots using :meth:`PdfPages.savefig` will be written to a file at
            this location. Any older file with the same name is overwritten.
        keep_empty : bool, optional
            If set to False, then empty pdf files will be deleted automatically
            when closed.
        metadata : dictionary, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            `{'Creator': 'My software', 'Author': 'Me',
            'Title': 'Awesome fig'}`

            The standard keys are `'Title'`, `'Author'`, `'Subject'`,
            `'Keywords'`, `'Producer'`, `'Creator'` and `'Trapped'`.
            Values have been predefined for `'Creator'` and `'Producer'`.
            They can be removed by setting them to the empty string.
        r   Zmpl_pgf_pdfpages_)r   Z	pdf_pagesz.texz.pdfr  N)r(  r.  r)  r0  r   r   r*  r+  rJ   r%   r   r,  r-  r  r/  )r]   filenamer)  r0  r   r   r   r[     s    
zPdfPages.__init__c             C   s   dddddddh}dt  d	t  d
}dd | j D }|| d}xF| D ]:\}}||krntd||d| d t| d 7 }qPW t }	t }
dj|||	|
|d}| j	
|d d S )NtitleZauthorZsubjectkeywordscreatorproducerZtrappedz%matplotlib %s, https://matplotlib.orgzmatplotlib pgf backend %s)r4  r5  c             S   s   i | ]\}}||  qS r   )r   )rA   kvr   r   r   
<dictcomp>  s    z*PdfPages._write_header.<locals>.<dictcomp>r/   z(Not a supported pdf metadata field: "{}"r  z={z},a/  \PassOptionsToPackage{{
  {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   ZpreambleZfontspecr0  zutf-8)r   r0  itemsupdater   r   r   r'   r&   r/  r=   rw   )r]   Zwidth_inchesZheight_inchesZsupported_keysZinfoDictr0  Zhyperref_optionsr6  r7  rn   r    rh   r   r   r   _write_header  s*    

 zPdfPages._write_headerc             C   s   | S )Nr   )r]   r   r   r   	__enter__5  s    zPdfPages.__enter__c             C   s   |    d S )N)r   )r]   exc_typeZexc_valZexc_tbr   r   r   __exit__8  s    zPdfPages.__exit__c             C   sv   | j d | j   | jdkr\z|   W dyt| j W n   t	| j Y nX X n| j
rrt| jd  dS )z
        Finalize this object, running LaTeX in a temporary directory
        and moving the final pdf file to `filename`.
        s   \end{document}\nr   Nr  )r/  r=   r   r.  
_run_latexr   r   r*  r  r   r)  r  r(  )r]   r   r   r   r   ;  s    

zPdfPages.closec          
   C   s   t d }|ddtj| jg}ytj|tj| jd W n< tj	k
rr } zt
d||jdf W d d }~X Y nX t| j| j d S )Nzpgf.texsystemz-interaction=nonstopmodez-halt-on-error)rH   r   z3%s was not able to process your file.

Full log:
%szutf-8)r   rJ   r%   r   r,  rL   rM   rN   r*  r  rW   r  r|   r   Zcopyfiler-  r(  )r]   r!   r  r   r   r   r   r?  N  s    &zPdfPages._run_latexc             K   s   t |tsD|dkrt }n
t|}|dkr<td||jj}zr|j}t	||_|
 \}}| jdkrz| || n| jd||f  |j| jfddi| |  jd7  _W d||_X dS )aQ  
        Saves a :class:`~matplotlib.figure.Figure` to this file as a new page.

        Any other keyword arguments are passed to
        :meth:`~matplotlib.figure.Figure.savefig`.

        Parameters
        ----------

        figure : :class:`~matplotlib.figure.Figure` or int, optional
            Specifies what figure is saved to file. If not specified, the
            active figure is saved. If a :class:`~matplotlib.figure.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)   )r  r   r   Z
get_activeZget_fig_managerr   r   Zcanvasr   r	  Zget_size_inchesr.  r;  r/  r=   savefig)r]   r   r   ZmanagerZorig_canvasr   r   r   r   r   r@  b  s&    




zPdfPages.savefigc             C   s   | j S )zP
        Returns the current number of pages in the multipage pdf file.
        )r.  )r]   r   r   r   get_pagecount  s    zPdfPages.get_pagecount)N)r`   ra   rb   r   	__slots__r[   r;  r<  r>  r   r?  r@  rA  r   r   r   r   r'    s   $.
2r'  )Jatexitr   errnoZloggingr   rJ   r   rer   rL   r   r   r   r   Z
matplotlibrV   r   r   r   r   r   r   Zmatplotlib.backend_basesr   r   r	   r
   r   Z!matplotlib.backends.backend_mixedr   Zmatplotlib.cbookr   Zmatplotlib.pathr   Zmatplotlib.figurer   Zmatplotlib._pylab_helpersr   Z	getLoggerr`   ri   Z
deprecatedr   r&   r'   Zlatex_pt_to_inr   r   Zmpl_in_to_ptZ	NO_ESCAPEcompiler3   r6   r7   r0   r2   r<   r@   rF   rX   r   rY   rd   re   r   r   r  r	  r$  Zexportr%  r&  registerr'  r   r   r   r   <module>   sp   
	&   p ?
