o
    º¼tf.H  ã                   @   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mZmZ dd	lmZ dd
lmZ zd dlmZ W n eyS   dZY nw ddd„Z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)ÚBool)ÚClassNotFound)Úsave_svgÚsvg_to_clipboardÚsvg_to_imageé   )ÚJupyterWidget)Ú
get_colors)Úlatex_to_pngéí  c              
   C   sr   t j | ¡s+z
t j| |d W dS  ty* } z|jtjkr‚ W Y d}~dS d}~ww t j | ¡s7td|  ƒ‚dS )zòensure that a directory exists

    If it doesn't exists, try to create it and protect against a race condition
    if another process is doing the same.

    The default permissions are 755, which differ from os.makedirs default of 777.
    )ÚmodeNz %r exists but is not a directory)	ÚosÚpathÚexistsÚmakedirsÚOSErrorÚerrnoÚEEXISTÚisdirÚIOError)r   r   Úe© r   úf/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/qtconsole/rich_jupyter_widget.pyÚ_ensure_dir_exists   s   ÿ€ÿÿr   c                   @   ó   e Zd ZdZdS )Ú
LatexErrorzException for Latex errorsN©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r    )   ó    r    c                   @   r   )ÚRichIPythonWidgetz4Dummy class for config inheritance. Destroyed below.Nr!   r   r   r   r   r'   -   r&   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d1dd„Zd1dd„Zd2dd„Zdd„ Zdd „ Zd!d"„ Zd3d$d%„Zd4d&d'„Zd4d(d)„Zd4d*d+„Zd,d-„ Zd5d/d0„Z‡  ZS )6Ú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.
        Ú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,   C   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)r0   r3   r   r   r6   Y   s   zRichJupyterWidget.export_htmlc                    s¼   ˆj  |¡ ¡ }| tjj¡‰ ˆ rVt ˆ¡}| 	d‡ ‡fdd„¡ | 	d‡ ‡fdd„¡ | 
¡  ˆj ˆ d¡‰ˆdurT| 
¡  | 	d‡fdd„¡ | 	d	‡‡fd
d„¡ |S tƒ  |¡}|S )zC Reimplemented to return a custom context menu for images.
        z
Copy Imagec                      ó
   ˆ  ˆ ¡S ©N)Ú_copy_imager   ©Únamer0   r   r   Ú<lambda>o   ó   
 z6RichJupyterWidget._context_menu_make.<locals>.<lambda>zSave Image As...c                      r7   r8   )Ú_save_imager   r:   r   r   r<   p   r=   NzCopy SVGc                      s   t ˆ ƒS r8   )r
   r   )Úsvgr   r   r<   v   s    zSave SVG As...c                      s   t ˆˆ jƒS r8   )r	   Ú_controlr   )r0   r?   r   r   r<   x   s    )r@   ZcursorForPositionZ
charFormatZstringPropertyr   ZQTextFormatZ	ImageNamer   ZQMenuZ	addActionZaddSeparatorr.   Úgetr+   Ú_context_menu_make)r0   ÚposÚformatZmenur3   )r;   r0   r?   r   rB   g   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)r0   ÚmsgÚprompt_numberr   r   r   Ú_pre_image_append€   s   z#RichJupyterWidget._pre_image_appendc                    s–  | j  d| dd¡¡ |  |¡rÉ|  ¡  |d }| dd¡}|d }|d d }d|v rC|  ||¡ |  |d d	¡ |  | jd	¡ dS d
|v rk|  ||¡ t	|d
  
d¡ƒ}| j|d	| d
d¡d |  | jd	¡ dS d|v r–| jr–|  ||¡ t	|d  
d¡ƒ}| j|d	| dd¡d |  | jd	¡ dS d|v rÃ|  ||¡ z
|  |d d	¡ W n ty¹   tƒ  |¡ Y S w |  | jd	¡ dS 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©rN   ú
image/jpegú
text/latex)ÚlogÚdebugrA   Úinclude_outputÚflush_clearoutputrI   Ú_append_svgrF   Zoutput_sep2r   ÚencodeÚ_append_pngr/   Ú_append_jpgÚ_append_latexr    r+   Ú_handle_display_dataÚ_handle_execute_result)r0   rG   rK   rH   rM   rN   ÚpngÚjpgr3   r   r   r_   ‰   sF   
ÿÿÿáz(RichJupyterWidget._handle_execute_resultc                    s:  | j  d| dd¡¡ |  |¡r›|  ¡  |d d }|d d }| j  d| dd¡¡ d|v r;|d }|  |d¡ dS d	|v rVt|d	  d
¡ƒ}| j|d| d	d¡d dS d|v rt| j	rtt|d  d
¡ƒ}| j
|d| dd¡d dS d|v r•tr•z|  |d d¡ W dS  ty”   tƒ  |¡ Y S w tƒ  |¡S dS )rJ   zdisplay_data: %srK   rL   rM   rN   zdisplay: %srO   TrP   rQ   NrR   rS   rT   )rU   rV   rA   rW   rX   rY   r   rZ   r[   r/   r\   r   r]   r    r+   r^   )r0   rG   rM   rN   r?   r`   ra   r3   r   r   r^   ­   s.   
ÿçz&RichJupyterWidget._handle_display_datac                 C   sœ   ddg}g d¢}dd„ |D ƒ}|| | }dd„ |D ƒ}g d¢}|| D ]'\}}	|t |ƒt |	ƒ … }
||
v s;|	|
v r> dS | |¡rK| |	¡rK d	S q$dS )
zs
        Determine if a Latex string is in math mode

        This is the only mode supported by qtconsole
        ÚmathZdisplaymath)ZequationZeqnarraymultlineÚgatherÚ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}}})rD   Úsplitrf   r   r   r   ri   Ú   s    ))z\[z\])z\(z\))ú$$rk   )ú$rl   FT)ÚlenÚ
startswithÚendswith)r0   ÚlatexZ
basic_envsZstarable_envsZ	star_envsÚenvsZ
env_syntaxZmath_syntaxÚstartÚendÚinnerr   r   r   Ú_is_latex_mathÎ   s   €z RichJupyterWidget._is_latex_mathc                 C   s0   zt | jƒ| W S  ty   t dƒ|  Y S w )z4Get color from the current syntax style if loadable.Údefault)r   Zsyntax_styler   )r0   Úcolorr   r   r   Ú
_get_coloré   s
   ýzRichJupyterWidget._get_colorNc                 C   sˆ   d}|   |¡rt|dd|  d¡d}|du r7| d¡r7| d¡r7zt|dd|  d¡d}W n	 ty6   Y nw |rB|  |||¡ dS t‚)z! Append latex data to the widget.NFZdvipngZfgcolor)ÚwrapÚbackendrw   rl   Z
matplotlib)ru   r   rx   rn   ro   Ú	Exceptionr[   r    )r0   rp   Úbefore_promptrN   r`   r   r   r   r]   ò   s    
ÿ
ÿÿzRichJupyterWidget._append_latexc                 C   ó   | j | j|||d dS )z# Append raw JPG data to the widget.rR   N)Ú_append_customÚ_insert_jpg)r0   ra   r|   rN   r   r   r   r\   	  s   zRichJupyterWidget._append_jpgc                 C   r}   )z, Append raw PNG data to the widget.
        rR   N)r~   Ú_insert_png)r0   r`   r|   rN   r   r   r   r[     s   zRichJupyterWidget._append_pngc                 C   s   |   | j||¡ dS )z, Append raw SVG data to the widget.
        N)r~   Ú_insert_svg)r0   r?   r|   r   r   r   rY     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QTextImageFormatÚsetName)r0   Úimager‚   r;   rD   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QApplicationÚ	clipboardZsetImage)r0   r;   rˆ   r   r   r   r9   #  s   
zRichJupyterWidget._copy_imagec                 C   s$   | j  ¡ }| tjjt |¡¡}|S )zE Returns the QImage stored as the ImageResource with 'name'.
        )r@   r‚   Úresourcer   r„   r…   r   r†   )r0   r;   r‚   rˆ   r   r   r   rŠ   )  s
   

ÿzRichJupyterWidget._get_imager`   c           
   	   C   sj  |dv rvz
|   | d¡¡}W n ty   d| d¡  Y S w |durGt|ƒ tj |¡}| d|| d¡|f d¡rEd|| d¡|f S dS t 	¡ }t 
|¡}| tjj¡ | || ¡ ¡ | ¡  d	|t d
dt| ¡  ¡  ¡ ƒ¡f S |dkr³zt| j| d¡ ƒ}W n ty¡   | jsžtj | ddtjj¡ d| _Y dS w | d¡}	|	dks­J ‚||	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.
        )r`   ra   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   r   r   ÚbasenameÚsaver   Z
QByteArrayZQBufferÚopenZ	QIODeviceZ	WriteOnlyÚupperÚcloseÚreÚsubrƒ   ZtoBase64rM   Údecoder.   r5   r   ZQMessageBoxÚwarningZOkÚfind)
r0   Úmatchr   rD   rˆ   ÚrelpathÚbaZbuffer_r?   Úoffsetr   r   r   r-   1  sP   ÿÿ
ÿ
ÿ
úö
z RichJupyterWidget._get_image_tagc                 C   ó   | j ||d|d dS )z% Insert raw PNG data into the widget.ra   rR   N©Ú_insert_img)r0   Úcursorra   rN   r   r   r   r   z  s   zRichJupyterWidget._insert_jpgc                 C   rŸ   )z. Insert raw PNG data into the widget.
        r`   rR   Nr    )r0   r¢   r`   rN   r   r   r   r€   ~  s   zRichJupyterWidget._insert_pngc           	      C   sô   |r|  dd¡}|  dd¡}nd }}z@t ¡ }| || ¡ ¡ |r5|r5| t|ƒt|ƒtjj	tjj
¡}n|rD|sD| t|ƒtjj
¡}n|rR|sR| t|ƒtjj
¡}W n tye   |  |d| ¡ Y dS w |  |¡}| ¡  | |¡ | ¡  dS )z  insert a raw image, jpg or png ÚwidthNÚheightzReceived invalid %s data.)rA   r   ZQImageZloadFromDatar”   ZscaledÚintr   ZQtZIgnoreAspectRatioZSmoothTransformationZscaledToWidthZscaledToHeightÚ
ValueErrorÚ_insert_plain_textr‰   ÚinsertBlockÚinsertImage)	r0   r¢   ZimgÚfmtrN   r£   r¤   rˆ   rD   r   r   r   r¡   ƒ  s0   þ€ÿ

zRichJupyterWidget._insert_imgc                 C   sd   zt |ƒ}W n ty   |  |d¡ Y dS w |  |¡}|| j| ¡ < | ¡  | |¡ | ¡  dS )z- Insert raw SVG data into the widet.
        zReceived invalid SVG data.N)r   r¦   r§   r‰   r.   r;   r¨   r©   )r0   r¢   r?   rˆ   rD   r   r   r   r     s   ÿ

zRichJupyterWidget._insert_svgr   c                 C   sr   t  | jd¡}| t jj¡ | | ¡ ¡ | d|| ¡ f ¡ | ¡ r7| 	¡ d }|  
|¡}| ||¡ dS 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setNameFilterÚexec_ZselectedFilesrŠ   r’   )r0   r;   rD   ZdialogÚfilenamerˆ   r   r   r   r>   «  s   
ýzRichJupyterWidget._save_image)FN)F)Nr`   r8   )r   )r"   r#   r$   r%   Z_payload_source_plotr   r/   r5   r,   r6   rB   rI   r_   r^   ru   rx   r]   r\   r[   rY   r‰   r9   rŠ   r-   r   r€   r¡   r   r>   Ú__classcell__r   r   r3   r   r(   1   s4    	$!
	




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,   )r0   Úar2   r3   r   r   r,   ¼  s   ÿzRichIPythonWidget.__init__)r"   r#   r$   r%   r,   r®   r   r   r3   r   r'   º  s    )r   )Úbase64r   r   r–   Úwarningsr   Zqtpyr   r   r   Z	traitletsr   Zpygments.utilr   Zqtconsole.svgr	   r
   r   Zjupyter_widgetr   Ústylesr   ZIPython.lib.latextoolsr   ÚImportErrorr   r{   r    r'   r(   r   r   r   r   Ú<module>   s.   ÿ
   