
    
8d$F                     ,   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 	 d dlmZ n# e$ r dZY nw xY w G d de          Z G d de          Z G d de          Z G 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                       e Zd ZdZdS )
LatexErrorzException for Latex errorsN__name__
__module____qualname____doc__     =lib/python3.11/site-packages/qtconsole/rich_jupyter_widget.pyr   r      s        $$$$r   r   c                       e Zd ZdZdS )RichIPythonWidgetz4Dummy class for config inheritance. Destroyed below.Nr   r   r   r   r   r      s        >>>>r   r   c                        e Zd ZdZdZ ed          ZdZ fdZ fdZ	 fdZ
d Z fdZ fd	Zd
 Zd ZddZddZddZddZd Zd Zd ZddZddZddZddZd Zd dZ x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                     d|d<    t                      j        |i | | j        | j        _        i | _        dt          j                                        v | _	        dS )z% Create a RichJupyterWidget.
        richkindjpegN)
super__init___get_image_tag_html_exporter	image_tag_name_to_svg_mapr   QImageReadersupportedImageFormats_jpg_supported)selfargskw	__class__s      r   r%   zRichJupyterWidget.__init__3   sh     6
$%"%%% )-(;% !#
 %(:(P(P(R(RRr   c                 V    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-   r0   s    r   r3   zRichJupyterWidget.export_htmlI   s)     ',#r   c                 v     j                             |                                          }|                    t          j        j                  rt          j                   }|	                    d fd           |	                    d fd           |
                                  j                            d          G|
                                 |	                    dfd           |	                    d fd	           n!t                                          |          }|S )
zC Reimplemented to return a custom context menu for images.
        z
Copy Imagec                  .                                    S N)_copy_imagenamer-   s   r   <lambda>z6RichJupyterWidget._context_menu_make.<locals>.<lambda>_   s    1A1A$1G1G r   zSave Image As...c                  .                                    S r6   )_save_imager8   s   r   r:   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>`   s    t7G7G7M7M r   NzCopy SVGc                  "    t                     S r6   )r   )svgs   r   r:   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>f   s    3CC3H3H r   zSave SVG As...c                  .    t           j                  S r6   )r   _control)r-   r>   s   r   r:   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>h   s    xT]'C'C r   )r@   cursorForPosition
charFormatstringPropertyr   QTextFormat	ImageNamer   QMenu	addActionaddSeparatorr)   getr$   _context_menu_make)r-   posformatmenur9   r>   r0   s   `   @@r   rJ   z$RichJupyterWidget._context_menu_makeW   sE    0055@@BB$$U%6%@AA 	3?4((DNN<)G)G)G)G)GHHHNN-/M/M/M/M/MNNN'++D$77C!!###z+H+H+H+HIII/CCCCCE E E 77--c22Dr   c                     |                      | 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)_append_plain_text
output_sep_append_html_make_out_prompt)r-   msgprompt_numbers      r   _pre_image_appendz#RichJupyterWidget._pre_image_appendp   s\    
 	666$//>>EEEd+++++r   c                 P   | j                             d|                    dd                     |                     |          r_|                                  |d         }|                    dd          }|d         }|d         d         }d|v rO|                     ||           |                     |d         d	           |                     | j        d	           dS d
|v r|                     ||           t          |d
         
                    d                    }|                     |d	|                    d
d                     |                     | j        d	           dS d|v r| j        r|                     ||           t          |d         
                    d                    }|                     |d	|                    dd                     |                     | j        d	           dS d|v r|                     ||           	 |                     |d         d	           n1# t          $ r$ t!                                          |          cY S w xY w|                     | j        d	           dS t!                                          |          S dS )/Overridden to handle rich data types, like SVG.zexecute_result: %scontent execution_countr   datametadataimage/svg+xmlT	image/pngasciiNr]   
image/jpeg
text/latex)logdebugrI   include_outputflush_clearoutputrV   _append_svgrR   output_sep2r   encode_append_pngr,   _append_jpg_append_latexr   r$   _handle_display_data_handle_execute_result)	r-   rT   rY   rU   r\   r]   pngjpgr0   s	           r   ro   z(RichJupyterWidget._handle_execute_resulty   s   +SWWY-C-CDDDs## 	;""$$$)nG#KK(91==M6?D9~j1H$&&&&sM:::  o!6===!!$"2D99999$$&&sM:::[ 1 8 8 A ABB  dX\\+BF6H 6H  I I I!!$"2D99999%%$*=%&&sM:::\ 2 9 9' B BCC  dX\\,BF6H 6H  I I I!!$"2D99999%%&&sM:::=&&tL'94@@@@! = = = 7777<<<<<=!!$"2D99999 ww55c:::?	; 	;s   H7 7+I%$I%c                    | 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
                    }|                     |d|                    d	d                     dS d|v r]| j	        rVt          |d                             d
                    }| 
                    |d|                    dd                     dS d|v rWt          rP	 |                     |d         d           dS # t          $ r$ t                                          |          cY S w xY wt                                          |          S dS )rX   zdisplay_data: %srY   rZ   r\   r]   zdisplay: %sr^   Tr_   r`   Nra   rb   rc   )rd   re   rI   rf   rg   rh   r   rj   rk   r,   rl   r   rm   r   r$   rn   )r-   rT   r\   r]   r>   rp   rq   r0   s          r   rn   z&RichJupyterWidget._handle_display_data   s   )3779b+A+ABBBs## 	9""$$$y>&)D9~j1H HNN=#'')R*@*@AAA$&&?+  d+++++$$  [ 1 8 8 A ABB  dX\\+t5T5T UUUUU%%$*=%\ 2 9 9' B BCC  dX\\,PT5U5U VVVVV%%,%=&&tL'94@@@@@! = = = 7777<<<<<= ww33C8883	9 	9s   F/ /+GGc                 .   ddg}g d}d |D             }||z   |z   }d |D             }g d}||z   D ]b\  }}	|t          |          t          |	                    }
||
v s|	|
v r dS |                    |          r|                    |	          r dS cdS )	zs
        Determine if a Latex string is in math mode

        This is the only mode supported by qtconsole
        mathdisplaymath)equationeqnarraymultlinegatheralignflalignalignatc                     g | ]}|d z   S )*r   .0envs     r   
<listcomp>z4RichJupyterWidget._is_latex_math.<locals>.<listcomp>   s    8883S3Y888r   c                 \    g | ])}d                      |                                          *S )z\begin{{{0}}} \end{{{0}}})rL   splitr~   s     r   r   z4RichJupyterWidget._is_latex_math.<locals>.<listcomp>   s3    WWW3299#>>DDFFWWWr   ))z\[z\])z\(z\))$$r   )$r   FT)len
startswithendswith)r-   latex
basic_envsstarable_envs	star_envsenvs
env_syntaxmath_syntaxstartendinners              r   _is_latex_mathz RichJupyterWidget._is_latex_math   s     m,
/ / /88-888	M)I5WWRVWWW

 
 

 &
2 	 	JE3#e**c#hhY./E~~uu&& 5>>#+>+> ttur   c                     	 t          | j                  |         S # t          $ r t          d          |         cY S w xY w)z4Get color from the current syntax style if loadable.default)r   syntax_styler
   )r-   colors     r   
_get_colorzRichJupyterWidget._get_color   sS    	0d/0077 	0 	0 	0 i((////	0s    >>Nc                    d}|                      |          r&t          |dd|                     d                    }|b|                    d          rM|                    d          r8	 t          |dd|                     d                    }n# t
          $ r Y nw xY w|r|                     |||           dS t          )z! Append latex data to the widget.NFdvipngfgcolor)wrapbackendr   r   
matplotlib)r   r   r   r   r   	Exceptionrk   r   )r-   r   before_promptr]   rp   s        r   rm   zRichJupyterWidget._append_latex   s    u%% 	Au5(%)__Y%?%?A A AC ;5++C00;U^^C5H5H;"5ul)-)C)CE E E     	S-:::::s   +&B 
BBc                 B    |                      | j        |||           dS )z# Append raw JPG data to the widget.ra   N)_append_custom_insert_jpg)r-   rq   r   r]   s       r   rl   zRichJupyterWidget._append_jpg   s(    D,c=8TTTTTr   c                 B    |                      | j        |||           dS )z, Append raw PNG data to the widget.
        ra   N)r   _insert_png)r-   rp   r   r]   s       r   rk   zRichJupyterWidget._append_png   s*     	D,c=8TTTTTr   c                 >    |                      | j        ||           dS )z, Append raw SVG data to the widget.
        N)r   _insert_svg)r-   r>   r   s      r   rh   zRichJupyterWidget._append_svg  s%     	D,c=AAAAAr   c                 :   | j                                         }t          |                                          }|                    t
          j        j        t          j	        |          |           t          j
                    }|                    |           |S )zr Adds the specified QImage to the document and returns a
            QTextImageFormat that references it.
        )r@   documentstrcacheKeyaddResourcer   QTextDocumentImageResourcer   QUrlQTextImageFormatsetName)r-   imager   r9   rL   s        r   
_add_imagezRichJupyterWidget._add_image  s     =))++5>>##$$U0>#[..	7 	7 	7'))tr   c                     |                      |          }t          j                                                            |           dS )z@ Copies the ImageResource with 'name' to the clipboard.
        N)
_get_imager   QApplication	clipboardsetImage)r-   r9   r   s      r   r7   zRichJupyterWidget._copy_image  s>     %%((**33E:::::r   c                     | j                                         }|                    t          j        j        t          j        |                    }|S )zE Returns the QImage stored as the ImageResource with 'name'.
        )r@   r   resourcer   r   r   r   r   )r-   r9   r   r   s       r   r   zRichJupyterWidget._get_image  sF     =))++!!%"5"C"(+d"3"35 5r   rp   c                    |dv r	 |                      |                    d                    }n(# t          $ r d|                    d          z  cY S w xY w|t          |           t          j                            |          }|                    |d|                    d          d|d          rd|d|                    d          d|d	S d
S t          j	                    }t          j
        |          }|                    t          j        j                   |                    ||                                           |                                 d|dt!          j        ddt%          |                                                                                                                    dS |dk    r	 t%          | j        |                    d                             }nP# t          $ rC | j        s8t0          j                            | ddt0          j        j                   d| _        Y dS w xY 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.
        )rp   rq   r9   z<b>Couldn't find image %s</b>Nz/qt_img.PNGz
<img src="z">z<b>Couldn't save image!</b>z<img src="data:image/z	;base64,
z(.{60})z\1\nz
" />r>   zError converting PNG to SVG.zCannot 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<svgz <b>Unrecognized image format</b>)r   groupKeyErrorr   ospathbasenamesaver   
QByteArrayQBufferopen	QIODevice	WriteOnlyuppercloseresubr   toBase64r\   decoder)   r2   r   QMessageBoxwarningOkfind)
r-   matchr   rL   r   relpathbabuffer_r>   offsets
             r   r&   z RichJupyterWidget._get_image_tag!  s   " ]""MF(;(;<< M M M6V9L9LLLLLM !$''''**400::$$$F8K8K8K8KVVT#% % 9 9;B77<AKK<O<O<O<OPVPVPVX X 98&(( .,,V-7888

7FLLNN333FF26*Wc"++--:L:L:N:N:U:U:W:W6X6XYYYY[ [ u__7$/F0C0CDEE 7 7 72 7)11$8V6
 /8.C.FH H H 37D/6 6 67* XXf%%FB;;;;vww< 65s"   (0 "AA-G6 6A	IIc                 8    |                      ||d|           dS )z% Insert raw PNG data into the widget.rq   ra   N_insert_img)r-   cursorrq   r]   s       r   r   zRichJupyterWidget._insert_jpgj  s%    eh?????r   c                 8    |                      ||d|           dS )z. Insert raw PNG data into the widget.
        rp   ra   Nr   )r-   r   rp   r]   s       r   r   zRichJupyterWidget._insert_pngn  s'     	eh?????r   c                 `   |r-|                     dd          }|                     dd          }ndx}}	 t          j                    }|                    ||                                           |rS|rQ|                    t          |          t          |          t          j        j	        t          j        j
                  }nm|r5|s3|                    t          |          t          j        j
                  }n6|r4|s2|                    t          |          t          j        j
                  }|                     |          }|                                 |                    |           |                                 dS # t           $ r |                     |d|z             Y dS w xY w)z  insert a raw image, jpg or png widthNheightzReceived invalid %s data.)rI   r   QImageloadFromDatar   scaledintr   QtIgnoreAspectRatioSmoothTransformationscaledToWidthscaledToHeightr   insertBlockinsertImage
ValueError_insert_plain_text)	r-   r   imgfmtr]   r   r   r   rL   s	            r   r   zRichJupyterWidget._insert_imgs  s    	"LL$//E\\(D11FF!!EF	!LNNEsCIIKK000 Z ZSZZV%+Y%@%+Y%CE E  Zv Z++CJJ	8VWW Z Z,,S[[&):XYY __U++F   v&&&       	M 	M 	M##F,G,KLLLLLL	Ms   C=F #F-,F-c                 P   	 t          |          }|                     |          }|| j        |                                <   |                                 |                    |           |                                 dS # t          $ r |                     |d           Y dS w xY w)z- Insert raw SVG data into the widet.
        zReceived invalid SVG data.N)r   r   r)   r9   r   r   r   r   )r-   r   r>   r   rL   s        r   r   zRichJupyterWidget._insert_svg  s    		! %%E __U++F36D!&++--0   v&&&       	J 	J 	J##F,HIIIIII	Js   B  B%$B%r   c                    t          j        | j        d          }|                    t           j        j                   |                    |                                           |                    |d|                                d           |                                rG|	                                d         }| 
                    |          }|                    ||           dS dS )z@ Shows a save dialog for the ImageResource with 'name'.
        z
Save Imagez	 file (*.)r   N)r   QFileDialogr@   setAcceptMode
AcceptSavesetDefaultSuffixlowersetNameFilterexec_selectedFilesr   r   )r-   r9   rL   dialogfilenamer   s         r   r<   zRichJupyterWidget._save_image  s     &t}lCCY2=>>>///HIII<<>> 	)++--a0HOOD))EJJx(((((	) 	)r   )FN)F)Nrp   r6   )r   )r   r   r   r   _payload_source_plotr	   r,   r2   r%   r3   rJ   rV   ro   rn   r   r   rm   rl   rk   rh   r   r7   r   r&   r   r   r   r   r<   __classcell__r0   s   @r   r   r   !   s         NT%[[N #S S S S S,        2, , ,"; "; "; "; ";H9 9 9 9 9B  60 0 0   .U U U UU U U U
B B B B

 
 
; ; ;  G6 G6 G6 G6R@ @ @ @@ @ @ @
! ! ! !4! ! !
) 
) 
) 
) 
) 
) 
) 
)r   r   c                   "     e Zd ZdZ fdZ xZS )r   z(Deprecated class. Use RichJupyterWidget.c                 d    t          dt                      t                      j        |i | d S )Nz6RichIPythonWidget is deprecated, use RichJupyterWidget)r   DeprecationWarningr$   r%   )r-   ar/   r0   s      r   r%   zRichIPythonWidget.__init__  s=    E	! 	! 	!!"r"""""r   )r   r   r   r   r%   r   r   s   @r   r   r     s>        22# # # # # # # # #r   )base64r   r   r   warningsr   qtpyr   r   r   ipython_genutils.pathr   	traitletsr	   pygments.utilr
   qtconsole.svgr   r   r   jupyter_widgetr   stylesr   IPython.lib.latextoolsr   ImportErrorr   r   r   r   r   r   r   <module>r     s         				 				       ) ) ) ) ) ) ) ) ) ) 3 3 3 3 3 3       ' ' ' ' ' ' B B B B B B B B B B ) ) ) ) ) )      3333333   LLL% % % % % % % %? ? ? ? ? ? ? ?D) D) D) D) D)) D) D) D)R# # # # #) # # # # #s   A AA