o
    h                  
   @   s  d 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
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ZddlZddlmZmZmZmZ ddlmZ ddl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* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 e
7e8Z9dZ:i 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-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>Z;d?d@dAdBZ<dCdD Z=dEdF Z>dGdH Z?dIdJ Z@dKdL ZAdMdN ZBdOdP ZCdQdR ZDdSdT ZEG dUdV dVe6jFZGG dWdX dXeZHG dYdZ dZe!ZId[d\ ZJd]d^ ZKdod_d`ZLdodadbZMeNdcdpdddeZOdfdg ZPdhdi ZQdqdjdkZRe"ZSg dlZTe jUG dmdn dne ZVdS )rzG
A PostScript backend, which can produce both PostScript .ps and .eps.
    N)Enum)StringIO)TemporaryDirectory)_apicbook_path_text_helpers)AFM)_BackendFigureCanvasBaseFigureManagerBaseRendererBase)is_writable_file_likefile_requires_unicode)get_font)	LoadFlags)	uni2type1)Path)
TexManager)Affine2D)MixedModeRenderer   )_backend_pdf_psFletter)      !@   legal)r      ledger)r      a0)Gz@@gHzgG@a1)p=
c7@r!   a2)
ףp=0@r#   a3)zGa'@r%   a4)
ףp= @r'   a5)RQ@r)   a6)Q@r+   a7)HzG@r-   a8)ffffff @r/   a9)\(\?r1   a10)gRQ?r3   b0)fffffFD@g)\L@b1))\<@r6   b2)QE4@r8   ))\,@r:   )Q8$@r;   )p=
ף@r<   ))\(@r=   )p=
ף@r>   )Gz@r?   ))\(?r@   )g)\(?rA   )b3b4b5b6b7b8b9b10 )sepc                 G   s   |  dd |D S )Nc                 s   s$    | ]}|d  d dV  qdS )1.3f0.N)rstrip).0arg rR   r/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/matplotlib/backends/backend_ps.py	<genexpr>I   s   " z_nums_to_str.<locals>.<genexpr>)join)rK   argsrR   rR   rS   _nums_to_strH   s   rW   c                 C   sr   t |r.t|rt| ddnt| d}| t|| W d   dS 1 s'w   Y  dS 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.
    latin-1encodingrbN)copy_function)r   r   openshutilcopyfileobjmovecopyfile)srcdstfhrR   rR   rS   _move_path_to_path_or_streamL   s   "re   c           
         s  t | dd  fdd|D }dj jd j dtt jd fdd|D t|d d	}d
}g }|D ]@} 	|t
j}  \}}	|d |dtt|jdg|jd tt|d |	dddddg ddd d  q8|d| | S )a  
    Subset *chars* from the font at *font_path* into a Type 3 font.

    Parameters
    ----------
    font_path : path-like
        Path to the font to be subsetted.
    chars : str
        The characters 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   )hinting_factorc                    s   g | ]}  |qS rR   )get_char_indexrP   cfontrR   rS   
<listcomp>n   s    z%_font_to_ps_type3.<locals>.<listcomp>aM  %!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
rJ   c                 3   s     | ]}d   | V  qdS )/N)get_glyph_name)rP   glyph_idrj   rR   rS   rT      s    z$_font_to_ps_type3.<locals>.<genexpr>)	font_nameinv_units_per_embboxrZ   
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   )namerr   @   NF)   m   l       crx   Tasciizce} _d
)r   formatpostscript_nameunits_per_EMrU   mapstrrr   len
load_glyphr   NO_SCALEget_pathappendrn   horiAdvancer   convert_to_stringr   decode)
	font_pathchars	glyph_idspreamble	postambleentriesro   gvri   rR   rj   rS   _font_to_ps_type3\   s>   
r   c              	   C   s  d dd |D }td| | zgi }| drd|d< tjj| fi |G}t| |&}t	|
 }td| t| jt| |t||| W d	   n1 sWw   Y  W d	   W d	S W d	   W d	S 1 sqw   Y  W d	S  ty   td
|   w )a2  
    Subset *chars* from the font at *font_path* into a Type 42 font at *fh*.

    Parameters
    ----------
    font_path : path-like
        Path to the font to be subsetted.
    chars : str
        The characters to include in the subsetted font.
    fh : file-like
        Where to write the font.
     c                 s   s    | ]}t |V  qd S N)chrrh   rR   rR   rS   rT      s    z%_font_to_ps_type42.<locals>.<genexpr>zSUBSET %s characters: %sz.ttcr   
fontNumberzSUBSET %s %d -> %dNzIThe PostScript backend does not currently support the selected font (%s).)rU   _logdebugendswith	fontToolsttLibTTFontr   get_glyphs_subsetfont_as_filegetvalueosstatst_sizer   write_serialize_type42RuntimeErrorwarning)r   r   rd   
subset_strkwrk   subsetfontdatarR   rR   rS   _font_to_ps_type42   s0   

Vr   c           	      C   s   t | d|\}}| d }| d }t|}t|||}td|d  d|d  d| d	 jd
d|d d|d d|d d|d d|j d|j	rQdnd d|j
 d|j dtt|   d| d| dS )aw  
    Output a PostScript Type-42 format representation of font

    Parameters
    ----------
    font : fontTools.ttLib.ttFont.TTFont
        The original font object
    subset : fontTools.ttLib.ttFont.TTFont
        The subset font object
    fontdata : bytes
        The raw font data in TTF format

    Returns
    -------
    str
        The Type-42 formatted font
    locapostrt   z
        %%!PS-TrueTypeFont-r   rN   r   -headz.7fzi
        10 dict begin
        /FontType 42 def
        /FontMatrix [1 0 0 1 0 0] def
        /FontName /   z; def
        /FontInfo 7 dict dup begin
        /FullName (   z) def
        /FamilyName (z) def
        /Version (   z) def
        /ItalicAngle z def
        /isFixedPitch truefalsez  def
        /UnderlinePosition z! def
        /UnderlineThickness zX def
        end readonly def
        /Encoding StandardEncoding def
        /FontBBox [z=] def
        /PaintType 0 def
        /CIDMap 0 def
        z	
        z9
        FontName currentdict end definefont pop
        )_version_and_breakpointsget_generate_charstrings_generate_sfntstextwrapdedentfontRevisiongetDebugNameitalicAngleisFixedPitchunderlinePositionunderlineThicknessrW   _bounds)	rk   r   r   versionbreakpointsr   rt   r   sfntsrR   rR   rS   r      sD   	


r   c              	      s   t d|dd \}}}||f}i  t|D ]!}t d|d|d  d|d d   \}}}	}|	 |d< q| durL fd	d
| jdd D }
nt }
th   |
t|}||fS )a  
    Read the version number of the font and determine sfnts breakpoints.

    When a TrueType font file is written as a Type 42 font, it has to be
    broken into substrings of at most 65535 bytes. These substrings must
    begin at font table boundaries or glyph boundaries in the glyf table.
    This function determines all possible breakpoints and it is the caller's
    responsibility to do the splitting.

    Helper function for _font_to_ps_type42.

    Parameters
    ----------
    loca : fontTools.ttLib._l_o_c_a.table__l_o_c_a or None
        The loca table of the font if available
    fontdata : bytes
        The raw data of the font

    Returns
    -------
    version : tuple[int, int]
        A 2-tuple of the major version number and minor version number.
    breakpoints : list[int]
        The breakpoints is a sorted list of offsets into fontdata; if loca is not
        available, just the table boundaries.
    z>3hNr   z>4sIII      r   rz   c                    s   h | ]} d  | qS )glyfrR   )rP   offsettablesrR   rS   	<setcomp>$  s    z+_version_and_breakpoints.<locals>.<setcomp>)	structunpackranger   	locationssetsortedvaluesr   )r   r   v1v2	numTablesr   itag_r   glyf_breakpointsr   rR   r   rS   r     s   0r   c                 C   s>   |  d}tjj|}| D ]	}|| | q|jpdS )as  
    Compute the font bounding box, as if all glyphs were written
    at the same start position.

    Helper function for _font_to_ps_type42.

    Parameters
    ----------
    font : fontTools.ttLib.ttFont.TTFont
        The font

    Returns
    -------
    tuple
        (xMin, yMin, xMax, yMax) of the combined bounding box
        of all the glyphs in the font
    F)r   r   r   r   )getGlyphSetr   pens	boundsPen	BoundsPenkeysdrawbounds)rk   gspenrt   rR   rR   rS   r   ,  s
   

r   c                 C   sL   |   }dt| d}t|D ]\}}|d| d| d7 }q|d7 }|S )a  
    Transform font glyphs into CharStrings

    Helper function for _font_to_ps_type42.

    Parameters
    ----------
    font : fontTools.ttLib.ttFont.TTFont
        The font

    Returns
    -------
    str
        A definition of the CharStrings dictionary in PostScript
    z/CharStrings z dict dup begin
rm   rJ   z def
zend readonly def)getGlyphOrderr   	enumerate)rk   gosr   rt   rR   rR   rS   r   E  s   r   c                    s   d d}|t | k r6t||d }||d  }||kr |d } d| ||   d7  |}|t | k s
 d7  d	 fd
dtdt  dD S )a  
    Transform font data into PostScript sfnts format.

    Helper function for _font_to_ps_type42.

    Parameters
    ----------
    fontdata : bytes
        The raw data of the font
    font : fontTools.ttLib.ttFont.TTFont
        The fontTools font object
    breakpoints : list
        Sorted offsets of possible breakpoints

    Returns
    -------
    str
        The sfnts array for the font definition, consisting
        of hex-encoded strings in PostScript format
    z/sfnts[r   i  r   r   <z00>z]defr{   c                 3   s     | ]} ||d   V  qdS )d   NrR   )rP   r   r   rR   rS   rT   }  s    z"_generate_sfnts.<locals>.<genexpr>r   )r   bisectbisect_lefthexrU   r   )r   rk   r   posr   newposrR   r   rS   r   ]  s   $r   c                    s   t   fdd}|S )z}
    Wrap `RendererPS` method *meth* to emit a PS comment with the method name,
    if the global flag `debugPS` is set.
    c                    s0   t r| jd j d  | g|R i |S )Nz% r{   )debugPS	_pswriterr   __name__)selfrV   kwargsmethrR   rS   wrapper  s   z!_log_if_debug_on.<locals>.wrapper)	functoolswraps)r   r   rR   r   rS   _log_if_debug_on  s   r   c                       s.  e Zd ZdZedZdZd8 fdd	Zdd Z	d9d
dZ
d9ddZedd Zd9ddZedd Zd9ddZd9ddZd9ddZdd Zdd Zd:d d!Zd"d# Zed;d$d%Zed;d&d'Ze	d;d(d)Zed*d+ Zedd,d-d.Zed:d/d0Zed1d2 Zed3d4 Zd	d	d5d6d7Z   Z!S )<
RendererPSz
    The renderer handles all the drawing primitives using a graphics
    context instance that controls the colors/styles.
    z	fonts/afm	ps.useafmH   c                    s   t  || || _tjd rd| _g | _|| _d | _d | _	d | _
d | _d | _d | _d | _i | _|d | _i | _d| _t | _ttj| _d S )Ntext.usetexr   r   )super__init__r   mplrcParamstextcntpsfragimagedpicolor	linewidthlinejoinlinecaplinedashfontnamefontsize_hatchesimage_magnification_clip_paths_path_collection_idr   CharacterTracker_character_trackerr   cacher   r   _logwarn_once)r   widthheightpswriterr  	__class__rR   rS   r     s&   


zRendererPS.__init__c                 C   sF   |d u rdS t |dkr!|d dkrdS |d dkr| d dS dS )NTr      r   r   zlThe PostScript backend does not support transparency; partially transparent artists will be rendered opaque.F)r   r  )r   rgb_or_rgbarR   rR   rS   _is_transparent  s   zRendererPS._is_transparentTc                 C   sl   |||f| j kr2| j||  kr|krn nt| dnt||| d |r4|||f| _ d S d S d S )Nz	 setgray
z setrgbcolor
)r  r   r   rW   )r   rr   bstorerR   rR   rS   	set_color  s   zRendererPS.set_colorc                 C   s>   t |}|| jkr| jt| d |r|| _d S d S d S )N setlinewidth
)floatr  r   r   rW   )r   r  r  rR   rR   rS   set_linewidth  s   

zRendererPS.set_linewidthc                 C   "   ddddddd|  } | ddS )Nr   r      )miterroundbevelr   r   r$  dz setlinejoin
rR   )r  rR   rR   rS   _linejoin_cmd     zRendererPS._linejoin_cmdc                 C   2   || j kr| j| | |r|| _ d S d S d S r   )r  r   r   r)  )r   r  r  rR   rR   rS   set_linejoin     

zRendererPS.set_linejoinc                 C   r#  )Nr   r   r$  )buttr&  
projectingr   r   r$  r(  z setlinecap
rR   )r  rR   rR   rS   _linecap_cmd  r*  zRendererPS._linecap_cmdc                 C   r+  r   )r  r   r   r0  )r   r  r  rR   rR   rS   set_linecap  r-  zRendererPS.set_linecapc                 C   sx   | j d ur| j \}}t||r||krd S | j|d ur.t|r.dt|  dt| dnd |r:||f| _ d S d S )N[z] z	 setdash
z[] 0 setdash
)r	  nparray_equalr   r   r   rW   )r   r   seqr  oldooldseqrR   rR   rS   set_linedash  s   

zRendererPS.set_linedashc                 C   sL   ||f| j | jfkr"| jd| d|dd |r$|| _ || _d S d S d S )Nrm   rJ   rL    selectfont
)r
  r  r   r   )r   r
  r  r  rR   rR   rS   set_font  s   
zRendererPS.set_fontc                 C   s   d}|| j v r| j | S dt| j  }| 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%dzH  << /PatternType 1
     /PaintType 2
     /TilingType 2
     /BBox[0 0 r(  rJ   z]
     /XStep z
     /YStep z(

     /PaintProc {
        pop
        r   r   Fsimplifyz]
        gsave
        fill
        grestore
        stroke
     } bind
   >>
   matrix
   0 z translate
   makepattern
   /z
 exch def
)
r  r   r  r   r   _convert_pathr   hatchr   scale)r   r>  r  sidelenrt   
pageheightrR   rR   rS   create_hatch  s0   





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   rR   rR   rS   get_image_magnification  s   z"RendererPS.get_image_magnificationFNc              
   C   sD   |rdd| j d | jd f}nd }t||||d dg dddS )Ng        g      R@r   )rv   rw   rx   ry   s   clTrz   )r  r  r   r   r   )r   path	transformclipr<  rR   rR   rS   r=  $  s   

zRendererPS._convert_pathc              
   C   s   g }|  }|d ur|tg |j|jR   d | \}}|d ur\|t|f}| j|}|d u rTdt	| j }| j
d| d| j||dd d || j|< || d d	|S )
N
 rectclip
zc%drm   z {
Fr;  z
clip
newpath
} bind def
r{   r   )get_clip_rectangler   rW   p0sizeget_clip_pathidr  r   r   r   r   r=  rU   )r   gcrG  rectrE  trfkeycustom_clip_cmdrR   rR   rS   _get_clip_cmd-  s$   "


zRendererPS._get_clip_cmdc                 C   s  |j d d \}}d}|d d dd d d df }	|	 dd}
|d u r2d}|| 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 colorimager   r  r{   z1 0 0 1 0 0rJ   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tobytesr   r  rU   r   r   frozen	to_valuesr   r   rS  )r   rN  xyimrF  hwimagecmddatahexdatamatrixxscaleyscalerR   rR   rS   
draw_imageC  sP   

zRendererPS.draw_imagec                 C   sB   |d u o	|  d u }|jo|}| j||||d}| ||| d S )NrG  r<  )get_hatch_pathshould_simplifyr=  _draw_ps)r   rN  rE  rF  rgbFacerG  r<  psrR   rR   rS   	draw_pathd  s   
zRendererPS.draw_pathc                 C   s  |  |rd n%|d |d   kr|d kr"n n	t|d  dn
t|d d   d}g d}| }	| sAt| dkrE| n| d }
|	dkoR|
dk}|rp|d|	  || |	  || 
|  || j||d	d
 |r|r|d |r||dg |r|d |r|d |ddg |j|dd| jd | jd fd	dD ]\}}t|r|dd  \}}||dd|dd qd|}| j|||d	d	d d S )Nr   r   r$  z setgrayr  z setrgbcolor)z/o {gsavenewpath	translatez%.1f setlinewidthFr;  rn  fillgrestorestrokez
} bind defr   rg  r   rJ   z or{   rq  rs  )r  rW   get_linewidthget_forced_alphar   get_rgb	get_alphar   r)  get_joinstyler0  get_capstyler=  extenditer_segmentsr  r  rU   rj  )r   rN  marker_pathmarker_transrE  transrk  ps_colorps_cmdlwalphars  verticescoder[  r\  rl  rR   rR   rS   draw_markersl  sV   $





zRendererPS.draw_markersc                 C   s@  t |dkrt |d jnd}| |||||}|d|  d |d | k }|s:t| |||||||||	|
|||S g }t| |||D ]'\}\}}d| j|f }| j||dd}| j	
d| d| d	 || qE| |||||||	|
|||D ]\}}}}}|d
d|d
d| }| ||| q||  jd7  _d S )Nr   r  r$  zp%d_%dFr;  rm   z {
newpath
translate
z
} bind def
r   rJ   r   )r   r  _iter_collection_uses_per_pathr   draw_path_collectionr   _iter_collection_raw_pathsr  r=  r   r   r   _iter_collectionrj  )r   rN  master_transformpathsall_transformsoffsetsoffset_trans
facecolors
edgecolors
linewidths
linestylesantialiasedsurlsoffset_positionlen_pathuses_per_pathshould_do_optimization
path_codesr   rE  rF  rt   
path_bytesxoyopath_idgc0rk  rl  rR   rR   rS   r    sB   



zRendererPS.draw_path_collection)mtextc             
   C   s2  |  | r	d S t| ds!| d | ||||||d| d S | j||dd\}}	}
| }d| j }t| d d dd	i}d
dd	t
jd d d}|| }d||f }t|d }t||
t|  ||
t|  }| 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)ismathz
psmarker%dr  rK   ,z{\sffamily %s}z{\ttfamily %s})z
sans-serif	monospacezfont.familyr   z{\rmfamily %s}z\color[rgb]{%s} %sZ   z/\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}g      ?rU  z	 moveto
(z)
show
grestore
r   )r  rx  hasattrr  	draw_textget_text_width_height_descentget_size_in_pointsr  rW   r   r   r  r3  radianscossinr  r   r   r   )r   rN  r[  r\  r   propangler  r_  r^  blr  thetextr  fontcmdtexrangler   rR   rR   rS   draw_tex  sD   

&
zRendererPS.draw_texc	                 C   s   |  | r	d S |dkr| ||||||S |r#| ||||||S g }	tjd r| |}
|
jdd	d}d|
  }d}d }|D ]D}tt|dt|d}z|
|}W n tyl   d	}|
d
}Y nw |
||}|}||| 7 }|	|||f ||| 7 }qEn0| |}
| j|
| t||
D ]}|jjdd	d}|j|j}|	||j|f q| j|   t|	dd D ]3\}}| ||
 d d dd |D }| j!"d| #| d|dd|dd|dd| d qd S )Nr  r   rz   replacegMbP?r   uni04Xquestion?c                 S   s   | d S )Nr   rR   )entryrR   rR   rS   <lambda>&  s    z&RendererPS.draw_text.<locals>.<lambda>Fr{   c                 s   s*    | ]\}}}|d d|ddV  qdS )r   z 0 m /r   z
 glyphshowNrR   )rP   r   r[  rt   rR   rR   rS   rT   (  s    z'RendererPS.draw_text.<locals>.<genexpr>rU  r   rJ    translate
 rotate
rV  )$r  rx  r  draw_mathtextr   r  _get_font_afmr}   encoder   r  r   r   ordget_width_from_char_nameKeyErrorget_width_charget_kern_dist_from_namer   _get_font_ttfr  trackr   layout	ft_objectrn   	glyph_idxr[  r  	itertoolsgroupbyr:  rU   r   r   rS  )r   rN  r[  r\  r   r  r  r  r  streamrk   ps_namer?  thisx	last_nameri   rt   r  kernitem
glyph_namegroupr  rR   rR   rS   r    sr   




zRendererPS.draw_textc                 C   s:  | j j|d|\}}}	}
}| j|   | jd|dd|dd|dd d}|
D ]M\}}}}}| j|| |j	|f|krT|j	|f}| jd|j	 d| d	 t
|tr`|t|n|||}| j|dd|dd
| d q,|D ]\}}}}| j| d| d| d| d q|| jd dS )z-Draw the math text using matplotlib.mathtext.r   rU  r   rJ   r  r  Nrm   r9  z	 moveto
/z glyphshow
z
 rectfill
	grestore
)
_text2pathmathtext_parserparser  rx  r   r   r  track_glyphr}   
isinstancer	   get_name_charr   rn   rg   )r   rN  r[  r\  r   r  r  r  r  descentglyphsrectslastfontrk   r  numoxoyr  r_  r^  rR   rR   rS   r  3  s>   
&zRendererPS.draw_mathtextc                 C   s  t |t |ks
J t |dkrd S |jdksJ |jd dks"J |jd dks+J |jdks2J |jd dks;J |jd dksDJ |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  g d	d
}d|d< || |
 |d< |d d d df d |d< |
 dd}| jd|dd|dd|dd|dd| d d S )Nr   r  r   r$  r   )axisi   l    ))flagsu1)pointsz2>u4)colors3u1)dtyper  r  g     o@r  r{   rT  zgsave
<< /ShadingType 4
   /ColorSpace [/DeviceRGB]
   /BitsPerCoordinate 32
   /BitsPerComponent 8
   /BitsPerFlag 8
   /AntiAlias true
   /Decode [ r   rJ   z  0 1 0 1 0 1 ]
   /DataSource <
z
>
>>
shfill
grestore
)r   ndimrW  reshaperF  r3  minmaxceilemptyrX  r   r   r   )r   rN  r  r  r  rW  flat_pointsflat_colors
points_min
points_maxfactorxminyminxmaxymaxra  rb  rR   rR   rS   draw_gouraud_trianglesN  sJ   

z!RendererPS.draw_gouraud_trianglesru  c          
      C   sf  | j j}| dko| |  }|sd}| |rd}| }|r?| |  | |  | 	|
  | j|   |sC|rN| j| dd   |d || | ||  |d |r|si|rm|d | j|dd ddi |d |s|r|d	 |r| || }	|d |t| dd   |d
|	 d |r|d |d	 dS )at  
        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.
        r   FNr  rU  r{   r  zfill
r  rJ   z setpattern fill grestore
zstroke
)r   r   rv  r  rx  	get_hatchr"  r,  rz  r1  r{  r8  
get_dashesr  rS  striprB  get_hatch_linewidthrW   get_hatch_color)
r   rl  rN  rk  rq  rs  r   mightstroker>  
hatch_namerR   rR   rS   rj  ~  sF   	
zRendererPS._draw_ps)r   )T)FNr   )"r   
__module____qualname____doc__r   _get_data_path_afm_font_dir_use_afm_rc_namer   r  r  r"  staticmethodr)  r,  r0  r1  r8  r:  rB  rD  r=  rS  r   rf  rm  r  r  r  r  r  r  rj  __classcell__rR   rR   r  rS   r     sL    








 
	 4
,):

/r   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   )rt   )r   rW  rR   rR   rS   swap_if_landscape  s   z_Orientation.swap_if_landscapeN)r   r  r  r   portraitr  r  rR   rR   rR   rS   r
    s    r
  c                       sz   e Zd ZdZdddZdd Zddddd	d
dZddddZddddZe	
edZe	
edZ fddZ  ZS )FigureCanvasPSr   
PostscriptzEncapsulated Postscript)rl  epsc                 C   s   dS )Nrl  rR   rC  rR   rR   rS   get_default_filetype  s   z#FigureCanvasPS.get_default_filetypeNr  )metadata	papertypeorientationbbox_inches_restorec                K   s*  | j j}d| j _i }	t|ttjfr#t|j}
|
	dd
d|	d< |p&i ddtj d|	d< td}|rGtjt|tjjd	nt |	d
< ddd |	 D }	|d u rbtjd }| }tjdgt|d tjt| d}tjd r| j n| j!}|||f||	|||d| d S )Nr   rz   r  TitleCreatorzMatplotlib vz, https://matplotlib.org/SOURCE_DATE_EPOCHz%a %b %d %H:%M:%S %YCreationDater{   c                 s   s$    | ]\}}d | d| V  qdS )z%%z: NrR   )rP   kr   rR   rR   rS   rT     s    
z+FigureCanvasPS._print_ps.<locals>.<genexpr>zps.papersizefigure)r  )r  r   )dpidsc_commentsr  r  r  )"r  r  r  r   r   PathLikepathlibr   rt   r  r   r   r   __version__getenvdatetimefromtimestampinttimezoneutcstrftimetimectimerU   itemsr  lowerr   check_in_list	papersizecheck_getitemr
  _print_figure_tex_print_figure)r   fmtoutfiler  r  r  r  r   r  r  filenamesource_date_epochprinterrR   rR   rS   	_print_ps  sP   



zFigureCanvasPS._print_psr  c                   s^  |dkt |ttjfst|stdj \	s!dkr'	}}	n	t	 \}}	d|	  
d|	  
}
}|
jj
j }|jj
j }dtju rj||
||f\}
}}}d|	  

d|
|||f t _t	j|dtj	||d	}j|  	
fd
d}tjd rt Q}tj|d}t|ddd}|| W d   n1 sw   Y  tjd dkrtt| d ntjd dkrtt| d t|| W d   dS 1 sw   Y  dS tj|ddd}t |st!"d|}|| W d   dS 1 s(w   Y  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
        string containing Document Structuring Convention comments,
        generated from the *metadata* parameter to `.print_figure`.
        r  z,outfile must be a path or a file-like objectr  g      B@r   r   r  r  r7  c                    s  r	t d| d nt d| d dkrt d | d t d| d t d dj d	t  d
d| d tt}t d| d tjd sM|tjj7 }t d| | d t d| d t d		t| d tjd sjj
 D ]+\}}|svqotjd }t|dkrd}|   |dkr| t|| qot|||  qot 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 t j | d t d| d t d| d st d| d |   d S )Nz%!PS-Adobe-3.0 EPSF-3.0)filez%!PS-Adobe-3.0r  z%%DocumentPaperSizes: z
%%Pages: 1z%%LanguageLevel: 3
z
%%Orientation: r{   z
%%EndComments
r   )endr9  z%%BeginPrologr   z/mpldict %d dict defzmpldict beginzps.fonttype   *   r  r:  z%%EndPrologz%%Page: 1 1z%s translatez	%d rotatez0 0 r   z	 rectclipshowpagez%%EOF)printrt   _get_bbox_headerr   _psDefsr   r  r  usedrU   r*  flushr   r   r   rW   r   r   )rd   Ndictr   r   fonttyperr   r  r  is_epsr  r  ps_rendererrotationr   r  r  r  rR   rS   print_figure_impl  sb   




"z7FigureCanvasPS._print_figure.<locals>.print_figure_implps.usedistillertmp.psr_  rX   rY   Nghostscript)ptyperr   xpdf)#r  r   r   r  r   
ValueErrorr  get_size_inchesr  r-  rr   r  r  r
  r  r   r   r   r   r   r   r  r   rE  rU   r]   _try_distill
gs_distillxpdf_distillre   r   open_file_cmr   codecs	getwriter)r   r1  r2  r  r  r  r  r  paper_widthpaper_heightllxllyurxuryrendererrI  tmpdirtmpfilerd   r9  rR   rE  rS   r0    sh   
";
"

$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
 }t|d}|jd| dt| dtt d	d
t dt|| dt|	d |
d  d| j  ddd |tju r|
|	}	}
||||f}|s|dkr|| j  \}}n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 d   dS 1 sw   Y  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`.
        r  r   r8  r7  rK  z+%!PS-Adobe-3.0 EPSF-3.0
%%LanguageLevel: 3
r{   z&
%%EndComments
%%BeginProlog
/mpldict z dict def
mpldict begin
r   z
end
%%EndProlog
mpldict begin
z translate
0 0 r   rH  z
end
showpage
rX   rY   r  rJ  rL  r   )rM  rr   rotatedrN  N)!r  rP  rr   r  r  r   r   r   r   r   r   r  r   
write_textr?  r   r@  rU   rW   r   r
  r  r  r-  _convert_psfragsr  rt   r   r  rQ  rR  rS  re   )r   r1  r2  r  r  r  r  r  rF  r  r  r  r  rY  rZ  r[  r\  rr   rG  r]  r^  tmppathrW  rX  psfrag_rotatedrR   rR   rS   r/  l  s|   	



"z FigureCanvasPS._print_figure_texrl  r  c                    s   | j   t  S r   )r  draw_without_renderingr   r   rC  r  rR   rS   r     s   

zFigureCanvasPS.draw)r   r  r  	fixed_dpi	filetypesr  r6  r0  r/  r   partialmethodprint_ps	print_epsr   r	  rR   rR   r  rS   r    s"    - Wr  c           
   	   C   s0  t dt jd t jd t jd t jd d||d  i# t jdd||d	kr2d
nd|  	 d dd}W d   n1 sIw   Y  t
 !}tj|d}tdddd||gt t||  W d   n1 suw   Y  t| }d|dv }	W d   |	S 1 sw   Y  |	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.preambler  graphicxr  z:\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{   r  r  r   )psfragsr  epsfile
   )r  NrK  dvipsz-qz-R0z-o	Landscapei  )r   
rc_contextr  
texmanager_usepackage_if_not_loadedr   make_dvirU   resolveas_posixr   r   rE  r   _check_and_log_subprocessr   r^   r`   r]   read)
rc  rl  rW  rX  r  dvifiler^  psfilerd   rd  rR   rR   rS   rb    sJ   


	


rb  c              
   O   sV   z| t |g|R i | W d S  tjy* } ztd| W Y d }~d S d }~ww )Nz%s.  Distillation step skipped.)r   r   ExecutableNotFoundErrorr   r   )funcrc  rV   r   excrR   rR   rS   rQ    s    rQ  c                 C   s   |rdg}n|dkrd|d  d|d  g}nd| g}| d }t jd	 }tt d
jddd| dg|d| | t t|  t	
||  |rXt| ||d dS 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.
    	-dEPSCropr  z-dDEVICEWIDTHPOINTS=r$  z-dDEVICEHEIGHTPOINTS=r  z-sPAPERSIZE=z.pszps.distiller.resr   z-dBATCHz	-dNOPAUSEz-r%dz-sDEVICE=ps2writez-sOutputFile=)r`  N)r   r  r   rw  _get_executable_info
executabler   r   remover^   r`   pstoeps)r_  r  rM  rr   r`  paper_optionrz  r  rR   rR   rS   rR    s4   


rR  c           	   	   C   s   t d t d |rdg}n|dkr#d|d  d|d  g}nd	| g}t 8}t|d
}t|d}tddddddg|| |t tdddd||gt t	||  W d   n1 sgw   Y  |rtt
|  dS d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   pdftopsr~  r  z-dDEVICEWIDTHPOINTS#r$  z-dDEVICEHEIGHTPOINTS#r  z-sPAPERSIZE#ztmp.pdfrK  ps2pdfz-dAutoFilterColorImages#falsez-dAutoFilterGrayImages#falsez-sAutoRotatePages#Nonez-sGrayImageFilter#FlateEncodez-sColorImageFilter#FlateEncodez-papermatchz-level3N)r   r  r   r  r   r   rw  r   r^   r`   r  )	r_  r  rM  rr   r`  r  r^  tmppdftmppsrR   rR   rS   rS  *  sH   

	rS  z3.9c                 C   s   t | |r
t| fS dfS )zx
    Return a postscript header string for the given bbox lbrt=(l, b, r, t).
    Optionally, return rotate command.
    r   )r?  _get_rotate_command)lbrtr`  rR   rR   rS   get_bbox_headerS  s   r  c                 C   s\   | \}}}}dt | dt | dt| dt| d|dd|dd|dd|dS )zGReturn a PostScript header string for bounding box *lbrt*=(l, b, r, t).z%%BoundingBox: rJ   z
%%HiResBoundingBox: z.6f)r$  mathr  r  lr  r  trR   rR   rS   r?  \  s   .r?  c                 C   s$   | \}}}}|| dddddS )uO   Return a PostScript 90° rotation command for bounding box *lbrt*=(l, b, r, t).z.2frJ   r   z translate
90 rotaterR   r  rR   rR   rS   r  c  s   r  c              	   C   s6  | d }t |d}}t | dh}|j}|D ]A}|dr.|d |r-|t|dd  q|drJ|| |d	 |rH|t|dd   n|rR|d
rRq|| q|D ]}|dre|d qY|drkqY|| qYW d   n1 szw   Y  W d   n1 sw   Y  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.
    z.epswbr[   s   %!PSs   %!PS-Adobe-3.0 EPSF-3.0
rz      
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]   r   
startswithr?  r  r  r   r  r^   r`   )r_  rr   r`  rm  epshtmphr   linerR   rR   rS   r  i  s<   

	




 
+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 } _dz/sc { setcachedevice } _dc                   @   s   e Zd ZdZeZdS )
_BackendPSzLevel IIN)r   r  r  backend_versionr  FigureCanvasrR   rR   rR   rS   r    s    r  )Fr   NF)F)NF)Wr  r   rU  r"  enumr   r   ior   r  loggingr  r   r  r^   r   tempfiler   r   r(  r   numpyr3  
matplotlibr   r   r   r   r   matplotlib._afmr	   matplotlib.backend_basesr
   r   r   r   matplotlib.cbookr   r   matplotlib.font_managerr   matplotlib.ft2fontr   matplotlib._mathtext_datar   matplotlib.pathr   matplotlib.texmanagerr   matplotlib.transformsr   !matplotlib.backends.backend_mixedr   r   r   	getLoggerr   r   r   r-  rW   re   r   r   r   r   r   r   r   r   RendererPDFPSBaser   r
  r  rb  rQ  rR  rS  
deprecatedr  r?  r  r  FigureManagerPSr@  exportr  rR   rR   rR   rS   <module>   s    
	
Q$0+#    (  1

')
7