B
    #õå[QD  ã               @   sÞ   d dl mZ d dlZd dl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mZmZ dd	lmZ yd d
lmZ W n ek
r˜   dZY nX G dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZdS )é    )Ú	b64decodeN)Úwarn)ÚQtCoreÚQtGui)Úensure_dir_exists)ÚBool)Úsave_svgÚsvg_to_clipboardÚsvg_to_imageé   )ÚJupyterWidget)Úlatex_to_pngc               @   s   e Zd ZdZdS )Ú
LatexErrorzException for Latex errorsN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   ú<lib/python3.7/site-packages/qtconsole/rich_jupyter_widget.pyr      s   r   c               @   s   e Zd ZdZdS )ÚRichIPythonWidgetz4Dummy class for config inheritance. Destroyed below.N)r   r   r   r   r   r   r   r   r      s   r   c                   sê   e Zd ZdZdZedƒZdZ‡ fdd„Z‡ fdd„Z	‡ fdd	„Z
d
d„ Z‡ fdd„Z‡ fdd„Zdd„ Zd/dd„Zd0dd„Zd1dd„Zd2dd„Zdd„ Zdd„ Zdd „ Zd3d"d#„Zd4d$d%„Zd5d&d'„Zd6d(d)„Zd*d+„ Zd7d-d.„Z‡  ZS )8ÚRichJupyterWidgetz² An JupyterWidget that supports rich text, including lists, images, and
        tables. Note that raw performance will be reduced compared to the plain
        text version.
    z0ipykernel.pylab.backend_payload.add_plot_payloadFc                s>   d|d< t t| ƒj||Ž | j| j_i | _dtj 	¡ k| _
dS )z% Create a RichJupyterWidget.
        ZrichZkindZjpegN)Úsuperr   Ú__init__Ú_get_image_tagZ_html_exporterZ	image_tagÚ_name_to_svg_mapr   ZQImageReaderZsupportedImageFormatsÚ_jpg_supported)ÚselfÚargsÚkw)Ú	__class__r   r   r   1   s
    
zRichJupyterWidget.__init__c                s   d| _ tt| ƒ ¡  dS )zª Shows a dialog to export HTML/XML in various formats.

        Overridden in order to reset the _svg_warning_displayed flag prior
        to the export running.
        FN)Ú_svg_warning_displayedr   r   Úexport_html)r   )r   r   r   r!   G   s    zRichJupyterWidget.export_htmlc                s¼   ˆj  |¡ ¡ }| tjj¡‰ ˆ r¨t ¡ }| d‡ ‡fdd„¡ | d‡ ‡fdd„¡ | 	¡  ˆj
 ˆ d¡‰ˆdk	r¸| 	¡  | d‡fdd„¡ | d	‡‡fd
d„¡ nttˆƒ |¡}|S )zC Reimplemented to return a custom context menu for images.
        z
Copy Imagec                  s
   ˆ  ˆ ¡S )N)Ú_copy_imager   )Únamer   r   r   Ú<lambda>]   s    z6RichJupyterWidget._context_menu_make.<locals>.<lambda>zSave Image As...c                  s
   ˆ  ˆ ¡S )N)Ú_save_imager   )r#   r   r   r   r$   ^   s    NzCopy SVGc                  s   t ˆ ƒS )N)r	   r   )Úsvgr   r   r$   d   s    zSave SVG As...c                  s   t ˆˆ jƒS )N)r   Ú_controlr   )r   r&   r   r   r$   f   s    )r'   ZcursorForPositionZ
charFormatZstringPropertyr   ZQTextFormatZ	ImageNameZQMenuZ	addActionZaddSeparatorr   Úgetr   r   Ú_context_menu_make)r   ÚposÚformatZmenu)r   )r#   r   r&   r   r)   U   s    z$RichJupyterWidget._context_menu_makec             C   s0   |   | jd¡ |  |  |¡d¡ |   dd¡ dS )ztAppend the Out[] prompt  and make the output nicer

        Shared code for some the following if statement
        TÚ
N)Z_append_plain_textZ
output_sepÚ_append_htmlZ_make_out_prompt)r   ÚmsgÚprompt_numberr   r   r   Ú_pre_image_appendn   s    z#RichJupyterWidget._pre_image_appendc                s   | j  d| dd¡¡ |  |¡rœ|  ¡  |d }| dd¡}|d }|d d }d|krˆ|  ||¡ |  |d d	¡ |  | jd	¡ nd
|krÖ|  ||¡ t	|d
  
d¡ƒ}| j|d	| d
d¡d |  | jd	¡ nÆd|kr.| jr.|  ||¡ t	|d  
d¡ƒ}| j|d	| dd¡d |  | jd	¡ nnd|krŒ|  ||¡ y|  |d d	¡ W n" tk
rz   tt| ƒ |¡S X |  | jd	¡ ntt| ƒ |¡S dS )z/Overridden to handle rich data types, like SVG.zexecute_result: %sÚcontentÚ Zexecution_countr   ÚdataÚmetadatazimage/svg+xmlTz	image/pngÚasciiN)r4   z
image/jpegz
text/latex)ÚlogÚdebugr(   Úinclude_outputÚflush_clearoutputr0   Ú_append_svgr-   Zoutput_sep2r   ÚencodeÚ_append_pngr   Ú_append_jpgÚ_append_latexr   r   r   Ú_handle_display_dataÚ_handle_execute_result)r   r.   r1   r/   r3   r4   ÚpngÚjpg)r   r   r   r@   w   s>    


z(RichJupyterWidget._handle_execute_resultc                sB  | j  d| dd¡¡ |  |¡r>|  ¡  |d d }|d d }| j  d| dd¡¡ d|krv|d }|  |d¡ nÈd	|krªt|d	  d
¡ƒ}| j|d| d	d¡d n”d|krä| j	rät|d  d
¡ƒ}| j
|d| dd¡d nZd|kr.tr.y|  |d d¡ W n" tk
r*   tt| ƒ |¡S X ntt| ƒ |¡S dS )z/Overridden to handle rich data types, like SVG.zdisplay_data: %sr1   r2   r3   r4   zdisplay: %szimage/svg+xmlTz	image/pngr5   N)r4   z
image/jpegz
text/latex)r6   r7   r(   r8   r9   r:   r   r;   r<   r   r=   r   r>   r   r   r   r?   )r   r.   r3   r4   r&   rA   rB   )r   r   r   r?   ›   s*    z&RichJupyterWidget._handle_display_datac             C   s¨   ddg}ddddddg}d	d
„ |D ƒ}|| | }dd
„ |D ƒ}ddddg}xV|| D ]J\}}	|t |ƒt |	ƒ … }
||
ks„|	|
krˆdS | |¡rV| |	¡rVdS qVW dS )zs
        Determine if a Latex string is in math mode

        This is the only mode supported by qtconsole
        ZmathZdisplaymathZequationZeqnarraymultlineZgatherZalignZflalignZalignatc             S   s   g | ]}|d  ‘qS )Ú*r   )Ú.0Úenvr   r   r   ú
<listcomp>Å   s    z4RichJupyterWidget._is_latex_math.<locals>.<listcomp>c             S   s   g | ]}d   |¡ ¡ ‘qS )z\begin{{{0}}} \end{{{0}}})r+   Úsplit)rD   rE   r   r   r   rF   È   s    )z\[z\])z\(z\))z$$z$$)ú$rH   FT)ÚlenÚ
startswithÚendswith)r   ÚlatexZ
basic_envsZstarable_envsZ	star_envsZenvsZ
env_syntaxZmath_syntaxÚstartÚendÚinnerr   r   r   Ú_is_latex_math¼   s    z RichJupyterWidget._is_latex_mathNc             C   s|   d}|   |¡rt|ddd}|dkr`| d¡r`| d¡r`yt|ddd}W n tk
r^   Y nX |rt|  |||¡ nt‚dS )z! Append latex data to the widget.NFZdvipng)ZwrapZbackendrH   Z
matplotlib)rP   r   rJ   rK   Ú	Exceptionr<   r   )r   rL   Úbefore_promptr4   rA   r   r   r   r>   ×   s    
zRichJupyterWidget._append_latexc             C   s   | j | j|||d dS )z# Append raw JPG data to the widget.)r4   N)Ú_append_customÚ_insert_jpg)r   rB   rR   r4   r   r   r   r=   ì   s    zRichJupyterWidget._append_jpgc             C   s   | j | j|||d dS )z, Append raw PNG data to the widget.
        )r4   N)rS   Ú_insert_png)r   rA   rR   r4   r   r   r   r<   ð   s    zRichJupyterWidget._append_pngc             C   s   |   | j||¡ dS )z, Append raw SVG data to the widget.
        N)rS   Ú_insert_svg)r   r&   rR   r   r   r   r:   õ   s    zRichJupyterWidget._append_svgc             C   sD   | j  ¡ }t| ¡ ƒ}| tjjt 	|¡|¡ t 
¡ }| |¡ |S )zr Adds the specified QImage to the document and returns a
            QTextImageFormat that references it.
        )r'   ÚdocumentÚstrZcacheKeyZaddResourcer   ÚQTextDocumentÚImageResourcer   ÚQUrlZQTextImageFormatZsetName)r   ÚimagerW   r#   r+   r   r   r   Ú
_add_imageú   s    


zRichJupyterWidget._add_imagec             C   s   |   |¡}tj ¡  |¡ dS )z@ Copies the ImageResource with 'name' to the clipboard.
        N)Ú
_get_imager   ZQApplicationZ	clipboardZsetImage)r   r#   r\   r   r   r   r"     s    
zRichJupyterWidget._copy_imagec             C   s$   | j  ¡ }| tjjt |¡¡}|S )zE Returns the QImage stored as the ImageResource with 'name'.
        )r'   rW   Úresourcer   rY   rZ   r   r[   )r   r#   rW   r\   r   r   r   r^     s    

zRichJupyterWidget._get_imagerA   c       
   	   C   sx  |dkrîy|   | d¡¡}W n tk
r:   d| d¡ S X |dk	rŽt|ƒ tj |¡}| d|| d¡|f d¡rˆd|| d¡|f S dS n^t 	¡ }t 
|¡}| tjj¡ | || ¡ ¡ | ¡  d	|t d
dt| ¡  ¡  ¡ ƒ¡f S n†|dkrpyt| j| d¡ ƒ}W n: tk
rJ   | jsFtj | ddtjj¡ d| _dS X | d¡}	|	dksdt‚||	d… S dS dS )ag   Return (X)HTML mark-up for the image-tag given by match.

        Parameters
        ----------
        match : re.SRE_Match
            A match to an HTML image tag as exported by Qt, with
            match.group("Name") containing the matched image ID.

        path : string|None, optional [default None]
            If not None, specifies a path to which supporting files may be
            written (e.g., for linked images).  If None, all images are to be
            included inline.

        format : "png"|"svg"|"jpg", optional [default "png"]
            Format for returned or referenced images.
        )rA   rB   r#   z<b>Couldn't find image %s</b>Nz%s/qt_img%s.%sÚPNGz<img src="%s/qt_img%s.%s">z<b>Couldn't save image!</b>z'<img src="data:image/%s;base64,
%s
" />z(.{60})z\1\nr&   zError converting PNG to SVG.zÔCannot convert PNG images to SVG, export with PNG figures instead. If you want to export matplotlib figures as SVG, add to your ipython config:

	c.InlineBackend.figure_format = 'svg'

And regenerate the figures.Tzë<b>Cannot convert  PNG images to SVG.</b>  You must export this session with PNG images. If you want to export matplotlib figures as SVG, add to your config <span>c.InlineBackend.figure_format = 'svg'</span> and regenerate the figures.z<svgéÿÿÿÿz <b>Unrecognized image format</b>)r^   ÚgroupÚKeyErrorr   ÚosÚpathÚbasenameÚsaver   Z
QByteArrayZQBufferÚopenZ	QIODeviceZ	WriteOnlyÚupperÚcloseÚreÚsubrX   ZtoBase64r3   Údecoder   r    r   ZQMessageBoxZwarningZOkÚfindÚAssertionError)
r   Úmatchre   r+   r\   ÚrelpathZbaZbuffer_r&   Úoffsetr   r   r   r     sD    
&



z RichJupyterWidget._get_image_tagc             C   s   | j ||d|d dS )z% Insert raw PNG data into the widget.rB   )r4   N)Ú_insert_img)r   ÚcursorrB   r4   r   r   r   rT   ]  s    zRichJupyterWidget._insert_jpgc             C   s   | j ||d|d dS )z. Insert raw PNG data into the widget.
        rA   )r4   N)rs   )r   rt   rA   r4   r   r   r   rU   a  s    zRichJupyterWidget._insert_pngc       	      C   sä   |r|  dd¡}|  dd¡}nd }}ypt ¡ }| || ¡ ¡ |rb|rb| ||tjjtjj	¡}n2|r||s|| 
|tjj	¡}n|r”|s”| |tjj	¡}W n$ tk
rº   |  |d| ¡ Y n&X |  |¡}| ¡  | |¡ | ¡  dS )z  insert a raw image, jpg or png ÚwidthNÚheightzReceived invalid %s data.)r(   r   ZQImageZloadFromDatari   Zscaledr   ZQtZIgnoreAspectRatioZSmoothTransformationZscaledToWidthZscaledToHeightÚ
ValueErrorÚ_insert_plain_textr]   ÚinsertBlockÚinsertImage)	r   rt   ZimgZfmtr4   ru   rv   r\   r+   r   r   r   rs   f  s*    

zRichJupyterWidget._insert_imgc             C   sd   yt |ƒ}W n  tk
r,   |  |d¡ Y n4X |  |¡}|| j| ¡ < | ¡  | |¡ | ¡  dS )z- Insert raw SVG data into the widet.
        zReceived invalid SVG data.N)r
   rw   rx   r]   r   r#   ry   rz   )r   rt   r&   r\   r+   r   r   r   rV   €  s    

zRichJupyterWidget._insert_svgr`   c             C   sn   t  | jd¡}| t jj¡ | | ¡ ¡ | d|| ¡ f ¡ | ¡ rj| 	¡ d }|  
|¡}| ||¡ dS )z@ Shows a save dialog for the ImageResource with 'name'.
        z
Save Imagez%s file (*.%s)r   N)r   ZQFileDialogr'   ZsetAcceptModeZ
AcceptSaveZsetDefaultSuffixÚlowerZsetNameFilterZexec_ZselectedFilesr^   rg   )r   r#   r+   ZdialogÚfilenamer\   r   r   r   r%   Ž  s    
zRichJupyterWidget._save_image)FN)FN)FN)F)NrA   )N)N)N)r`   )r   r   r   r   Z_payload_source_plotr   r   r    r   r!   r)   r0   r@   r?   rP   r>   r=   r<   r:   r]   r"   r^   r   rT   rU   rs   rV   r%   Ú__classcell__r   r   )r   r   r      s0   	$!




I


r   c                   s    e Zd ZdZ‡ fdd„Z‡  ZS )r   z(Deprecated class. Use RichJupyterWidget.c                s    t dtƒ tt| ƒj||Ž d S )Nz6RichIPythonWidget is deprecated, use RichJupyterWidget)r   ÚDeprecationWarningr   r   r   )r   Úar   )r   r   r   r   Ÿ  s    zRichIPythonWidget.__init__)r   r   r   r   r   r}   r   r   )r   r   r     s   )Úbase64r   rd   rk   Úwarningsr   Zqtconsole.qtr   r   Zipython_genutils.pathr   Z	traitletsr   Zqtconsole.svgr   r	   r
   Zjupyter_widgetr   ZIPython.lib.latextoolsr   ÚImportErrorrQ   r   r   r   r   r   r   r   Ú<module>   s&   
   