3
$ßL]¥  ã               @   s8  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" ej#e$ƒZ%ej&dƒd	d
„ ƒZ'dd„ Z(dd„ Z)d8Z*de* Z+d9Z,de, Z-dZ.ej/e.d ƒZ0ej/e.d ƒZ1dd„ Z2ej/e.d ƒZ3dd„ Z4dd„ Z5dd„ Z6dd„ Z7dd „ Z8G d!d"„ d"e9ƒZ:ej&d#ƒG d$d%„ d%ƒƒZ;G d&d'„ d'ƒZ<G d(d)„ d)eƒZ=G d*d+„ d+eƒZ>G d,d-„ d-ƒZ?G d.d/„ d/eƒZ@G d0d1„ d1eƒZAejBG d2d3„ d3eƒƒZCd4d5„ ZDe jEeDƒ G d6d7„ d7ƒZFdS ):é    N)Ú_pngÚcbookÚfont_managerÚ__version__ÚrcParams)Ú_BackendÚFigureCanvasBaseÚFigureManagerBaseÚGraphicsContextBaseÚRendererBase)ÚMixedModeRenderer)Ú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   úG/tmp/pip-install-edjban26/matplotlib/matplotlib/backends/backend_pgf.pyÚget_texcommand   s    
r   c              C   s”   g } t d }|dkr| jdƒ |dkrŠt d rŠdddg}dd	d
g}xFt||ƒD ]8\}}tjtj|ƒƒ}| jd||j|jj	ƒ d f ƒ qNW dj
| ƒ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ÚfamilyÚcommandÚpathr   r   r   Úget_fontspec'   s    


r&   c               C   s   t d S )zGet LaTeX preamble from rc.zpgf.preamble)r   r   r   r   r   Úget_preamble<   s    r'   g      ð?gáz®GR@g      R@z(?<!\\)(?:\\\\)*z\$z([_^$%])c             C   s   d| j dƒ S )Nú\é   )Úgroup)Úmr   r   r   Ú<lambda>P   s    r,   z(\\mathdefault)c             C   s   | j dƒd t| j dƒƒ … S )Nr   r)   )r*   Úlen)r+   r   r   r   r,   R   s    c             C   s\   t jt| ƒ} tj| ƒ}x:t|ƒD ].\}}|d s>tjt|ƒ}nd| }|||< q W dj|ƒ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_texificationU   s    
r<   c             C   s   | j |ƒ | j dƒ d S )Nz%
)Úwrite)ÚfhÚliner   r   r   Úwritelnm   s    
r@   c                sä   g }dddddœ}| j ƒ d ‰ ˆ |kr6|j|ˆ  ƒ n6t‡ fdd„tjjD ƒƒrltd d	krl|jd
ˆ  ƒ n | jƒ }|jd||d f ƒ ddddœ}|j|| jƒ  ƒ dddddddg}| j	ƒ |krÐ|jdƒ |jdƒ dj
|ƒS )Nz	\rmfamilyz	\sffamilyz	\ttfamily)r   Zsansz
sans-serifr   r   c             3   s   | ]}|j ˆ kV  qd S )N)r   )Ú.0Ú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)Ú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_strt   s&    



rH   c                 sV   t jdƒrdd„ } | S ytjdƒ‰ W n tk
r8   Y nX ‡ fdd„}|S tdƒ‚dS )	z:Returns a function that converts a pdf file to a png file.Ú
pdftocairoc             S   s6   ddddd| | t jj|ƒd g}tj|tjd� d S )NrI   z-singlefilez-pngz-rz%dr   )Ústderr)Úosr%   ÚsplitextÚ
subprocessÚcheck_outputÚSTDOUT)ÚpdffileÚpngfileÚdpiÚcmdr   r   r   Úcairo_convert•   s    z0make_pdf_to_png_converter.<locals>.cairo_convertZ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%d)rJ   )Ú
executablerM   rN   rO   )rP   rQ   rR   rS   )Úgs_infor   r   Ú
gs_convertŸ   s    
z-make_pdf_to_png_converter.<locals>.gs_convertz&No suitable pdf to png renderer found.N)ÚshutilÚwhichÚmplZ_get_executable_infoÚFileNotFoundErrorÚRuntimeError)rT   rW   r   )rV   r   Úmake_pdf_to_png_converter’   s    
r]   c                   s   e Zd Zd‡ fdd„	Z‡  ZS )Ú
LatexErrorr/   c                s   t ƒ j|ƒ || _d S )N)ÚsuperÚ__init__Úlatex_output)ÚselfÚmessagera   )Ú	__class__r   r   r`   ¬   s    zLatexError.__init__)r/   )Ú__name__Ú
__module__Ú__qualname__r`   Ú__classcell__r   r   )rd   r   r^   «   s   r^   z3.1c               @   s   e Zd ZdZedd„ ƒZdS )ÚLatexManagerFactoryNc              C   sZ   t d } tjƒ }tj}|r<|j|kr<|j| kr<tjdƒ |S tjdƒ tƒ }|t_|S d S )Nzpgf.texsystemzreusing LatexManagerzcreating LatexManager)	r   ÚLatexManagerÚ_build_latex_headerri   Úprevious_instanceÚlatex_headerr    Ú_logÚdebug)r    rm   ÚprevZnew_instr   r   r   Úget_latex_managerµ   s    


z%LatexManagerFactory.get_latex_manager)re   rf   rg   rl   Ústaticmethodrq   r   r   r   r   ri   ±   s   ri   c               @   sŠ   e Zd ZdZejƒ Zedd„ ƒZe	dd„ ƒZ
e	ejdƒ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 )rj   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 custom preamble in the rc parameters.
    c              C   s2   t ƒ } tƒ }ddjtd ƒ| |dddg}dj|ƒS )Nz\documentclass{minimal}z% !TeX program = {}zpgf.texsystemz\begin{document}ztext $math \mu$z!\typeout{pgf_backend_query_start}r   )r'   r&   Úformatr   r   )Úlatex_preambler   rm   r   r   r   rk   Ï   s    z LatexManager._build_latex_headerc             C   s   | j | jƒ ƒS )z„
        Return the previous LatexManager if the header and tex system did not
        change, or a new instance otherwise.
        )Ú_get_cached_or_new_implrk   )Úclsr   r   r   Ú_get_cached_or_newã   s    zLatexManager._get_cached_or_newr)   c             C   s   | ƒ S )Nr   )rv   Úheaderr   r   r   ru   ë   s    z$LatexManager._get_cached_or_new_implc              C   s$   t tjƒ} x| D ]}|jƒ  qW d S )N)Úlistrj   Ú_unclean_instancesÚ_cleanup)Zunclean_instancesZlatex_managerr   r   r   Ú_cleanup_remaining_instancesð   s    

z)LatexManager._cleanup_remaining_instancesc             C   s&   | j j|ƒ | j jdƒ | j jƒ  d S )Nr   )Úlatex_stdin_utf8r=   Úflush)rb   r;   r   r   r   Ú_stdin_writelnö   s    zLatexManager._stdin_writelnc             C   sf   |j dƒ}tƒ }xJ| jjjdƒ}||7 }|t|ƒ d … |kr@P t|ƒstd|jdƒƒ‚qW |jdƒS )NÚutf8r)   zLaTeX process halted)ÚencodeÚ	bytearrayÚlatexÚstdoutÚreadr-   r^   Údecode)rb   r;   ÚexpÚbufÚbr   r   r   Ú_expectû   s    
zLatexManager._expectc             C   s
   | j dƒS )Nz
*)rŠ   )rb   r   r   r   Ú_expect_prompt  s    zLatexManager._expect_promptc             C   s<  t j| _t| _tjdd�| _tj	j
| ƒ td | _tjƒ | _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| }|j|jd	ƒƒ\}}|jd
krÚtd| ƒ‚tj| jdgtjtj| jd�}|| _tjdƒ| jjƒ| _| j| jƒ ƒ | jdƒ | j ƒ  i | _!d S )NZmpl_pgf_lm_)Úprefixzpgf.texsystemz
\makeatletter
\@@end
z-halt-on-error)Ústdinr„   Ú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:
%sr€   z*pgf_backend_query_start)"rK   r%   Ú_os_pathrX   Ú_shutilÚtempfileÚmkdtempÚtmpdirrj   rz   Úaddr   r    rk   rm   rM   ÚPopenÚPIPEr[   r\   ÚOSErrorÚcommunicater�   Ú
returncoder^   rƒ   ÚcodecsÚ	getwriterr�   r}   r   rŠ   r‹   Ú	str_cache)rb   Z	latex_endrƒ   Z
test_inputr„   rJ   r   r   r   r`   
  s@    





zLatexManager.__init__c             C   s–   | j j| jƒsd S y$| jjƒ  | jjƒ  | jjjƒ  W n tk
rJ   Y nX y| j	j
| jƒ tjj| ƒ W n& tk
r�   tjjd| j ƒ Y nX d S )Nz error deleting tmp directory %s
)r�   Úisdirr“   rƒ   r˜   r}   Úcloser„   Ú	Exceptionr�   Úrmtreerj   rz   ÚdiscardÚsysrJ   r=   )rb   r   r   r   r{   7  s    

zLatexManager._cleanupc             C   s   t jdƒ | jƒ  d S )Nzdeleting LatexManager)rn   ro   r{   )rb   r   r   r   Ú__del__F  s    
zLatexManager.__del__c          *   C   sZ  t |ƒ}d||f }|| jkr(| j| S | j|ƒ y| jƒ  W n4 tk
rr } ztdj||jƒƒ‚W Y dd}~X nX | jdƒ y| jƒ }W n4 tk
r¾ } ztdj||jƒƒ‚W Y dd}~X nX y|jƒ d j	dƒ\}}}	W n& t
k
�r   tdj||ƒƒ‚Y nX 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   ú,r.   éþÿÿÿr¥   r¥   )rH   rœ   r   r‹   r^   Ú
ValueErrorrs   ra   Ú
splitlinesr4   rŸ   Úfloat)rb   r8   rF   Ú	prop_cmdsZtextboxÚeZanswerÚwidthÚheightÚoffsetÚwÚhÚor   r   r   Úget_width_height_descentJ  s0    



4z%LatexManager.get_width_height_descentN)re   rf   rg   Ú__doc__ÚweakrefÚWeakSetrz   rr   rk   Úclassmethodrw   Ú	functoolsÚ	lru_cacheru   r|   r   rŠ   r‹   r`   r{   r£   r±   r   r   r   r   rj   Ç   s   -rj   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| ƒ |j| _|| _|| _d| _tjƒ | _|r`dd„ }xZt	j
D ]}|jdƒrB|| j
|< qBW n6t|dƒ s|tjj|jƒ r–tjdtƒ 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 optionc              _   s   d S )Nr   )r¹   rº   r   r   r   r,   ›  s    Ú
draw_imageN)r   r`   rR   r>   ÚfigureÚimage_counterrj   rw   ÚlatexManagerr¸   Ú__dict__Ú
startswithÚhasattrrK   r%   Úexistsr   r   Z_warn_externalÚUserWarning)rb   r¼   r>   ÚdummyZnopr+   r   r   r   r`   y  s    


zRendererPgf.__init__Nc             C   s,  t | jdƒ d| j }| j|ƒ | j||ƒ |j|ƒjƒ \}}	|d | |d | |	d | |	d | f}
t | jd|
 ƒ | jd ||ƒ | j|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ƒ q¾W 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>   rR   Ú_print_pgf_clipÚ_print_pgf_path_stylesÚget_extentsÚ
get_pointsÚ_print_pgf_pathÚ_pgf_path_drawÚget_linewidthÚiter_segments)rb   ÚgcZmarker_pathZmarker_transr%   ZtransÚrgbFaceÚfÚblÚtrÚcoordsZpointÚcodeÚxÚyr   r   r   Údraw_markers�  s(    

,zRendererPgf.draw_markersc             C   sþ  t | jdƒ | j|ƒ | j||ƒ | j||||ƒ | j|jƒ dk|d k	d� t | jdƒ |jƒ �rút | jdƒ | j||ƒ | j|ƒ | j||||ƒ t | jdƒ t | jdƒ t | jdƒ t | jdƒ t | jdƒ tj	j
ƒ j| jƒ}| jd |jƒ |ƒ | jdd	� t | jdƒ t | jd
ƒ d| j }|j|ƒjƒ \\}}\}	}
|| ||	  }}	|| ||
  }}
tj|	| ƒtj|
| ƒ }}t | jd||f ƒ xZt|ƒD ]N}x*t|ƒD ]}t | jdƒ t | jdƒ �qªW t | jd| ƒ t | jdƒ �qœW 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_hatchrZ   Z
transformsZAffine2DÚscalerR   Zget_hatch_pathrÊ   rË   ÚmathÚceilÚrange)rb   rÐ   r%   Ú	transformrÑ   rÚ   rÒ   ZxminZyminZxmaxZymaxZrepxZrepyZiyÚixr   r   r   Ú	draw_path¿  sL    



zRendererPgf.draw_pathc             C   s    d| j  }|jƒ }|rn|jƒ \}}|| \}}|d | |d | || || f}t| jd| ƒ t| jdƒ |jƒ \}	}
|	d k	rœ| j||	|
ƒ t| jdƒ d S )Ng      ð?r   r)   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}z\pgfusepath{clip})rR   Úget_clip_rectanglerË   r@   r>   Zget_clip_pathrÌ   )rb   rÐ   rÒ   ÚbboxÚp1Úp2r®   r¯   rÕ   ÚclippathZclippath_transr   r   r   rÈ   ô  s    
$zRendererPgf._print_pgf_clipc             C   s€  ddddœ}t | j||jƒ  ƒ ddddœ}t | j||jƒ  ƒ |d k	}|jƒ r^|jƒ  }}n(|jƒ d	 }|r‚t|ƒd	kr‚|d	 nd
}|r²t | jdt|d d	… ƒ ƒ t | jdƒ |rÎ|d
krÎt | jd| ƒ |j	ƒ t
 t }|jƒ }	t | jd| ƒ t | jd|	d d	…  ƒ t | jdƒ |d
k�r4t | jd| ƒ |jƒ \}
}|d k�rXt | jdƒ n$t | jddj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   rC   8  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   )rb   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|jƒ nd }|rP|d krP|jƒ \}}|d |d |d |d f}	nd }	�x<|j||	d�D �](\}
}|tjkr¤t|
ƒ\}}t| jd|| || f ƒ qf|tj	kr¼t| jdƒ qf|tj
krðt|
ƒ\}}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}})rR   rá   rË   rÏ   r   ZMOVETOrê   r@   r>   Z	CLOSEPOLYZLINETOZCURVE3ZCURVE4)rb   rÐ   r%   rÞ   rÑ   rÒ   râ   rã   rä   rí   ÚpointsrÖ   r×   rØ   ZcxÚcyZpxÚpyrÕ   Zc1xZc1yZc2xZc2yr   r   r   rÌ   ;  s>    





(zRendererPgf._print_pgf_pathTc             C   s:   g }|r|j dƒ |r |j dƒ t| jddj|ƒ ƒ d S )NrÅ   rÆ   z\pgfusepath{%s}r¤   )r   r@   r>   r   )rb   rÅ   rÆ   Úactionsr   r   r   rÍ   c  s    

zRendererPgf._pgf_path_drawc             C   s   dS )NTr   )rb   r   r   r   Úoption_scale_imagek  s    zRendererPgf.option_scale_imagec             C   s
   t d  S )Nzimage.composite_image)r   )rb   r   r   r   Úoption_image_nocompositeo  s    z$RendererPgf.option_image_nocompositec          
   C   sz  |j d d… \}}|dks"|dkr&d S tjj| jjƒ}tjjtjj| jjƒƒd }	d|	| jf }
|  jd7  _t	j
|d d d… tjj||
ƒƒ t| jdƒ | j|ƒ d| j }|d kræt| jd|| || f ƒ || ||  }}n\|jƒ jƒ \}}}}}}t| jd|| || || || || | || | f ƒ d }}t|d kƒjƒ }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}éÿÿÿÿ)ÚshaperK   r%   Údirnamer>   r   rL   Úbasenamer½   r   Z	write_pngr   r@   rÈ   rR   ÚfrozenZ	to_valuesÚstrÚlower)rb   rÐ   r×   rØ   ZimrÞ   r¯   r®   r%   ÚfnameZ	fname_imgrÒ   Ztr1Ztr2Ztr3Ztr4Ztr5Ztr6Zinterpr   r   r   r»   s  s4     

zRendererPgf.draw_imageúTeX!c	       	   	   C   s   | j ||||||||ƒ d S )N)Ú	draw_text)	rb   rÐ   r×   rØ   r;   rF   ÚangleÚismathÚmtextr   r   r   Údraw_tex—  s    zRendererPgf.draw_texc	             C   sÊ  t |ƒ}t|ƒ}	d|	|f }t| jdƒ |jƒ }
|
dkrXt| jd|
 ƒ t| jd|
 ƒ t|jƒ ƒd d… }t| jd| ƒ t| jdƒ t| jd	ƒ d
| }d| jj }g }|oÎ|dksÄ|j	ƒ dkoÎ|j
ƒ dk�rP|jƒ }|jƒ j|ƒ\}}|jd||  ƒ |jd||  ƒ ddddœ}dddddœ}|j||jƒ  ƒ |j||j
ƒ  ƒ n8|jd||  ƒ |jd||  ƒ |jdƒ |jdƒ |dk�r |jd| ƒ t| jddj|ƒ|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   Ú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<   rH   r@   r>   rè   rê   ré   r¼   rR   Zget_rotation_modeZget_verticalalignmentZget_unitless_positionZget_transformZtransform_pointr   Zget_horizontalalignmentr   )rb   rÐ   r×   rØ   r;   rF   rþ   rÿ   r   r©   ÚalphaZrgbrÒ   Z	text_argsÚposZhalignZvalignr   r   r   rý   ›  sH    



zRendererPgf.draw_textc             C   s<   t |ƒ}| jj||ƒ\}}}t| j }|| || || fS )N)r<   r¾   r±   rë   rR   )rb   r;   rF   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   )rb   r   r   r   ÚflipyÜ  s    zRendererPgf.flipyc             C   s   | j jƒ | j jƒ fS )N)r¼   Úget_figwidthÚget_figheight)rb   r   r   r   Úget_canvas_width_heightà  s    z#RendererPgf.get_canvas_width_heightc             C   s   |t  | j S )N)rë   rR   )rb   rî   r   r   r   Úpoints_to_pixelsä  s    zRendererPgf.points_to_pixelsc             C   s   t ƒ S )N)ÚGraphicsContextPgf)rb   r   r   r   Únew_gcè  s    zRendererPgf.new_gc)F)N)N)N)TF)N)rü   N)FN)re   rf   rg   r`   rÙ   rà   rÈ   rÉ   rÌ   rÍ   rò   ró   r»   r  rý   r  r  r  r  r  r   r   r   r   r¸   w  s"   
%
!
53
(

$

3r¸   c               @   s   e Zd ZdS )r  N)re   rf   rg   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j| ƒ d S )N)r  Úremaining_tmpdirsr”   )r“   r   r   r   r”   ö  s    zTmpDirCleaner.addc                 s4   x.t jD ]$} dj| ƒ‰ tj| ‡ fdd„d� qW d S )Nzerror deleting tmp directory {}c                 s
   t jˆ ƒS )N)rn   Úerror)r¹   )Úerror_messager   r   r,      s    z9TmpDirCleaner.cleanup_remaining_tmpdirs.<locals>.<lambda>)Úonerror)r  r  rs   rX   r    )r“   r   )r  r   Úcleanup_remaining_tmpdirsú  s
    
z'TmpDirCleaner.cleanup_remaining_tmpdirsN)re   rf   rg   Úsetr  rr   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   )rb   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j|ƒ d S d}dg}x tƒ jƒ D ]}	|jd|	 ƒ q:W x tƒ jƒ D ]}	|jd|	 ƒ q\W |jdƒ dj|ƒ}| jjƒ | jj	ƒ  }
}| jj
ƒ }|j|ƒ |j|ƒ |jdƒ t|dƒ t|d	ƒ t|d
ƒ t|d|
|f ƒ t|dƒ t| j|
||t | j|ƒ|d�}| j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   )rb   r>   r  r   r¹   rº   ZrendererZheader_textZheader_info_preambler?   r®   r¯   rR   r   r   r   Ú_print_pgf_to_fh  s>    












z FigureCanvasPgf._print_pgf_to_fhc          
   O   sj   |j ddƒr | jd|ž|Ž dS tj|ddd��0}tj|ƒsJtjdƒ|ƒ}| j|f|ž|Ž W dQ R X 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)Úencoding)N)Úgetr!  r   Úopen_file_cmZfile_requires_unicoderš   r›   )rb   Úfname_or_fhr¹   rº   Úfiler   r   r   Ú	print_pgfE  s    
zFigureCanvasPgf.print_pgfc             O   s  | j jƒ | j jƒ  }}z¾tjdd�}tjj|dƒ}tjj|dƒ}tjj|dƒ}	| j|f|ž|Ž t	ƒ }
t
ƒ }d|||
|f }tj|ƒj|dd� td	 }tj|d
ddgt|d� t|	dƒ�}tj||ƒ W d Q R X W d ytj|ƒ W n   tj|ƒ 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)rŽ   Úrb)r¼   r  r  r‘   r’   rK   r%   r   r'  r'   r&   r   r   Z
write_textr   r   Ú_check_and_log_subprocessrn   ÚopenrX   Úcopyfileobjr    r  r”   )rb   r>   r¹   rº   r®   r¯   r“   Z	fname_pgfZ	fname_texÚ	fname_pdfrt   r   Z	latexcoder    Úfh_srcr   r   r   Ú_print_pdf_to_fhR  s*    z FigureCanvasPgf._print_pdf_to_fhc          
   O   sN   |j ddƒr | jd|ž|Ž dS tj|dƒ�}| j|f|ž|Ž W dQ R X dS )z3Use LaTeX to compile a Pgf generated figure to PDF.r  FNÚwb)N)r#  r!  r   r$  r/  )rb   r%  r¹   rº   r&  r   r   r   Ú	print_pdf|  s
    zFigureCanvasPgf.print_pdfc       	      O   s¦   t ƒ }zrtjdd�}tjj|dƒ}tjj|dƒ}| j|f|ž|Ž |||| jjd� t	|dƒ�}t
j||ƒ W d Q R X W d yt
j|ƒ W n   tj|ƒ Y nX X d S )Nr(  )rŒ   z
figure.pdfz
figure.png)rR   r)  )r]   r‘   r’   rK   r%   r   r1  r¼   rR   r+  rX   r,  r    r  r”   )	rb   r>   r¹   rº   Ú	converterr“   r-  Z	fname_pngr.  r   r   r   Ú_print_png_to_fh„  s    z FigureCanvasPgf._print_png_to_fhc          
   O   sN   |j ddƒr | jd|ž|Ž dS tj|dƒ�}| j|f|ž|Ž W dQ R X dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.r  FNr0  )N)r#  r!  r   r$  r3  )rb   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¼   )rb   r   r   r   Úget_renderer   s    zFigureCanvasPgf.get_renderer)re   rf   rg   Z	filetypesr  r!  r'  r/  r1  r3  r4  r5  r   r   r   r   r    s   9*r  c               @   s   e Zd ZdS )ÚFigureManagerPgfN)re   rf   rg   r   r   r   r   r6  ¤  s   r6  c               @   s   e Zd ZeZeZdS )Ú_BackendPgfN)re   rf   rg   r  ZFigureCanvasr6  ZFigureManagerr   r   r   r   r7  ¨  s   r7  c               C   s   t jƒ  tjƒ  d S )N)rj   r|   r  r  r   r   r   r   Ú_cleanup_all®  s    r8  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;  rB  c            C   sr   || _ d| _|| _|pi | _tjdd�| _d| _tj	j
| j| jd ƒ| _tj	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.pdfr0  N)r:  r@  r;  rB  r‘   r’   r<  r=  rK   r%   r   r>  r?  r+  rA  )rb   Úfilenamer;  rB  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jƒ D ƒ}|j|ƒ d}xF|jƒ D ]:\}}||krntdj|ƒƒ‚|d| d t|ƒ d 7 }qPW tƒ }	tƒ }
dj|||	|
|d�}| j	j
|jdƒƒ d S )NÚtitleÚauthorÚsubjectÚkeywordsÚcreatorÚproducerZtrappedz%matplotlib %s, https://matplotlib.orgzmatplotlib pgf backend %s)rH  rI  c             S   s   i | ]\}}||j ƒ “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¬   ÚpreambleZfontspecrB  zutf-8)r   rB  ÚitemsÚupdater¦   rs   rù   r'   r&   rA  r=   r�   )rb   Zwidth_inchesZheight_inchesZsupported_keysZinfoDictrB  Zhyperref_optionsrJ  rK  rt   r   rm   r   r   r   Ú_write_headerö  s*    

 zPdfPages._write_headerc             C   s   | S )Nr   )rb   r   r   r   Ú	__enter__$  s    zPdfPages.__enter__c             C   s   | j ƒ  d S )N)rž   )rb   Úexc_typeÚexc_valÚexc_tbr   r   r   Ú__exit__'  s    zPdfPages.__exit__c             C   sv   | j jdƒ | j jƒ  | jdkr\z| jƒ  W dytj| jƒ W n   tj	| jƒ Y nX X n| j
rrt| 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   Nr0  )rA  r=   rž   r@  Ú
_run_latexrX   r    r<  r  r”   r;  r+  r:  )rb   r   r   r   rž   *  s    

zPdfPages.closec             C   s@   t d }tj|ddtjj| jƒgt| jd� t	j
| j| jƒ d S )Nzpgf.texsystemz-interaction=nonstopmodez-halt-on-error)rŽ   )r   r   r*  rK   r%   r÷   r>  rn   r<  rX   Úcopyfiler?  r:  )rb   r    r   r   r   rV  =  s    zPdfPages._run_latexc             K   sÄ   t |tƒsD|dkrtjƒ }n
tj|ƒ}|dkr<tdj|ƒƒ‚|jj}zr|j}t	|ƒ|_|j
ƒ \}}| jdkrz| j||ƒ n| j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%%
rs   r  r)   )Ú
isinstancer   r   Z
get_activeZget_fig_managerr¦   rs   Zcanvasr¼   r  Zget_size_inchesr@  rP  rA  r=   Úsavefig)rb   r¼   rº   ÚmanagerZorig_canvasr«   r¬   r   r   r   rY  F  s&    




zPdfPages.savefigc             C   s   | j S )zP
        Returns the current number of pages in the multipage pdf file.
        )r@  )rb   r   r   r   Úget_pagecountx  s    zPdfPages.get_pagecount)	r:  r;  r<  r=  r>  r?  r@  rA  rB  )N)re   rf   rg   r²   Ú	__slots__r`   rP  rQ  rU  rž   rV  rY  r[  r   r   r   r   r9  ¶  s$           $.	
2r9  gRh�¸’VŒ?gÇqÇqŒ?)GÚatexitrš   r¶   ÚloggingrÛ   rK   r   ÚrerX   rM   r¢   r‘   r³   Z
matplotlibrZ   r   r   r   r   r   r   Zmatplotlib.backend_basesr   r   r	   r
   r   Z!matplotlib.backends.backend_mixedr   Zmatplotlib.pathr   Zmatplotlib.figurer   Zmatplotlib._pylab_helpersr   Ú	getLoggerre   rn   Ú
deprecatedr   r&   r'   Zlatex_pt_to_inrì   rë   Zmpl_in_to_ptZ	NO_ESCAPEÚcompiler3   r6   r7   r0   r2   r<   r@   rH   r]   rŸ   r^   ri   rj   r¸   r  r  r  r6  Úexportr7  r8  Úregisterr9  r   r   r   r   Ú<module>   sl   
	 1  x "
