U
    \	a%                     @   s  d Z ddlZddlmZ ddlZddlmZ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ZddlZddlmZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZm Z m!Z!m"Z" dd
l#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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: e;e<Z=dZ>dZ?G dd dZ@e@ ZAdddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2ZBd3d4 ZCd5d6 ZDd7d8 ZEd9d: ZFd;d< ZGd=d> ZHG d?d@ d@e:jIZJdAdB ZKejLdCdDdEG dFdG dGe ZMG dHdI dIeZNG dJdK dKeZOdLdM ZPdNdO ZQdfdRdSZRdgdTdUZSdhdVdWZTdidXdYZUeZVdZd[d\d]d^d_d`dadbdcg
ZWejXG ddde deeZYdS )jzG
A PostScript backend, which can produce both PostScript .ps and .eps.
    N)Enum)StringIOTextIOWrapper)TemporaryDirectory)_apicbook_path)_text_layout)AFM)_Backend_check_savefig_extra_argsFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase_no_output_draw)is_writable_file_likefile_requires_unicode)get_font)LOAD_NO_HINTINGLOAD_NO_SCALE)convert_ttf_to_psMathTextParser)	uni2type1)Path)
TexManager)Affine2D)MixedModeRenderer   )_backend_pdf_pszLevel IIc                   @   s   e Zd Zdd ZdS )PsBackendHelperc                 C   s
   i | _ d S N)_cachedself r&   B/tmp/pip-unpacked-wheel-wjyw_3jo/matplotlib/backends/backend_ps.py__init__/   s    zPsBackendHelper.__init__N)__name__
__module____qualname__r(   r&   r&   r&   r'   r!   .   s   r!   )      !@   )r,      )r-      )Gz@@gHzgG@)p=
c7@r0   )
ףp=0@r1   )zGa'@r2   )
ףp= @r3   )RQ@r4   )Q@r5   )HzG@r6   )g(\ @r7   )Zd;O?gffffff @)gRQ?r8   )fffffFD@g)\L@))\<@r9   )QE4@r:   ))\,@r;   )Q8$@r<   )p=
ף@r=   ))\(@r>   )p=
ף@r?   )Gz@r@   ))\(?rA   )g)\(?rB   )letterZlegalZledgera0Za1Za2a3Za4Za5Za6Za7Za8Za9Za10Zb0Zb1Zb2Zb3Zb4Zb5Zb6Zb7Zb8Zb9Zb10c                 C   sF   t t ddD ]0\}\}}|dr(q| |k r||k r|  S qdS )NT)reverselrD   )sorted	papersizeitems
startswith)whkeypwphr&   r&   r'   _get_papertypeQ   s    

rQ   c                 C   sF   t | tr| S t| }| |kr&t|S d|  }|d}|d}|S )Nz%1.3f0.)
isinstancestrintrstrip)valZivalsr&   r&   r'   _num_to_strZ   s    


rZ   c                  G   s   d tt| S )N )joinmaprZ   )argsr&   r&   r'   _nums_to_strh   s    r_   c                 C   sX   |  dd} |  dd} |  dd} |  dd} |  d	d
} tddd | } | dS )zR
    Quote dangerous characters of S for use in a PostScript string constant.
       \s   \\   (s   \(   )s   \)   's   \251   `s   \301s   [^ -~\n]c                 S   s   dt |   S )Ns   \%03o)ordgroup)xr&   r&   r'   <lambda>u       z!quote_ps_string.<locals>.<lambda>ascii)replaceresubdecode)rY   r&   r&   r'   quote_ps_stringl   s    ro   c              	   C   s\   t |rFt|rt| dddnt| d}| t|| W 5 Q R X ntj| |tjd dS )z
    Move the contents of file at *src* to path-or-filelike *dst*.

    If *dst* is a path, the metadata of *src* are *not* copied.
    rlatin-1encodingrb)copy_functionN)r   r   openshutilcopyfileobjmovecopyfile)srcdstfhr&   r&   r'   _move_path_to_path_or_streamy   s    r~   c           	         s   t | dd dj jd j dtt jd fdd|D t|d d}d}g }|D ]} 	|t
}  \}}|d	 |dtt|jd
f|jd tt|d |ddddd
dddddgdd d  q^|d| | S )a  
    Subset *glyph_ids* from the font at *font_path* into a Type 3 font.

    Parameters
    ----------
    font_path : path-like
        Path to the font to be subsetted.
    glyph_ids : list of int
        The glyph indices to include in the subsetted font.

    Returns
    -------
    str
        The string representation of a Type 3 font, which can be included
        verbatim into a PostScript file.
    r   )Zhinting_factoraM  %!PS-Adobe-3.0 Resource-Font
%%Creator: Converted from TrueType to Type 3 by Matplotlib.
10 dict begin
/FontName /{font_name} def
/PaintType 0 def
/FontMatrix [{inv_units_per_em} 0 0 {inv_units_per_em} 0 0] def
/FontBBox [{bbox}] def
/FontType 3 def
/Encoding [{encoding}] def
/CharStrings {num_glyphs} dict dup begin
/.notdef 0 def
r[   c                 3   s   | ]}d   |V  qdS )z/{}N)formatget_glyph_name).0glyph_idfontr&   r'   	<genexpr>   s   z$_font_to_ps_type3.<locals>.<genexpr>)Z	font_nameZinv_units_per_embboxrs   Z
num_glyphsz
end readonly def

/BuildGlyph {
 exch begin
 CharStrings exch
 2 copy known not {pop /.notdef} if
 true 3 1 roll get exec
 end
} _d

/BuildChar {
 1 index /Encoding get exch get
 1 index /BuildGlyph get exec
} _d

FontName currentdict end definefont pop
z/%(name)s{%(bbox)s sc
r   )namer   @   NF   m   lri      cTrj   zce} _d
)r   r   postscript_nameZunits_per_EMr\   r]   rU   r   lenZ
load_glyphr   get_pathappendr   ZhoriAdvancer   convert_to_stringr   rn   )		font_path	glyph_idspreambleZ	postambleentriesr   gvcr&   r   r'   _font_to_ps_type3   sJ    
      r   c                       s^  e Zd ZdZedZdZe	de
dd Ze	de
dd ZdA fd
d	Ze	ddd Ze	ddd ZdBddZdCddZedd ZdDddZedd ZdEddZdFddZdGdd Zd!d" Zd#d$ ZdHd'd(Zd)d* ZdId+d,ZdJd-d.ZdKd/d0Zd1d2 Z e!dd3dLd5d6Z"dMd7d8Z#d9d: Z$d;d< Z%d=d> Z&dNd?d@Z'  Z(S )O
RendererPSz
    The renderer handles all the drawing primitives using a graphics
    context instance that controls the colors/styles.
    z	fonts/afm	ps.useafm3.4c                 C   s   t dS )NZPSr   r$   r&   r&   r'   rh      ri   zRendererPS.<lambda>z3.3c                 C   s   | j jS r"   )_character_trackerused_charactersr$   r&   r&   r'   rh      ri   H   c                    s   t  || || _tjd r*d| _g | _|| _d | _d | _	d | _
d | _d | _d | _d | _i | _|d | _i | _d| _t | _d S )Ntext.usetexr   r   )superr(   	_pswritermplrcParamstextcntpsfragimagedpicolor	linewidthlinejoinlinecaplinedashfontnamefontsize_hatchesimage_magnification_clip_paths_path_collection_idr    ZCharacterTrackerr   )r%   widthheightZpswriterr   	__class__r&   r'   r(      s$    

zRendererPS.__init__c                 O   s   | j j|| dS )z;Keep track of which characters are required from each font.N)r   trackr%   r^   kwargsr&   r&   r'   track_characters  s    zRendererPS.track_charactersc                 O   s   | j j|| d S r"   )r   merger   r&   r&   r'   merge_used_characters  s    z RendererPS.merge_used_charactersTc                 C   s\   |||f| j krX||kr2||kr2| jd|  n| jd|||f  |rX|||f| _ d S )Nz%1.3f setgray
z%1.3f %1.3f %1.3f setrgbcolor
)r   r   write)r%   rp   r   bstorer&   r&   r'   	set_color
  s    zRendererPS.set_colorc                 C   s0   t |}|| jkr,| jd|  |r,|| _d S )Nz%1.3f setlinewidth
)floatr   r   r   )r%   r   r   r&   r&   r'   set_linewidth  s
    
zRendererPS.set_linewidthc                 C   s"   ddddddd|  } | ddS )Nr   r      )miterroundbevelr   r   r   dz setlinejoin
r&   )r   r&   r&   r'   _linejoin_cmd  s    zRendererPS._linejoin_cmdc                 C   s*   || j kr&| j| | |r&|| _ d S r"   )r   r   r   r   )r%   r   r   r&   r&   r'   set_linejoin"  s    
zRendererPS.set_linejoinc                 C   s"   ddddddd|  } | ddS )Nr   r   r   )buttr   
projectingr   r   r   r   z setlinecap
r&   )r   r&   r&   r'   _linecap_cmd(  s    zRendererPS._linecap_cmdc                 C   s*   || j kr&| j| | |r&|| _ d S r"   )r   r   r   r   )r%   r   r   r&   r&   r'   set_linecap/  s    
zRendererPS.set_linecapc                 C   sx   | j d k	r,| j \}}t||r,||kr,d S |d k	rZt|rZdt| |f }| j| n| jd |rt||f| _ d S )Nz[%s] %d setdash
z[] 0 setdash
)r   npZarray_equalr   r_   r   r   )r%   offsetseqr   ZoldoZoldseqrY   r&   r&   r'   set_linedash5  s    

zRendererPS.set_linedashc                 C   sD   ||f| j | jfkr@| jd| d|dd |r@|| _ || _d S )N/r[   z1.3f selectfont
)r   r   r   r   )r%   r   r   r   r&   r&   r'   set_fontC  s
    zRendererPS.set_fontc                 C   s   d}|| j kr| j | S dt| j  }tjd }| jd }| jd|dd|dd|dd|dd	|d
d| jt	|t
 |dd d|d
d| d || j |< |S )Nr   zH%dzhatch.linewidthzH  << /PatternType 1
     /PaintType 2
     /TilingType 2
     /BBox[0 0 r   r[   z]
     /XStep z
     /YStep z(

     /PaintProc {
        pop
        fz setlinewidth
Fsimplifyz_
        gsave
        fill
        grestore
        stroke
     } bind
   >>
   matrix
   0.0 z translate
   makepattern
   /z
 exch def
)r   r   r   r   r   r   r   _convert_pathr   hatchr   scale)r%   r   Zsidelenr   r   Z
pageheightr&   r&   r'   create_hatchJ  s"    



0 
 

zRendererPS.create_hatchc                 C   s   | j S )z
        Get the factor by which to magnify images passed to draw_image.
        Allows a backend to have images at a different resolution to other
        artists.
        )r   r$   r&   r&   r'   get_image_magnificationl  s    z"RendererPS.get_image_magnificationFNc                 C   sJ   |rdd| j d | jd f}nd }t||||d ddddddgd	d
S )Ng        g      R@   r   r   ri   r   s   clTrj   )r   r   r   r   rn   )r%   path	transformclipr   r&   r&   r'   r   t  s          zRendererPS._convert_pathc              
   C   s   g }|  }|d k	r.|dt|j|j   | \}}|d k	r|t|f}| j|}|d krdt	| j }| j
d| d| j||dd d || j|< || d d	|S )
Nz%s clipbox
zc%xr   z {
Fr   z
clip
newpath
} bind def
r    )Zget_clip_rectangler   r_   sizeZp0Zget_clip_pathidr   getr   r   r   r   r\   )r%   gcr   Zrectr   ZtrfrN   Zcustom_clip_cmdr&   r&   r'   _get_clip_cmd}  s$    

zRendererPS._get_clip_cmdc                    s0  |j d d \}}d}|d d dd d d df  d    d fddttt  D }	|d krd	}
|| j }|| j }n d
t	t
|  }
d}d}| jd| | d|dd
|dd|
 d|dd
|dd|dd|dd
|dd|dd|dd|dd| d|	 d d S )Nr   zfalse 3 colorimage      r   c                    s$   g | ]} | |d    qS )r   r&   )r   ndataZncharsr&   r'   
<listcomp>  s   z)RendererPS.draw_image.<locals>.<listcomp>z1 0 0 1 0 0r[   g      ?gsave
r   z translate
[z	] concat
z scale
/DataString r   z string def
z 8 [ z 0 0 -z 0 z5 ]
{
currentfile DataString readhexstring pop
} bind 

grestore
)shapetobyteshexr\   rangemathceilr   r   r]   rU   frozenZ	to_valuesr   r   r   )r%   r   rg   yZimr   rM   rL   ZimagecmdZhexlinesZmatrixZxscaleZyscaler&   r   r'   
draw_image  s4    
D
zRendererPS.draw_imagec                 C   sB   |d ko|  d k}|jo|}| j||||d}| ||| d S )Nr   r   )Zget_hatch_pathZshould_simplifyr   _draw_ps)r%   r   r   r   rgbFacer   r   psr&   r&   r'   	draw_path  s    
zRendererPS.draw_pathc                 C   s  t r| jd t|rd n>|d |d   kr<|d krLn nd|d  nd|d d  }dd	d
dg}| }	| st| dkr| n
| d }
|	dko|
dk}|r|	d|	  |	| 
|  |	| |  |	| j||dd |r6|r|	d	 |r&||dg |r6|	d |rF|	d |ddg |j|dd| jd | jd fddD ]6\}}t|rx|dd  \}}|	d||f  qxd|}| j|||ddd d S )Nz% draw_markers 
r   r   r   z%1.3f setgrayz%1.3f %1.3f %1.3f setrgbcolorr   z/o {Zgsavenewpath	translatez%.1f setlinewidthFr   fillZgrestorestrokez
} bind defr   r   z%g %g or   )r   r  )debugPSr   r   _is_transparentget_linewidthZget_forced_alphar   get_rgbZ	get_alphar   r   get_joinstyler   get_capstyler   extendZiter_segmentsr   r   r\   r   )r%   r   Zmarker_pathZmarker_transr   transr   Zps_colorZps_cmdZlwalphar  verticescoderg   r   r   r&   r&   r'   draw_markers  s^     







zRendererPS.draw_markersc                 C   s:  t |dkrt |d jnd}| |||||}|d|  d |d | k }|stt| |||||||||	|
|||S g }t| |||D ]N\}\}}d| j|f }| j||dd}| j	
d| d| d	 || q| |||||||||	|
|||D ]*\}}}}}d
|||f }| ||| q|  jd7  _d S )Nr   r   r   zp%x_%xFr   r   z {
newpath
translate
z
} bind def
z%g %g %sr   )r   r  Z_iter_collection_uses_per_pathr   draw_path_collection	enumerateZ_iter_collection_raw_pathsr   r   r   r   r   Z_iter_collectionr   )r%   r   Zmaster_transformpathsZall_transformsoffsetsZoffsetTransZ
facecolorsZ
edgecolorsZ
linewidthsZ
linestylesZantialiasedsurlsZoffset_positionZlen_pathZuses_per_pathZshould_do_optimizationZ
path_codesir   r   r   Z
path_bytesxoyoZpath_idZgc0r   r   r&   r&   r'   r    sv    	                
          zRendererPS.draw_path_collectionismathTeX!c	              
   C   s8  t | ds0td | ||||||d| d S | j||dd\}	}
}| }d| j }d| d d  }d	d
dt	j
d d d}|| }d||f }d}tt	j
drt|| |}| jd||||d |f  n0t|| || }| jd||||d |f  | jd| d| d |  jd7  _d S )Nr   zThe PS backend determines usetex status solely based on rcParams['text.usetex'] and does not support having usetex=True only for some elements; this element will thus be rendered as if usetex=False.FTeX)r  z
psmarker%dz%1.3f,%1.3f,%1.3fr   z{\sffamily %s}z{\ttfamily %s})z
sans-serifZ	monospacezfont.familyr   z{\rmfamily %s}z\color[rgb]{%s} %sztext.latex.previewz/\psfrag{%s}[Bl][Bl][1][%f]{\fontsize{%f}{%f}%s}g      ?z/\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}r   z	 moveto
(z)
show
grestore
r   )hasattr_logwarning	draw_textZget_text_width_height_descentget_size_in_pointsr   r  r   r   r   dict__getitem__r_   r   r   r   r   )r%   r   rg   r   rY   propangler  mtextrL   rM   blr   thetextr   ZfontcmdZtexZcorrposr&   r&   r'   draw_tex'  s\    

         
zRendererPS.draw_texc	                    s  t r| jd t| r d S |dkr<| ||||||S |rT| ||||||S tjd r| 	| d|
  }	d}
d }g }|D ]}tt|dt|d}z |}W n" tk
r   d} d	}Y nX  ||}|}|
||	 7 }
||
|f |
||	 7 }
qnB| |  j|dtd
 | j |  fddt| D }| j|    jddd}| ||
  ddd |D }| jd|  | d|dd|dd|dd| d d S )Nz% text
r  r   gMbP?r   uniZ04XZquestion?)flagsc                    s   g | ]}|j  |jfqS r&   )rg   r   Z	glyph_idx)r   itemr   r&   r'   r   {  s   z(RendererPS.draw_text.<locals>.<listcomp>rj   rk   r   c                 s   s&   | ]\}}|d d|ddV  qdS )r   z 0 m /rY   z
 glyphshowNr&   )r   rg   r   r&   r&   r'   r     s   z'RendererPS.draw_text.<locals>.<genexpr>r   r   r[    translate
 rotate
r   )!r  r   r   r  r  r'  draw_mathtextr   r   Z_get_font_afmr  r   r   re   Zget_width_from_char_nameKeyErrorZget_width_charZget_kern_dist_from_namer   Z_get_font_ttfZset_textr   r   r   r	   Zlayoutr   r   encodern   r   r\   r   )r%   r   rg   r   rY   r!  r"  r  r#  r   Zthisx	last_nameZxs_namesr   r   r   kernZps_namer%  r&   r   r'   r  T  s`    



 
zRendererPS.draw_textc                 C   sZ  t r| jd | jjj|d|tjd d\}}}	}
}| j|	   | jd|dd|dd|dd	 d
}|
D ]\}}}}}| j
|t| |j|f|kr|j|f}| jd|j d| d t|tr|t|n|||}| j|dd|dd| d qr|D ]2\}}}}| j| d| d| d| d q| jd d
S )z-Draw the math text using matplotlib.mathtext.z% mathtext
r   r   )Z_force_standard_ps_fontsr   r   r[   r,  r-  Nr   r   z	 moveto
/z glyphshow
z
 rectfill
	grestore
)r  r   r   Z
_text2pathmathtext_parserparser   r   r   r  r   r   chrr   rT   r
   Zget_name_charr   get_char_index)r%   r   rg   r   rY   r!  r"  r   r   ZdescentZglyphsZrectsZlastfontr   r   numZoxZoyZsymbol_namerL   rM   r&   r&   r'   r.    s<      
(zRendererPS.draw_mathtextc                 C   s    |  ||d|d| d S )N)r   r   r   )r   r      )draw_gouraud_trianglesreshape)r%   r   pointscolorsr
  r&   r&   r'   draw_gouraud_triangle  s     z RendererPS.draw_gouraud_trianglec                 C   s  t |t |kst|jdks"t|jd dks4t|jd dksFt|jdksTt|jd dksft|jd dksxt|j}||d |d  df}||}||d |d  df}tj|ddd }tj|ddd }	t	d|	|  }
|\}}|	\}}tj
|d |d  d	d
dgd}d|d< || |
 |d< |d d d df d |d< t| }| jd|dd|dd|dd|dd| d d S )Nr   r   r   r9  r   )Zaxisi   l    )r*  u1)r<  z2>u4)r=  Z3u1)Zdtyper*  r<  g     o@r=  zgsave
<< /ShadingType 4
   /ColorSpace [/DeviceRGB]
   /BitsPerCoordinate 32
   /BitsPerComponent 8
   /BitsPerFlag 8
   /AntiAlias true
   /Decode [ r   r[   z 0 1 0 1 0 1 ]
   /DataSource (z)
>>
shfill
grestore
)r   AssertionErrorndimr   r;  r   r   minmaxr   emptyro   r   r   r   )r%   r   r<  r=  r
  r   Zflat_pointsZflat_colorsZ
points_minZ
points_maxZfactorZxminZyminZxmaxZymaxZ	streamarrstreamr&   r&   r'   r:    s6    
(	z!RendererPS.draw_gouraud_trianglesc                 C   sr  | j j}tr |r |d| d  | dko8t|  }|sBd}t|rNd}| }	|r| |  | |	  | 
|  | j|   | j| dd   |d || | ||  |d |r|s|	r|d | j|dd ddi |d	 |s|	r|d
 |	rX| |	}
|d |d| dd   |d|
  |rf|d |d
 dS )av  
        Emit the PostScript snippet 'ps' with all the attributes from 'gc'
        applied.  'ps' must consist of PostScript commands to construct a path.

        The fill and/or stroke kwargs can be set to False if the
        'ps' string already includes filling and/or stroking, in
        which case _draw_ps is just supplying properties and
        clipping.
        z% r   r   FNr   r   r   zfill
r3  z	%f %f %f z%s setpattern fill grestore
zstroke
)r   r   r  r  r  r  Z	get_hatchr   r   r  r   r  r   Z
get_dashesr   r   stripr   Zget_hatch_color)r%   r   r   r   r   r  commandr   Zmightstroker   Z
hatch_namer&   r&   r'   r     sH    
zRendererPS._draw_ps)r   )T)T)T)T)T)T)FN)N)N)N)r  N)FN)TTN))r)   r*   r+   __doc__r   Z_get_data_pathZ_afm_font_dirZ_use_afm_rc_namer   
deprecatedpropertyr4  r   r(   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r  r  delete_parameterr'  r  r.  r>  r:  r   __classcell__r&   r&   r   r'   r      sP   













"
	
*
 
7,
,
9+r   c                 C   sJ   | d krdS t | dkrB| d dkr(dS | d dkr>td dS dS d S )NTr9  r   r   r   zlThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.F)r   r  r  )Zrgb_or_rgbar&   r&   r'   r    s    r  r   r   )alternativec                       s(   e Zd Z fddZ fddZ  ZS )GraphicsContextPSc                    s   ddddt    S )Nr   r   r   )r   r   r   )r   r  r$   r   r&   r'   r  $  s    zGraphicsContextPS.get_capstylec                    s   ddddt    S )Nr   r   r   )r   r   r   )r   r  r$   r   r&   r'   r  '  s    zGraphicsContextPS.get_joinstyle)r)   r*   r+   r  r  rM  r&   r&   r   r'   rO  "  s   rO  c                   @   s    e Zd Zed\ZZdd ZdS )_Orientationr   c                 C   s   | j dkr|d d d S |S )N	landscaper   )r   )r%   r   r&   r&   r'   swap_if_landscape.  s    z_Orientation.swap_if_landscapeN)r)   r*   r+   r   portraitrQ  rR  r&   r&   r&   r'   rP  +  s   rP  c                       s   e Zd ZdZdddZdd Zdd Zd	d
 Ze	dddddddddZ
eddddZeddddZ fddZ  ZS )FigureCanvasPSr   Z
PostscriptzEncapsulated Postscript)r   epsc                 C   s   dS Nr   r&   r$   r&   r&   r'   get_default_filetype7  s    z#FigureCanvasPS.get_default_filetypec                 O   s   | j |df||S rV  	_print_psr%   outfiler^   r   r&   r&   r'   print_ps:  s    zFigureCanvasPS.print_psc                 O   s   | j |df||S )NrU  rX  rZ  r&   r&   r'   	print_eps=  s    zFigureCanvasPS.print_epsr   dpiNrS  )r^  metadata	papertypeorientationc                O   s0  |d kr| j  }| j d i }	t|ttjfrTt|j	}
|

ddd|	d< |pZi ddtj d|	d< td}|rtjt|d	nt |	d
< ddd |	 D }	|d krtjd }| }tjdt|d tjt| d}tjd r
| jn| j }|||f||	||d| d S )Nr   rj   rk   ZTitleZCreatorzMatplotlib vz, https://matplotlib.org/SOURCE_DATE_EPOCHz%a %b %d %H:%M:%S %YZCreationDater   c                 s   s"   | ]\}}d | d| V  qdS )z%%z: Nr&   )r   kr   r&   r&   r'   r   Y  s    z+FigureCanvasPS._print_ps.<locals>.<genexpr>zps.papersizeauto)r`  )ra  r   )r^  dsc_commentsra  r`  )rd  )!figureZget_dpiZset_dpirT   rU   osPathLikepathlibr   r   r0  rn   r   r   __version__getenvdatetimeutcfromtimestamprV   strftimetimectimer\   rJ   r   lowerr   Zcheck_in_listrI   Zcheck_getitemrP  _print_figure_tex_print_figure)r%   r[  r   r^  r_  r`  ra  r^   r   re  filenameZsource_date_epochprinterr&   r&   r'   rY  @  sT    



 
 zFigureCanvasPS._print_psbbox_inches_restorec                   s  |dkt |ttjfr(t|}d}nt|r6d}ntdj \	dkrft	
	f 
t \}	}
tjd r	|	ks|
krt	
	f 
t \}	}
d|		  
d|
  
}}|jjj }|jjj }dtjkr,||||f\}}}}d	|
  
 
d
||||f t _t	j|dtj	||d}j|  	
fdd}tjd r6t }tj|d}t|ddd}|| W 5 Q R X tjd dkrtt| d n"tjd dkr tt| d t|| W 5 Q R X n\|rpt |}|sbt!|dd}dd |_"n|}|| n"t|ddd}|| W 5 Q R X dS )a+  
        Render the figure to a filesystem path or a file-like object.

        Parameters are as for `.print_figure`, except that *dsc_comments* is a
        all string containing Document Structuring Convention comments,
        generated from the *metadata* parameter to `.print_figure`.
        rU  FTz,outfile must be a path or a file-like objectrd  ps.usedistillerg      B@r   r   Z   r   rv  c              	      s8  rt d| d nt d dd| d t  dj dtd	  d
d| d tt}t d| d tjd s|tjj7 }t d| | d t d| d t d	t| d tjd sljj
 D ]\}}|sqt|  fdd|D }tjd }t|dkr
d}|   |dkr.| t|| qztt|| || W q tk
rh   td  Y qX qt d| d t d| d st d| d t d| d t dt | d rt d | d t dt
d d d	d	 | d t 	j | d t d| d t d| d s,t d| d |   d S )Nz%!PS-Adobe-3.0 EPSF-3.0)filez%%!PS-Adobe-3.0
%%DocumentPaperSizes: z
%%Pages: 1
r   )endr{  z
%%Orientation: r   r   z
%%EndComments
z%%BeginPrologr   z/mpldict %d dict defzmpldict beginc                    s   g | ]}  |qS r&   )r7  )r   r   r   r&   r'   r     s     zKFigureCanvasPS._print_figure.<locals>.print_figure_impl.<locals>.<listcomp>zps.fonttype   *   r   zDThe PostScript backend does not currently support the selected font.r|  z%%EndPrologz%%Page: 1 1z%s translatez	%d rotatez
%s clipboxr   Zshowpagez%%EOF)printr   get_bbox_headerr   psDefsr   r   r   usedr\   rJ   r   flushr   r   r   rg  fsencodeRuntimeErrorr  r  r_   r   getvalue)r}   ZNdictr   charsr   Zfonttyper   re  r   is_epsra  r`  ps_rendererZrotationr%   r   r  r  r   r'   print_figure_impl  st       





  
z7FigureCanvasPS._print_figure.<locals>.print_figure_impltmp.psrL   rq   rr   ghostscript)ptyper   xpdfc                   S   s   d S r"   r&   r&   r&   r&   r'   rh     ri   z.FigureCanvasPS._print_figure.<locals>.<lambda>N)#rT   rU   rg  rh  fspathr   
ValueErrorrf  get_size_inchesrQ   rR  rI   r   r   r   r   r   rP  rQ  r   r   r   r   drawr   r   r\   rv   _try_distill
gs_distillxpdf_distillr~   r   r   close)r%   r[  r   r^  re  ra  r`  rw  Zpassed_in_file_objectpaper_widthpaper_heightllxllyurxuryrendererr  tmpdirtmpfiler}   Zrequires_unicoder&   r  r'   rs  j  s    

    "D      
zFigureCanvasPS._print_figurec                C   s
  |dk}| j  \}	}
d}d}|}|}|| j jj }|| j jj }||||f}t | _t|	|
| j|d}t| j |	|
|||d}| j 	| t
 n}tj|d}t|jd| dt|d  dtt d	d
t dt|| dt|	d |
d  d| j  ddd |tjkr0|
|	 }	}
||||f}|rL|| j  \}}n |dkr`t|	|
}t| \}}| }| }| }t||j|||||j }t!j"d dkst!j"d rt#t$|||||d n$t!j"d dkrt#t%|||||d t&|| W 5 Q R X dS )a(  
        If :rc:`text.usetex` is True, a temporary pair of tex/eps files
        are created to allow tex to manage the text layout via the PSFrags
        package. These files are processed to yield the final ps or eps file.

        The rest of the behavior is as for `._print_figure`.
        rU  r   rz  rv  r  z%!PS-Adobe-3.0 EPSF-3.0
r   z&
%%EndComments
%%BeginProlog
/mpldict z dict def
mpldict begin
r   z
end
%%EndProlog
mpldict begin
r,  r   z 0 0 clipbox
z
end
showpage
rq   rr   rd  rx  r  r   )r  r   rotatedr  N)'rf  r  r   r   r   r   r   r   r   r  r   rg  r   r\   ri  r   
write_textr  r   r  r_   r  rP  rQ  rR  rQ   rI   Zget_texmanagerZget_font_preambleZget_custom_preambleconvert_psfragsr   r   r   r   r  r  r  r~   )r%   r[  r   r^  re  ra  r`  rw  r  r   r   r  r  r  r  r  r  r   r  r  r  r  r  r  Z
texmanagerfont_preamblecustom_preamblepsfrag_rotatedr&   r&   r'   rr    s       






       z FigureCanvasPS._print_figure_texc                    s   t | j t  S r"   )r   rf  r   r  r$   r   r&   r'   r  l  s    
zFigureCanvasPS.draw)r)   r*   r+   Z	fixed_dpi	filetypesrW  r\  r]  r   rL  rY  r   rs  rr  r  rM  r&   r&   r   r'   rT  2  s*   
   ) #^rT  c              	   C   s   t dt jd d||d  iB t jdd||dkr@dndt|  	 d	 d
d}W 5 Q R X t
 8}tj|d}	tdddd|	|gt t|	|  W 5 Q R X t| }
d|
dk}W 5 Q R X |S )aj  
    When we want to use the LaTeX backend with postscript, we write PSFrag tags
    to a temporary postscript file, each one marking a position for LaTeX to
    render some text. convert_psfrags generates a LaTeX document containing the
    commands to convert those tags to text. LaTeX/dvips produces the postscript
    file that includes the actual text.
    ztext.latex.preamblezq\usepackage{psfrag,color}
\usepackage[dvips]{graphicx}
\geometry{papersize={%(width)sin,%(height)sin},margin=0in})r   r   zt
\begin{figure}
  \centering\leavevmode
  %(psfrags)s
  \includegraphics*[angle=%(angle)s]{%(epsfile)s}
\end{figure}r   rQ  ry  r   )psfragsr"  epsfile
   )r   r  Zdvipsz-qz-R0z-oZ	Landscapei  )r   Z
rc_contextr   r   Zmake_dvir\   ri  r   resolveas_posixr   rg  r   r   _check_and_log_subprocessr  rw   ry   rv   read)r  r  r  r  r  r  ra  Zdvifiler  psfiler}   r  r&   r&   r'   r  q  s6    	 	
r  c              
   O   sD   z| || W n0 t jk
r> } ztd| W 5 d }~X Y nX d S )Nz%s.  Distillation step skipped.)r   ZExecutableNotFoundErrorr  r  )funcr^   r   excr&   r&   r'   r    s    r  FrC   c              
   C   s|   |r
d}nd| }| d }t jd }tt djddd| d	|d
| | gt t|  t	
||  |rxt| ||d dS )z
    Use ghostscript's pswrite or epswrite device to distill a file.
    This yields smaller files without illegal encapsulated postscript
    operators. The output is low-level, converting text to outlines.
    	-dEPSCropz-sPAPERSIZE=%s.pszps.distiller.resgsz-dBATCHz	-dNOPAUSEz-r%dz-sDEVICE=ps2writez-sOutputFile=%sr  N)r   r   r   r  _get_executable_info
executabler  rg  removerw   ry   pstoeps)r  rU  r  r   r  Zpaper_optionr  r^  r&   r&   r'   r    s*    

     
r  c                 C   s   t d t d | d }| d }tddddd	d
|r<dnd| | |g	t tdddd||gt t|  t||  |rt	|  t

| d D ]}t| qdS )a
  
    Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
    This yields smaller files without illegal encapsulated postscript
    operators. This distiller is preferred, generating high-level postscript
    output that treats text as text.
    r  Zpdftopsz.pdfr  Zps2pdfz-dAutoFilterColorImages#falsez-dAutoFilterGrayImages#falsez-sAutoRotatePages#Nonez-sGrayImageFilter#FlateEncodez-sColorImageFilter#FlateEncoder  z-sPAPERSIZE#%sz-papermatchz-level2z.*N)r   r  r   r  r  rg  r  rw   ry   r  glob)r  rU  r  r   r  Zpdffiler  fnamer&   r&   r'   r    s6    

 	 
r  c           	      C   sd   | \}}}}|r"d|| df }nd}d||t |t |f }d||||f }d||g|fS )zx
    Return a postscript header string for the given bbox lbrt=(l, b, r, t).
    Optionally, return rotate command.
    z%.2f %.2f translate
90 rotater   r   z%%%%BoundingBox: %d %d %d %dz)%%%%HiResBoundingBox: %.6f %.6f %.6f %.6fr   )r   r   r\   )	Zlbrtr  rG   r   rp   trotate	bbox_infoZhires_bbox_infor&   r&   r'   r    s       r  c           
   
   C   s&  |rt ||d\}}nd\}}| d }t|d}t| d}|j}|D ]|}	|	drv|d |r||dd	  qH|	d
r||	 |d |r||dd	   qqH|r|	drqH||	 qH|D ],}	|	dr|d q|	drq||	 qW 5 Q R X W 5 Q R X t|  t||  dS )z
    Convert the postscript to encapsulated postscript.  The bbox of
    the eps file will be replaced with the given *bbox* argument. If
    None, original bbox will be used.
    r  )NNz.epswbrt   s   %!PSs   %!PS-Adobe-3.0 EPSF-3.0
rj      
s   %%EndCommentssp   %%BeginProlog
save
countdictstack
mark
newpath
/showpage {} def
/setpagedevice {pop} def
%%EndProlog
%%Page 1 1
)s   %%Bounds   %%HiResBounds   %%DocumentMedias   %%Pagess   %%EOFsJ   cleartomark
countdictstack
exch sub { end } repeat
restore
showpage
%%EOF
s   %%PageBoundingBoxN)	r  rv   r   rK   r0  rg  r  rw   ry   )
r  r   r  r  r  r  ZepshZtmphr   liner&   r&   r'   r    s8    

	




r  z/_d { bind def } bind defz/m { moveto } _dz/l { lineto } _dz/r { rlineto } _dz/c { curveto } _dz/cl { closepath } _dz/ce { closepath eofill } _dzO/box {
      m
      1 index 0 r
      0 exch r
      neg 0 r
      cl
    } _dz6/clipbox {
      box
      clip
      newpath
    } _dz/sc { setcachedevice } _dc                   @   s   e Zd ZeZdS )
_BackendPSN)r)   r*   r+   rT  ZFigureCanvasr&   r&   r&   r'   r  s  s   r  )FrC   NF)FrC   NF)F)NF)ZrH  rl  enumr   r  ior   r   loggingr   rg  ri  rl   rw   tempfiler   ro  Znumpyr   Z
matplotlibr   r   r   r   r	   Zmatplotlib.afmr
   Zmatplotlib.backend_basesr   r   r   r   r   r   r   Zmatplotlib.cbookr   r   Zmatplotlib.font_managerr   Zmatplotlib.ft2fontr   r   Zmatplotlib._ttconvr   Zmatplotlib.mathtextr   Zmatplotlib._mathtext_datar   Zmatplotlib.pathr   Zmatplotlib.texmanagerr   Zmatplotlib.transformsr   Z!matplotlib.backends.backend_mixedr   r   r    	getLoggerr)   r  Zbackend_versionr  r!   Zps_backend_helperrI   rQ   rZ   r_   ro   r~   r   ZRendererPDFPSBaser   r  rI  rO  rP  rT  r  r  r  r  r  r  ZFigureManagerPSr  exportr  r&   r&   r&   r'   <module>   s   $
	P    >  A1
"
%

=%