o
    h                     @   s  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mZ d dlZd dlmZ d dlZd dlmZmZ d dlmZ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$ d dl%m&Z& e'e(Z)dZ*dd Z+dZ,de, Z-dZ.de. Z/dd Z0dd Z1dd Z2dd Z3dd Z4G dd de5Z6G dd  d Z7e8d!d"d# Z9G d$d% d%eZ:G d&d' d'eZ;eZ<ej=G d(d) d)eZ>G d*d+ d+Z?dS ),    N)BytesIO)TemporaryDirectory)Image)cbookfont_manager)_BackendFigureCanvasBaseFigureManagerBaseRendererBase)MixedModeRenderer)_create_pdf_info_dict_datetime_to_pdf)Path)Figure)FontProperties)Gcfz\documentclass{article}c                  C   s   t tjd d } ddddd|  dd	| d
|  f ddtjd g	tjd r>ddgdd tg ddd dD D  dg ng tjjdddS )z=Prepare a LaTeX preamble based on the rcParams configuration.z	font.size)size
z\def\mathdefault#1{#1}z4\everymath=\expandafter{\the\everymath\displaystyle}z\IfFileExists{scrextend.sty}{z'  \usepackage[fontsize=%fpt]{scrextend}z}{z:  \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}333333?z  \normalsize}zpgf.preamblepgf.rcfontsz1\ifdefined\pdftexversion\else  % non-pdftex case.z  \usepackage{fontspec}c                 S   s&   g | ]\}}d ||j |j f qS )z   \%s{%s}[Path=\detokenize{%s/}])nameparentas_posix).0commandpath r   s/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/matplotlib/backends/backend_pgf.py
<listcomp>B   s    z!_get_preamble.<locals>.<listcomp>)setmainfontsetsansfontsetmonofontc                 S   s   g | ]
}t t|qS r   )pathlibr   fmfindfont)r   familyr   r   r   r   G   s    )serifzsans\-serif	monospacez\fi
underscorestrings)option)r   mplrcParamsget_size_in_pointsjoinzip
texmanager_usepackage_if_not_loaded)font_size_ptr   r   r   _get_preamble'   sL   
 r4   gRhV?      ?gqq?c                 C   s   |  ddS )zh
    Do some necessary and/or useful substitutions for texts to be included in
    LaTeX documents.
    u   −z\ensuremath{-})replace)textr   r   r   _tex_escapeX   s   r8   c                 C   s   |  | |  d d S )Nz%
)write)fhliner   r   r   _writeln`   s   
r<   c                    s  g }ddddd}|  d   |v r||   n&tjd s&|d nt fdd	tjjD r;|d
   nt	d  |
 }|d||d f  dddd}|||   g d}| |v rn|d |d dd| d d t|  d S )z
    Generate a TeX string that renders string *s* with font properties *prop*,
    also applying any required escapes to *s*.
    z	\rmfamilyz	\sffamilyz	\ttfamily)r'   sansz
sans-serifr(   r   r   z\fontfamily{\familydefault}c                 3   s    | ]}|j  kV  qd S N)r   )r   fontr&   r   r   	<genexpr>u   s    z*_escape_and_apply_props.<locals>.<genexpr>z9\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fizIgnoring unknown font: %sz\fontsize{%f}{%f}r    z\itshapez\slshape)normalitalicoblique)semibolddemibolddemiboldheavyz
extra boldblackz	\bfseriesz\selectfont{z1\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}z\catcode`\%=\active\def%{\%}r   )
get_familyappendr,   r-   anyr$   fontManagerttflist_logwarningr.   	get_style
get_weightr/   r8   )spropcommandsfamiliesr   styles
boldstylesr   r@   r   _escape_and_apply_propsg   sD   


r\   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={r   )
isinstancedatetimer   r   decodestr)keyvaluer   r   r   _metadata_to_str   s   
re   c                      s`   z
t d W dd S  t jy   Y nw 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   s0   t jdddddd| | tj|d gt jdS )	Nrf   z-singlefilez-transpz-pngz-rz%dr   stderr)
subprocesscheck_outputosr   splitextSTDOUTpdffilepngfiledpir   r   r   <lambda>   s    z+make_pdf_to_png_converter.<locals>.<lambda>gsc                    s6   t j jddddddddd	d
d| d| | gt jdS )Nz-dQUIETz-dSAFERz-dBATCHz	-dNOPAUSEz
-dNOPROMPTz-dUseCIEColorz-dTextAlphaBits=4z-dGraphicsAlphaBits=4z-dDOINTERPOLATEz-sDEVICE=pngalphaz-sOutputFile=%sz-r%drg   )ri   rj   
executablerm   rn   gs_infor   r   rr      s    
z&No suitable pdf to png renderer found.)r,   _get_executable_infoExecutableNotFoundErrorRuntimeErrorr   r   ru   r   make_pdf_to_png_converter   s   
rz   c                       s&   e Zd Zd fdd	Zdd Z  ZS )
LatexErrorrB   c                    s   t  | || _d S r>   )super__init__latex_output)selfmessager~   	__class__r   r   r}      s   
zLatexError.__init__c                 C   s    | j \}| jr|d| j 7 }|S Nr   )argsr~   r   rV   r   r   r   __str__   s   zLatexError.__str__)rB   )__name__
__module____qualname__r}   r   __classcell__r   r   r   r   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ddZ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   s(   t dtjd  dt ddg} d| S )Nz% !TeX program = pgf.texsystemz\usepackage{graphicx}\begin{document}z!\typeout{pgf_backend_query_start}r   )_DOCUMENTCLASSr,   r-   r4   r/   )latex_headerr   r   r   _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   )clsr   r   r   _get_cached_or_new   s   zLatexManager._get_cached_or_new   c                 C   s   |  S r>   r   )r   headerr   r   r   r      s   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stdinr9   flushr   r   r   r   _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 haltedrB   )	listr   stdoutreadrN   lenkillr{   r/   )r   rV   charscr   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   sx   t  | _| jj| _t| | jj| _| jdd | j	
d\}}| j	jdkr0td|   |d | _	t| j| _d S )NFexpect_replyz
\makeatletter\@@end
r   zaLaTeX errored (probably missing font or error in preamble) while processing the following input:
)r   _tmpdirr   tmpdirweakreffinalizecleanup_finalize_tmpdirr   r   communicate
returncoder{   r   	functools	lru_cache_get_box_metrics)r   r   rh   r   r   r   r}     s   
zLatexManager.__init__Tr   c             
   C   s   zt jtjd dgt jt jd| jd| _W n- ty, } zttjd d|d }~w t	yB } ztdtjd |d }~ww dd }t
| || j| _| |   |rd| d	 |   d S d S )
Nr   -halt-on-errorutf-8)r   r   encodingcwdz] not found; install it or change rcParams['pgf.texsystem'] to an available TeX implementationzError starting c                 S   s4   |    z|   W d S  ty   |   Y d S w r>   )r   r   ry   wait)r   r   r   r   finalize_latex(  s   z9LatexManager._setup_latex_process.<locals>.finalize_latexz*pgf_backend_query_start)ri   Popenr,   r-   PIPEr   r   FileNotFoundErrorry   OSErrorr   r   _finalize_latexr   r   r   r   )r   r   errr   r   r   r   r     s<   
z!LatexManager._setup_latex_processc                 C   s   |  t||S )z
        Get the width, total height, and descent (in TeX points) for a text
        typeset by the current LaTeX environment.
        )r   r\   )r   r7   rW   r   r   r   get_width_height_descent7  s   z%LatexManager.get_width_height_descentc           
   
   C   s   |  d|  z|  }W n ty# } z
td||j|d}~ww z| d d\}}}W n tyG } z	td|||d}~ww t	|dd t	|dd t	|dd }}}	|||	 |	fS )z
        Get the width, total height and descent (in TeX points) for a TeX
        command's output in the current LaTeX environment.
        zW{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}\typeout{\the\wd0,\the\ht0,\the\dp0}}z#Error measuring {}
LaTeX Output:
{}N,)
r   r   r{   
ValueErrorformatr~   
splitlinessplit	Exceptionfloat)
r   texanswerr   widthheightoffsetwhor   r   r   r   >  s6   
4zLatexManager._get_box_metricsN)r   r   r   __doc__staticmethodr   classmethodr   r   r   r   r   r   r   r}   r   r   r   r   r   r   r   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)manr   r   r   _get_image_inclusion_command^  s   
r   c                       s   e Zd Z 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dZd'ddZdd Zdd  Zd!d" Zd#d$ Z  ZS )(RendererPgfc                    s(   t    |j| _|| _|| _d| _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   N)r|   r}   rq   r:   figureimage_counter)r   r   r:   r   r   r   r}   p  s
   

zRendererPgf.__init__Nc                 C   sD  t | jd d| j }| | | || || \}}	|d | |d | |	d | |	d | f}
t | jd|
  | d || | j|	 dk|d ud t | jd d	| j }| | ||f}|j
|d
|dD ]-\}}|d | |d | }}t | jd t | jd||f  t | jd t | jd qlt | jd d S )N\begin{pgfscope}r5   r   r   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{        strokefillr   B^!Vl@F)simplifyclip"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}\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   gcmarker_pathmarker_transr   transrgbFacefbltrcoordsmaxcoordr   pointcodexyr   r   r   draw_markers  s6   

,
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   r   r5   r   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   	get_hatchr,   
transformsAffine2Dscalerq   get_hatch_pathr   r   mathceilrange)r   r   r   	transformr   r   r   xminyminxmaxymaxrepxrepyiyixr   r   r   	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   )rq   get_clip_rectangler   r<   r:   get_clip_pathr   )r   r   r   bboxp1p2r   r   r   clippath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 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}rB   c                 s   s    | ]}d | V  qdS )z{%fpt}Nr   )r   dashr   r   r   rA   "  s    z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>)r<   r:   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_listr   r   r   r     sZ   
z"RendererPgf._print_pgf_path_stylesc                 C   sh  d| j  }|r| nd }d| j  }|r;|d u r;| \}}	t|d | t|d | t|	d |t|	d |f}
n| | ||f}
|j||
dD ]\}}|tjkrht|\}}t	| j
d|| || f  qJ|tjkrtt	| j
d qJ|tjkrt|\}}t	| j
d|| || f  qJ|tjkrt|\}}}}|| || || || f}t	| j
d	|  qJ|tjkrt|\}}}}}}|| || || || || || f}t	| j
d
|  qJ|r| nd }|d ur0|\}}}|d ur2|d9 }|d9 }t	| j
d t	| j
d t	| j
d|| dd|| dd t	| j
dt| d t	| j
d d S d S d S )Nr5   r   r   r   )r   z&\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}}g      ?   z\usepgfmodule{decorations}z(\usepgflibrary{decorations.pathmorphing}z/\pgfkeys{/pgf/decoration/.cd, segment length = r   zin, amplitude = zin}z\pgfmathsetseed{r   z%\pgfdecoratecurrentpath{random steps})rq   r  r   maxminr   r   MOVETOr#  r<   r:   	CLOSEPOLYLINETOCURVE3CURVE4get_sketch_paramsint)r   r   r   r  r   r   r  r   r  r  r   pointsr   r   r   cxcypxpyr   c1xc1yc2xc2ysketch_paramsr   length
randomnessr   r   r   r   %  sx   






(



	zRendererPgf._print_pgf_pathTFc                 C   s:   g }|r	| d |r| d t| jdd|  d S )Nr   r   z\pgfusepath{%s}r   )rN   r<   r:   r/   )r   r   r   actionsr   r   r   r   g  s   

zRendererPgf._pgf_path_drawc                 C      dS )NTr   r   r   r   r   option_scale_imageo     zRendererPgf.option_scale_imagec                 C   s   t jd  S )Nzimage.composite_image)r,   r-   r   r   r   r   option_image_nocomposites  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 )Nr0  r   r   rB   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   )shaperk   r   existsgetattrr:   r   r#   r   r   stemr   r   	fromarraysaver   r<   r   rq   frozen	to_valuesrb   lowerr   )r   r   r   r   imr  r   r   r   	fname_imgr   tr1tr2tr3tr4tr5tr6interpr   r   r   
draw_imagew  sJ    

zRendererPgf.draw_image)mtextc             
   C   s   | j ||||||d|d d S )NTeX)ismathr_  )	draw_text)r   r   r   r   rV   rW   angler_  r   r   r   draw_tex  s   zRendererPgf.draw_texc	                 C   s  t ||}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 )Nr   r5   r  r  r  z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   anchorcenter_baselineleftrightrB   )rg  rh  centertopbottombase)rj  rk  baselineri  zx=r   inzy=zin, y=zin, left, basez	rotate=%fz\pgftext[%s]{%s}r   r   )r\   r<   r:   r   r!  r#  r"  r   rq   get_rotation_modeget_verticalalignmentget_unitless_positionget_transformr  extendget_horizontalalignmentrN   r/   )r   r   r   r   rV   rW   rc  ra  r_  alphargbrq   	text_argsposhalignvalignr   r   r   rb    sF   



$zRendererPgf.draw_textc                 C   s6   t  ||\}}}t| j }|| || || fS r>   )r   r   r   r$  rq   )r   rV   rW   ra  r   r   dr   r   r   r   get_text_width_height_descent  s
   
z)RendererPgf.get_text_width_height_descentc                 C   rG  )NFr   r   r   r   r   flipy  rI  zRendererPgf.flipyc                 C   s    | j  | j | j  | j fS r>   )r   get_figwidthrq   get_figheightr   r   r   r   get_canvas_width_height  s   z#RendererPgf.get_canvas_width_heightc                 C   s   |t  | j S r>   )r$  rq   )r   r:  r   r   r   points_to_pixels  s   zRendererPgf.points_to_pixelsr>   )TF)FN)r   r   r   r}   r   r  r   r   r   r   rH  rJ  r^  rd  rb  r|  r}  r  r  r   r   r   r   r   r   n  s$    

&5
3
B
)
0r   c                       sd   e Zd ZddddZdd Z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   rG  )Nr  r   r   r   r   r   get_default_filetype     z$FigureCanvasPgf.get_default_filetypeNbbox_inches_restorec          
      C   s   d}dg}t   D ]	}|d|  q
|d d|}| j | 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}
%%
%% Also ensure that all the required font packages are loaded; for instance,
%% the lmodern package is sometimes necessary when using math font.
%%   \usepackage{lmodern}
%%
%% 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   rN   r/   r   r~  r  rq   r9   r<   r   r   draw)
r   r:   r  header_textheader_info_preambler;   r   r   rq   rendererr   r   r   _print_pgf_to_fh  s8   











z FigureCanvasPgf._print_pgf_to_fhc                 K   s`   t j|ddd}t |std|}| j|f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_fhkwargsfiler   r   r   	print_pgf-  s
   
"zFigureCanvasPgf.print_pgfmetadatac                K   sP  | j  \}}td|pi }ddd | D }t }t|}	| j|	d fi | |	d j	dt
d| d	||f d
t ddddg	dd tjd }
tj|
dddgt|d |	d d$}t|d}t|| W d   n1 szw   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 r>   re   r   kvr   r   r   rA   <      
z,FigureCanvasPgf.print_pdf.<locals>.<genexpr>z
figure.pgfz
figure.texr   #\usepackage[pdfinfo={%s}]{hyperref}8\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}\usepackage{pgf}r   z
\centeringz\input{figure.pgf}z\end{document}r   r  r   -interaction=nonstopmoder   r   
figure.pdfrbwbN)r   get_size_inchesr   r/   itemsr   r#   r   r  
write_textr   r4   r,   r-   r   _check_and_log_subprocessrR   openr  shutilcopyfileobj)r   r  r  r  r   r   	info_dictpdfinfor   tmppath
texcommandorigdestr   r   r   	print_pdf7  sT   



 "zFigureCanvasPgf.print_pdfc           
   
   K   s   t  }t a}t|}|d }|d }| j|fi | |||| jjd |d$}t	|d}	t
||	 W d   n1 sCw   Y  W d   n1 sRw   Y  W d   dS W d   dS 1 sjw   Y  dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.r  z
figure.png)rq   r  r  N)rz   r   r#   r   r  r   rq   r  r   r  r  r  )
r   r  r  	converterr   r  pdf_pathpng_pathr  r  r   r   r   	print_pngX  s$   

 "zFigureCanvasPgf.print_pngc                 C   s   t | jd S r>   )r   r   r   r   r   r   get_renderere     zFigureCanvasPgf.get_rendererc                    s   | j   t  S r>   )r   draw_without_renderingr|   r  r   r   r   r   r  h  s   

zFigureCanvasPgf.draw)r   r   r   	filetypesr  r  r  r  r  r  r  r   r   r   r   r   r    s    8
!r  c                   @   s   e Zd ZeZdS )_BackendPgfN)r   r   r   r  FigureCanvasr   r   r   r   r  p  s    r  c                   @   sX   e Zd ZdZ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()
    Nr  c                C   s4   || _ d| _|p	i  | _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.

        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   r  N)_output_name
_n_figurescopy	_metadatar   
_info_dictr   _file)r   filenamer  r   r   r   r}     s
   zPdfPages.__init__c              	   C   sV   d dd | j D }d td| d||f dt dd	g}| j|d
 d S )Nr   c                 s   r  r>   r  r  r   r   r   rA     r  z)PdfPages._write_header.<locals>.<genexpr>r   r  r  r  z\setlength{\parindent}{0pt}z\begin{document}%r   )r/   r  r  r   r4   r  r9   encode)r   width_inchesheight_inchesr  r   r   r   r   _write_header  s   

zPdfPages._write_headerc                 C   s   | S r>   r   r   r   r   r   	__enter__  r  zPdfPages.__enter__c                 C   s   |    d S r>   )close)r   exc_typeexc_valexc_tbr   r   r   __exit__  r  zPdfPages.__exit__c                 C   s,   | j d | jdkr|   | 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   N)r  r9   r  
_run_latexr  r   r   r   r   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  rR   r  movewith_suffixr  )r   r  r   
tex_sourcer   r   r   r    s   
"zPdfPages._run_latexc                 K   s   t |ts"|du rt }nt|}|du rtd| |jj}| \}}| j	dkr4| 
|| n
| jd||f  |j| jfddd| |  j	d7  _	dS )a5  
        Save a `.Figure` to this file as a new page.

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

        Parameters
        ----------
        figure : `.Figure` or int, default: the active figure
            The figure, or index of the figure, that is saved to the file.
        Nz
No figure r   s   \newpage\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%fin\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin%%
r  )r   backendr   )r_   r   r   
get_activeget_fig_managerr   canvasr   r  r  r  r  r9   savefig)r   r   r  managerr   r   r   r   r   r    s"   



zPdfPages.savefigc                 C   s   | j S )z=Return the current number of pages in the multipage pdf file.)r  r   r   r   r   get_pagecount  s   zPdfPages.get_pagecountr>   )r   r   r   r   r}   r  r  r  r  r  r  r  r   r   r   r   r  u  s    

$r  )@r  r`   r   ior   loggingr  rk   r#   r  ri   tempfiler   r   PILr   
matplotlibr,   r   r   r$   matplotlib.backend_basesr   r   r	   r
   !matplotlib.backends.backend_mixedr   matplotlib.backends.backend_pdfr   r   matplotlib.pathr   matplotlib.figurer   matplotlib.font_managerr   matplotlib._pylab_helpersr   	getLoggerr   rR   r   r4   latex_pt_to_inr%  r$  mpl_in_to_ptr8   r<   r\   re   rz   r   r{   r   r   r   r   r  FigureManagerPgfexportr  r  r   r   r   r   <module>   sb    
+- 
    