a
    œòJbF  ã                   @   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m	Z	 d dl
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 d	dlmZ zd dlmZ W n ey²   dZY n0 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Ú	QtWidgets)Úensure_dir_exists)ÚBool)ÚClassNotFound)Úsave_svgÚsvg_to_clipboardÚsvg_to_imageé   )ÚJupyterWidget)Ú
get_colors)Ú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.9/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.Nr   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„ Zd1dd„Zd2dd„Zd3dd„Zd4dd„Zdd„ Zdd „ Zd!d"„ Zd5d$d%„Zd6d&d'„Zd7d(d)„Zd8d*d+„Zd,d-„ Zd9d/d0„Z‡  ZS ):Ú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 ƒ j|i |¤Ž | j| j_i | _dtj ¡ v | _	dS )z% Create a RichJupyterWidget.
        ZrichÚkindZjpegN)
ÚsuperÚ__init__Ú_get_image_tagZ_html_exporterZ	image_tagÚ_name_to_svg_mapr   ZQImageReaderZsupportedImageFormatsÚ_jpg_supported)ÚselfÚargsÚkw©Ú	__class__r   r   r   3   s
    
zRichJupyterWidget.__init__c                    s   d| _ 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   Úexport_html)r!   r$   r   r   r'   I   s    zRichJupyterWidget.export_htmlc                    sº   ˆj  |¡ ¡ }| tjj¡‰ ˆ rªt ˆ¡}| 	d‡ ‡fdd„¡ | 	d‡ ‡fdd„¡ | 
¡  ˆj ˆ d¡‰ˆdur¶| 
¡  | 	d‡fdd„¡ | 	d	‡‡fd
d„¡ ntƒ  |¡}|S )zC Reimplemented to return a custom context menu for images.
        z
Copy Imagec                      s
   ˆ  ˆ ¡S ©N)Ú_copy_imager   ©Únamer!   r   r   Ú<lambda>_   ó    z6RichJupyterWidget._context_menu_make.<locals>.<lambda>zSave Image As...c                      s
   ˆ  ˆ ¡S r(   )Ú_save_imager   r*   r   r   r,   `   r-   NzCopy SVGc                      s   t ˆ ƒS r(   )r   r   )Úsvgr   r   r,   f   r-   zSave SVG As...c                      s   t ˆˆ jƒS r(   )r
   Ú_controlr   )r!   r/   r   r   r,   h   r-   )r0   ZcursorForPositionZ
charFormatZstringPropertyr   ZQTextFormatZ	ImageNamer   ZQMenuZ	addActionZaddSeparatorr   Úgetr   Ú_context_menu_make)r!   ÚposÚformatZmenur$   )r+   r!   r/   r   r2   W   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_appendp   s    z#RichJupyterWidget._pre_image_appendc                    sš  | j  d| dd¡¡ |  |¡r–|  ¡  |d }| dd¡}|d }|d d }d|v rˆ|  ||¡ |  |d d	¡ |  | jd	¡ nd
|v rÖ|  ||¡ t	|d
  
d¡ƒ}| j|d	| d
d¡d |  | jd	¡ nÀd|v r.| jr.|  ||¡ t	|d  
d¡ƒ}| j|d	| dd¡d |  | jd	¡ nhd|v rŠ|  ||¡ z|  |d d	¡ W n  tyx   tƒ  |¡ Y S 0 |  | jd	¡ ntƒ  |¡S dS )ú/Overridden to handle rich data types, like SVG.zexecute_result: %sÚcontentÚ Zexecution_countr   ÚdataÚmetadataúimage/svg+xmlTú	image/pngÚasciiN©r>   ú
image/jpegú
text/latex)ÚlogÚdebugr1   Úinclude_outputÚflush_clearoutputr9   Ú_append_svgr6   Zoutput_sep2r   ÚencodeÚ_append_pngr    Ú_append_jpgÚ_append_latexr   r   Ú_handle_display_dataÚ_handle_execute_result)r!   r7   r;   r8   r=   r>   ÚpngÚjpgr$   r   r   rO   y   sB    ÿÿ
z(RichJupyterWidget._handle_execute_resultc                    s<  | j  d| dd¡¡ |  |¡r8|  ¡  |d d }|d d }| j  d| dd¡¡ d|v rv|d }|  |d¡ nÂd	|v rªt|d	  d
¡ƒ}| j|d| d	d¡d nŽd|v rä| j	rät|d  d
¡ƒ}| j
|d| dd¡d nTd|v r,tr,z|  |d d¡ W n  ty(   tƒ  |¡ Y S 0 ntƒ  |¡S dS )r:   zdisplay_data: %sr;   r<   r=   r>   zdisplay: %sr?   Tr@   rA   NrB   rC   rD   )rE   rF   r1   rG   rH   rI   r   rJ   rK   r    rL   r   rM   r   r   rN   )r!   r7   r=   r>   r/   rP   rQ   r$   r   r   rN      s*    z&RichJupyterWidget._handle_display_datac                 C   sœ   ddg}g d¢}dd„ |D ƒ}|| | }dd„ |D ƒ}g d¢}|| D ]N\}}	|t |ƒt |	ƒ … }
||
v sv|	|
v r| dS | |¡rH| |	¡rH d	S qHdS )
zs
        Determine if a Latex string is in math mode

        This is the only mode supported by qtconsole
        ZmathZdisplaymath)ZequationZeqnarraymultlineZgatherZalignZflalignZalignatc                 S   s   g | ]}|d  ‘qS )Ú*r   ©Ú.0Úenvr   r   r   Ú
<listcomp>Ç   r-   z4RichJupyterWidget._is_latex_math.<locals>.<listcomp>c                 S   s   g | ]}d   |¡ ¡ ‘qS )z\begin{{{0}}} \end{{{0}}})r4   ÚsplitrS   r   r   r   rV   Ê   r-   ))z\[z\])z\(z\))ú$$rX   )ú$rY   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_mathc                 C   s4   zt | jƒ| W S  ty.   t dƒ|  Y S 0 dS )z4Get color from the current syntax style if loadable.ÚdefaultN)r   Zsyntax_styler	   )r!   Úcolorr   r   r   Ú
_get_colorÙ   s    zRichJupyterWidget._get_colorNc                 C   sŠ   d}|   |¡r$t|dd|  d¡d}|du rn| d¡rn| d¡rnzt|dd|  d¡d}W n tyl   Y n0 |r‚|  |||¡ nt‚dS )z! Append latex data to the widget.NFZdvipngZfgcolor)ÚwrapZbackendrc   rY   Z
matplotlib)ra   r   rd   r[   r\   Ú	ExceptionrK   r   )r!   r]   Úbefore_promptr>   rP   r   r   r   rM   â   s    
ÿÿ
zRichJupyterWidget._append_latexc                 C   s   | j | j|||d dS )z# Append raw JPG data to the widget.rB   N)Ú_append_customÚ_insert_jpg)r!   rQ   rg   r>   r   r   r   rL   ù   s    zRichJupyterWidget._append_jpgc                 C   s   | j | j|||d dS )z, Append raw PNG data to the widget.
        rB   N)rh   Ú_insert_png)r!   rP   rg   r>   r   r   r   rK   ý   s    zRichJupyterWidget._append_pngc                 C   s   |   | j||¡ dS )z, Append raw SVG data to the widget.
        N)rh   Ú_insert_svg)r!   r/   rg   r   r   r   rI     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.
        )r0   ÚdocumentÚstrZcacheKeyZaddResourcer   ÚQTextDocumentÚImageResourcer   ÚQUrlZQTextImageFormatÚsetName)r!   Úimagerl   r+   r4   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+   rr   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'.
        )r0   rl   Úresourcer   rn   ro   r   rp   )r!   r+   rl   rr   r   r   r   rt     s
    

ÿzRichJupyterWidget._get_imagerP   c           
   	   C   sz  |dv rðz|   | d¡¡}W n  ty<   d| d¡  Y S 0 |durt|ƒ 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rrzt| j| d¡ ƒ}W n: tyL   | jsFtj | ddtjj¡ d| _Y dS 0 | d¡}	|	dksfJ ‚||	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.
        )rP   rQ   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>)rt   ÚgroupÚKeyErrorr   ÚosÚpathÚbasenameÚsaver   Z
QByteArrayZQBufferÚopenZ	QIODeviceZ	WriteOnlyÚupperÚcloseÚreÚsubrm   ZtoBase64r=   Údecoder   r&   r   ZQMessageBoxZwarningZOkÚfind)
r!   Úmatchr{   r4   rr   ÚrelpathZbaZbuffer_r/   Úoffsetr   r   r   r   !  sL    ÿ
ÿ
ÿ

ú
z RichJupyterWidget._get_image_tagc                 C   s   | j ||d|d dS )z% Insert raw PNG data into the widget.rQ   rB   N©Ú_insert_img)r!   ÚcursorrQ   r>   r   r   r   ri   j  s    zRichJupyterWidget._insert_jpgc                 C   s   | j ||d|d dS )z. Insert raw PNG data into the widget.
        rP   rB   Nrˆ   )r!   rŠ   rP   r>   r   r   r   rj   n  s    zRichJupyterWidget._insert_pngc           	      C   sâ   |r|  dd¡}|  dd¡}nd }}zpt ¡ }| || ¡ ¡ |rb|rb| ||tjjtjj	¡}n2|r||s|| 
|tjj	¡}n|r”|s”| |tjj	¡}W n" ty¸   |  |d| ¡ Y n&0 |  |¡}| ¡  | |¡ | ¡  dS )z  insert a raw image, jpg or png ÚwidthNÚheightzReceived invalid %s data.)r1   r   ZQImageZloadFromDatar   Zscaledr   ZQtZIgnoreAspectRatioZSmoothTransformationZscaledToWidthZscaledToHeightÚ
ValueErrorÚ_insert_plain_textrs   ÚinsertBlockÚinsertImage)	r!   rŠ   ZimgZfmtr>   r‹   rŒ   rr   r4   r   r   r   r‰   s  s,    þ

zRichJupyterWidget._insert_imgc                 C   sb   zt |ƒ}W n ty*   |  |d¡ Y n40 |  |¡}|| j| ¡ < | ¡  | |¡ | ¡  dS )z- Insert raw SVG data into the widet.
        zReceived invalid SVG data.N)r   r   rŽ   rs   r   r+   r   r   )r!   rŠ   r/   rr   r4   r   r   r   rk     s    

zRichJupyterWidget._insert_svgrv   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QFileDialogr0   ZsetAcceptModeZ
AcceptSaveZsetDefaultSuffixÚlowerZsetNameFilterZexec_ZselectedFilesrt   r}   )r!   r+   r4   ZdialogÚfilenamerr   r   r   r   r.   ›  s    
zRichJupyterWidget._save_image)FN)FN)FN)F)NrP   )N)N)N)rv   )r   r   r   r   Z_payload_source_plotr   r    r&   r   r'   r2   r9   rO   rN   ra   rd   rM   rL   rK   rI   rs   r)   rt   r   ri   rj   r‰   rk   r.   Ú__classcell__r   r   r$   r   r   !   s2   	$!	




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ƒ j|i |¤Ž d S )Nz6RichIPythonWidget is deprecated, use RichJupyterWidget)r   ÚDeprecationWarningr   r   )r!   Úar#   r$   r   r   r   ¬  s    ÿzRichIPythonWidget.__init__)r   r   r   r   r   r“   r   r   r$   r   r   ª  s   )Úbase64r   rz   r   Úwarningsr   Zqtpyr   r   r   Zipython_genutils.pathr   Z	traitletsr   Zpygments.utilr	   Zqtconsole.svgr
   r   r   Zjupyter_widgetr   Zstylesr   ZIPython.lib.latextoolsr   ÚImportErrorrf   r   r   r   r   r   r   r   Ú<module>   s*   
   