U
    \	akY                     @   sD  d Z zddlZW n ek
r,   ddlZY nX ddlmZ ddlmZmZ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 ddlmZmZmZmZm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% ddl&m'Z'm(Z( ddl)m*Z+ dZ,dd Z-G dd deZ*G dd deZ.ej/G dd deZ0dS )a  
An `Anti-Grain Geometry <http://antigrain.com>`_ (AGG) backend.

Features that are implemented:

* capstyles and join styles
* dashes
* linewidth
* lines, rectangles, ellipses
* clipping to a rectangle
* output to RGBA and Pillow-supported image formats
* alpha blending
* DPI scaling properly - everything scales properly (dashes, linewidths, etc)
* draw polygon
* freetype2 w/ ft2font

Still TODO:

* integrate screen dpi w/ ppi and text
    N)nullcontext)radianscossin)Image)_apicbook)colors)_Backend_check_savefig_extra_argsFigureCanvasBaseFigureManagerBaseRendererBase)findfontget_font)LOAD_FORCE_AUTOHINTLOAD_NO_HINTINGLOAD_DEFAULTLOAD_NO_AUTOHINT)MathTextParser)Path)BboxBboxBase)RendererAggzv2.2c                  C   s(   t tttttt tttd
} | tjd  S )N)
defaultZno_autohintZforce_autohintZ
no_hintingTFZeitherZnativeautononeztext.hinting)r   r   r   r   mplrcParams)mapping r    C/tmp/pip-unpacked-wheel-wjyw_3jo/matplotlib/backends/backend_agg.pyget_hinting_flag2   s    r"   c                       s   e Zd ZdZe Z fddZdd Zdd Z	dd	 Z
ed
dd Zed
dd Zd6ddZdd Zdd Zd7ddZdd ZddddZdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd8d0d1Zd2d3 Zd4d5 Z   Z!S )9r   z
    The renderer handles all the drawing primitives using a graphics
    context instance that controls the colors/styles
    c                    sd   t    || _|| _|| _tt|t||| _g | _| 	  t
d| _tdd| j| j| _d S )NZAggr   )super__init__dpiwidthheight_RendererAggint	_renderer_filter_renderers_update_methodsr   mathtext_parserr   Zfrom_boundsbbox)selfr&   r'   r%   	__class__r    r!   r$   U   s    

zRendererAgg.__init__c                 C   s   | j | j| jdS )Nr&   r'   r%   r2   r/   r    r    r!   __getstate__c   s    zRendererAgg.__getstate__c                 C   s   |  |d |d |d  d S )Nr&   r'   r%   )r$   )r/   stater    r    r!   __setstate__h   s    zRendererAgg.__setstate__c                 C   s@   | j j| _| j j| _| j j| _| j j| _| j j| _| j j| _d S N)r*   Zdraw_gouraud_triangleZdraw_gouraud_triangles
draw_imageZdraw_markersZdraw_quad_meshcopy_from_bboxr3   r    r    r!   r,   k   s    




zRendererAgg._update_methodsz3.4c                 C   s@   t |  }t|d \}}|j|j|j|j |j|j fS )N.   )npasarraybuffer_rgbar   _get_nonzero_slicesstartstop)r/   orig_imgslice_yslice_xr    r    r!   get_content_extentsv   s    
 
zRendererAgg.get_content_extentsc                 C   s\   |   }|d | j|d |d   g|d |d  | j|d  gg}| |}t||fS )Nr      r;      )rE   r'   r9   r<   array)r/   extentsr.   regionr    r    r!   tostring_rgba_minimized}   s    
z#RendererAgg.tostring_rgba_minimizedNc                 C   s  t jd }|jjd }||  kr,dkrJn n|jrJ|d krJ| d krJt|| }tt|| }t	d||}	t
|	}
|	dd  d |
d d< ||
d< t|	|
D ]\}}|j||d d f }|j}|d k	r||| }tj|d< t||}z| j|||| W q tk
rD } ztd|W 5 d }~X Y qX qnFz| j|||| W n. tk
r } ztd|W 5 d }~X Y nX d S )Nzagg.path.chunksizer   d   rF   z<Exceeded cell block limit (set 'agg.path.chunksize' rcparam))r   r   ZverticesshapeZshould_simplifyZ	get_hatchr<   ceilr)   ZarangeZ
zeros_likezipcodesr   ZMOVETOr*   	draw_pathOverflowError)r/   gcpathZ	transformZrgbFaceZnmaxZnptsZnchZchsizeZi0i1Zii0Zii1vcperrr    r    r!   rR      sD    
$



zRendererAgg.draw_pathc                 C   s:   |dkrt jddd | j|||||||||	|
|||S )Ndata3.3zaSupport for offset_position='data' is deprecated since %(since)s and will be removed %(removal)s.message)r   warn_deprecatedr*   draw_path_collection)r/   rT   Zmaster_transformpathsZall_transformsoffsetsZoffsetTransZ
facecolorsZ
edgecolorsZ
linewidthsZ
linestylesZantialiasedsurlsZoffset_positionr    r    r!   r`      s(               z RendererAgg.draw_path_collectionc                 C   s|   | j || j|\}}}	}
}}}|tt| }|tt| }t|| | }t|| | }| j|||d || dS )z/Draw mathtext using :mod:`matplotlib.mathtext`.rF   N)	r-   parser%   r   r   r   roundr*   draw_text_image)r/   rT   xyspropangleoxoyr&   r'   descentZ
font_imageused_charactersxdydr    r    r!   draw_mathtext   s    zRendererAgg.draw_mathtextFc	                 C   s   |r|  ||||||S t }	| |}
|
d kr4d S |
j|d|	d |
jtjd d |
 d }|
 \}}|d }|d }|t	t
| }|tt
| }t|| | }t|| | }| j|
||d || d S )Nr   flagsztext.antialiased)Zantialiased      P@rF   )rr   r"   _get_agg_fontset_textZdraw_glyphs_to_bitmapr   r   get_descentZget_bitmap_offsetr   r   r   re   r*   rf   )r/   rT   rg   rh   ri   rj   rk   ismathmtextrt   fontdZxoZyorp   rq   r    r    r!   	draw_text   s&    
zRendererAgg.draw_textc                 C   s   |dkrN|dkrt jddd |  }| }|j||| d\}}}|||fS |r|| j|| j|\}	}
}}}}}|||fS t }| 	|}|j
|d|d | \}}| }|d	 }|d	 }|d	 }|||fS )
N)TeXTeX!r   r\   zrSupport for ismath='TeX!' is deprecated since %(since)s and will be removed %(removal)s; use ismath='TeX' instead.r]   )rendererg        rs   ru   )r   r_   get_texmanagerget_size_in_pointsget_text_width_height_descentr-   rd   r%   r"   rv   rw   Zget_width_heightrx   )r/   ri   rj   ry   
texmanagerZfontsizewhr|   rl   rm   r&   r'   rn   Zfontsro   rt   r{   r    r    r!   r      s6       


z)RendererAgg.get_text_width_height_descent)rz   c                C   s   |  }|  }	|	||| j}
t|
d tj}
| j||dd\}}}|tt	| }|t
t	| }t|| }t|| }| j|
|||| d S )N     o@r~   )ry   )r   r   Zget_greyr%   r<   rH   uint8r   r   r   r   re   r*   rf   )r/   rT   rg   rh   ri   rj   rk   rz   sizer   Zr   r   r|   rp   rq   r    r    r!   draw_tex   s    zRendererAgg.draw_texc                 C   s   | j | jfS r7   )r&   r'   r3   r    r    r!   get_canvas_width_height	  s    z#RendererAgg.get_canvas_width_heightc                 C   s2   t |}t|}|  | }||| j |S )zJ
        Get the font for text instance t, caching for efficiency
        )r   r   clearr   Zset_sizer%   )r/   rj   fnamer{   r   r    r    r!   rv     s    zRendererAgg._get_agg_fontc                 C   s   || j  d S )NH   )r%   )r/   Zpointsr    r    r!   points_to_pixels  s    zRendererAgg.points_to_pixelsc                 C   s
   t | jS r7   )
memoryviewr*   r3   r    r    r!   r>     s    zRendererAgg.buffer_rgbac                 C   s"   t | jjddddgdd S )Nr;   r   rF   rG   Zaxisr<   r=   r*   Ztaketobytesr3   r    r    r!   tostring_argb!  s    zRendererAgg.tostring_argbc                 C   s    t | jjdddgdd S )Nr   rF   rG   r   r   r3   r    r    r!   tostring_rgb$  s    zRendererAgg.tostring_rgbc                 C   s   | j   d S r7   )r*   r   r3   r    r    r!   r   '  s    zRendererAgg.clearc                 C   s   dS )NTr    r3   r    r    r!   option_image_nocomposite*  s    z$RendererAgg.option_image_nocompositec                 C   s   dS )NFr    r3   r    r    r!   option_scale_image2  s    zRendererAgg.option_scale_imagec           
   
   C   s   |dk	s|dk	r|dkr*|  \}}}}n&t|trD|j\}}}}n|\}}}}|dkrd|| }}	n|\}}	| j|t|t|t|t|t|t|	 n| j| dS )a4  
        Restore the saved region. If bbox (instance of BboxBase, or
        its extents) is given, only the region specified by the bbox
        will be restored. *xy* (a pair of floats) optionally
        specifies the new position (the LLC of the original region,
        not the LLC of the bbox) where the region will be restored.

        >>> region = renderer.copy_from_bbox()
        >>> x1, y1, x2, y2 = region.get_extents()
        >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
        ...                         xy=(x1-dx, y1))

        N)Zget_extents
isinstancer   rI   r*   restore_regionr)   )
r/   rJ   r.   xyx1y1Zx2y2rl   rm   r    r    r!   r   6  s     
   zRendererAgg.restore_regionc                 C   s6   | j | j tt| jt| j| j| _|   dS )zX
        Start filtering. It simply create a new canvas (the old one is saved).
        N)	r+   appendr*   r(   r)   r&   r'   r%   r,   r3   r    r    r!   start_filterY  s
    zRendererAgg.start_filterc           
   	   C   s   t |  }t|d \}}|||f }| j | _|   |j	r||d | j
\}}}|  }	|jjdkrt |d t j}| j|	|j| t| j|j | |ddd  dS )a  
        Save the plot in the current canvas as a image and apply
        the *post_processing* function.

           def post_processing(image, dpi):
             # ny, nx, depth = image.shape
             # image (numpy array) has RGBA channels and has a depth of 4.
             ...
             # create a new_image (numpy array of 4 channels, size can be
             # different). The resulting image may have offsets from
             # lower-left corner of the original image
             return new_image, offset_x, offset_y

        The saved renderer is restored and the returned image from
        post_processing is plotted (using draw_image) on it.
        r:      fr   NrM   )r<   r=   r>   r   r?   r+   popr*   r,   r   r%   Znew_gcZdtypekindr   r8   r@   r)   r'   rA   )
r/   Zpost_processingrB   rC   rD   Zcropped_imgimgrl   rm   rT   r    r    r!   stop_filterb  s       zRendererAgg.stop_filter)N)FN)NN)"__name__
__module____qualname____doc__	threadingRLocklockr$   r4   r6   r,   r   
deprecatedrE   rK   rR   r`   rr   r}   r   r   r   rv   r   r>   r   r   r   r   r   r   r   r   __classcell__r    r    r0   r!   r   B   s8   


!

#	r   c                       s   e Zd Zdd Zd&ddZ fddZd'd	d
Zdd Zdd Zdd Z	e
dd ZeZe
dddddZdd Ze
dddgdejddddejddddejddd ddd!d"d#ZeZe
dd!d$d%ZeZ  ZS )(FigureCanvasAggc                 C   s   |   }||S r7   )get_rendererr9   )r/   r.   r   r    r    r!   r9     s    zFigureCanvasAgg.copy_from_bboxNc                 C   s   |   }||||S r7   )r   r   )r/   rJ   r.   r   r   r    r    r!   r     s    zFigureCanvasAgg.restore_regionc              
      s^   | j dd| _tj@ | jr&| j nt  | j| j t	   W 5 Q R X W 5 Q R X d S )NT)cleared)
r   r   r   r   ZtoolbarZ_wait_cursor_for_draw_cmr   figuredrawr#   r3   r0   r    r!   r     s    zFigureCanvasAgg.drawFc                 C   sh   | j jj\}}||| j jf}t| do4t| dd |k}|sTt||| j j| _|| _n|rb| j	  | jS )Nr   _lastKey)
r   r.   r   r%   hasattrgetattrr   r   r   r   )r/   r   r   r   keyZreuse_rendererr    r    r!   r     s    

zFigureCanvasAgg.get_rendererc                 C   s
   | j  S )z
        Get the image as RGB `bytes`.

        `draw` must be called at least once before this function will work and
        to update the renderer for any subsequent changes to the Figure.
        )r   r   r3   r    r    r!   r     s    zFigureCanvasAgg.tostring_rgbc                 C   s
   | j  S )z
        Get the image as ARGB `bytes`.

        `draw` must be called at least once before this function will work and
        to update the renderer for any subsequent changes to the Figure.
        )r   r   r3   r    r    r!   r     s    zFigureCanvasAgg.tostring_argbc                 C   s
   | j  S )z
        Get the image as a `memoryview` to the renderer's buffer.

        `draw` must be called at least once before this function will work and
        to update the renderer for any subsequent changes to the Figure.
        )r   r>   r3   r    r    r!   r>     s    zFigureCanvasAgg.buffer_rgbac              	   G   s<   t |  |  }t|d}||  W 5 Q R X d S )Nwb)r   r   r   r   Zopen_file_cmwriter>   )r/   filename_or_objargsr   fhr    r    r!   	print_raw  s    
zFigureCanvasAgg.print_raw)metadata
pil_kwargsc             	   G   s0   t |  tjj||  dd| jj||d dS )a  
        Write the figure to a PNG file.

        Parameters
        ----------
        filename_or_obj : str or path-like or file-like
            The file to write to.

        metadata : dict, optional
            Metadata in the PNG file as key-value pairs of bytes or latin-1
            encodable strings.
            According to the PNG specification, keys must be shorter than 79
            chars.

            The `PNG specification`_ defines some common keywords that may be
            used as appropriate:

            - Title: Short (one line) title or caption for image.
            - Author: Name of image's creator.
            - Description: Description of image (possibly long).
            - Copyright: Copyright notice.
            - Creation Time: Time of original image creation
              (usually RFC 1123 format).
            - Software: Software used to create the image.
            - Disclaimer: Legal disclaimer.
            - Warning: Warning of nature of content.
            - Source: Device used to create the image.
            - Comment: Miscellaneous comment;
              conversion from other image format.

            Other keywords may be invented for other purposes.

            If 'Software' is not given, an autogenerated value for Matplotlib
            will be used.  This can be removed by setting it to *None*.

            For more details see the `PNG specification`_.

            .. _PNG specification:                 https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords

        pil_kwargs : dict, optional
            Keyword arguments passed to `PIL.Image.Image.save`.

            If the 'pnginfo' key is present, it completely overrides
            *metadata*, including the default 'Software' key.
        Zpngupper)formatoriginr%   r   r   N)r   r   r   imageZimsaver>   r   r%   )r/   r   r   r   r   r    r    r!   	print_png  s    1
     zFigureCanvasAgg.print_pngc                 C   s2   t |  |  }t| t|jt|jffS r7   )r   r   r   bytesr>   r)   r&   r'   )r/   r   r    r    r!   print_to_buffer  s
    

zFigureCanvasAgg.print_to_bufferqualityoptimizeprogressive)extra_kwargsr\   zpil_kwargs={'quality': ...})alternativezpil_kwargs={'optimize': ...}zpil_kwargs={'progressive': ...})r   c                O   s  t | j \}}}}z2| j|t|||g d |  t|  W 5 | j||||f X |dkrni }dD ]}	|	|krr|	|	|
|	 qrd|krttjd }
|d< |
dkrtjdddd	d
 |	d| jj| jjf tt|  dddf j|fddi|S )a  
        Write the figure to a JPEG file.

        Parameters
        ----------
        filename_or_obj : str or path-like or file-like
            The file to write to.

        Other Parameters
        ----------------
        quality : int, default: :rc:`savefig.jpeg_quality`
            The image quality, on a scale from 1 (worst) to 95 (best).
            Values above 95 should be avoided; 100 disables portions of
            the JPEG compression algorithm, and results in large files
            with hardly any gain in image quality.  This parameter is
            deprecated.
        optimize : bool, default: False
            Whether the encoder should make an extra pass over the image
            in order to select optimal encoder settings.  This parameter is
            deprecated.
        progressive : bool, default: False
            Whether the image should be stored as a progressive JPEG file.
            This parameter is deprecated.
        pil_kwargs : dict, optional
            Additional keyword arguments that are passed to
            `PIL.Image.Image.save` when saving the figure.  These take
            precedence over *quality*, *optimize* and *progressive*.
        rF   N)r   r   r   r   zsavefig.jpeg_quality)r   K   _   r\   ZrcParamzSet the quality using `pil_kwargs={'quality': ...}`; the future default quality will be 75, matching the default of Pillow and libjpeg.)nameZobj_typeZaddendumr%   .r;   r   Zjpeg)mcolorsZto_rgbar   Zget_facecolorZset_facecolorr<   rH   r   r   
setdefaultr   dict__getitem__r   r   r   r_   r%   r   	fromarrayr=   r>   save)r/   r   r   r   kwargsrgbakr   r    r    r!   	print_jpg  s8    &$
   zFigureCanvasAgg.print_jpgc                C   sT   t |  |d kri }|d| jj| jjf tt| 	 j
|fddi|S )Nr%   r   Ztiff)r   r   r   r   r%   r   r   r<   r=   r>   r   )r/   r   r   r    r    r!   	print_tifM  s    
zFigureCanvasAgg.print_tif)NN)F)r   r   r   r9   r   r   r   r   r   r>   r   r   Z
print_rgbar   r   r   Zdelete_parameterr   Z
print_jpegr   Z
print_tiffr   r    r    r0   r!   r     s@   

			
 5
8r   c                   @   s   e Zd ZeZeZdS )_BackendAggN)r   r   r   r   ZFigureCanvasr   ZFigureManagerr    r    r    r!   r   Y  s   r   )1r   r   ImportErrorZdummy_threading
contextlibr   mathr   r   r   Znumpyr<   ZPILr   Z
matplotlibr   r   r   r	   r   Zmatplotlib.backend_basesr
   r   r   r   r   Zmatplotlib.font_managerr   r   Zmatplotlib.ft2fontr   r   r   r   Zmatplotlib.mathtextr   Zmatplotlib.pathr   Zmatplotlib.transformsr   r   Z matplotlib.backends._backend_aggr   r(   Zbackend_versionr"   r   exportr   r    r    r    r!   <module>   s6     D V