
    [A1e.H                        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 	 d dlmZ ddZ G d de      Z G d de      Z G d de      Z G d de      Zy# e$ r dZY :w xY w)    )	b64decodeN)warn)QtCoreQtGui	QtWidgets)Bool)ClassNotFound)save_svgsvg_to_clipboardsvg_to_image   )JupyterWidget)
get_colors)latex_to_pngc                 6   t         j                  j                  |       s	 t        j                  | |       yt         j                  j                  |       st        d| z        y# t        $ r(}|j
                  t
        j                  k7  r Y d}~yd}~ww xY w)zensure 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   es      ?/usr/lib/python3/dist-packages/qtconsole/rich_jupyter_widget.py_ensure_dir_existsr      sy     77>>$	KK4( WW]]4 84?@@ !  	ww%,,& '	s   A' '	B0BBc                       e Zd ZdZy)
LatexErrorzException for Latex errorsN__name__
__module____qualname____doc__     r   r    r    )   s    $r'   r    c                       e Zd ZdZy)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        |   |i | | j                  | j                  _        i | _        dt        j                  j                         v | _	        y)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   r1   zRichJupyterWidget.__init__C   s^     6
$%"% )-(;(;% !#
 %(:(:(P(P(RRr'   c                 0    d| _         t        | 	          y)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_displayedr0   export_html)r9   r<   s    r   r?   zRichJupyterWidget.export_htmlY   s     ',#r'   c                 ,     j                   j                  |      j                         }|j                  t        j
                  j                        rt        j                         }|j                  d fd       |j                  d fd       |j                           j                  j                  d      ;|j                          |j                  dfd       |j                  d fd	       |S t         9  |      }|S )
zC Reimplemented to return a custom context menu for images.
        z
Copy Imagec                  &    j                         S N)_copy_imagenamer9   s   r   <lambda>z6RichJupyterWidget._context_menu_make.<locals>.<lambda>o   s    1A1A$1G r'   zSave Image As...c                  &    j                         S rB   )_save_imagerD   s   r   rF   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>p   s    t7G7G7M r'   NzCopy SVGc                      t               S rB   )r   )svgs   r   rF   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>v   s    3CC3H r'   zSave SVG As...c                  0    t         j                        S rB   )r
   _control)r9   rJ   s   r   rF   z6RichJupyterWidget._context_menu_make.<locals>.<lambda>x   s    xT]]'C r'   )rL   cursorForPosition
charFormatstringPropertyr   QTextFormat	ImageNamer   QMenu	addActionaddSeparatorr5   getr0   _context_menu_make)r9   posformatmenurE   rJ   r<   s   `   @@r   rV   z$RichJupyterWidget._context_menu_makeg   s     005@@B$$U%6%6%@%@A??4(DNN<)GHNN-/MN''++D$7C!!#z+HI/CE  7-c2Dr'   c                     | j                  | j                  d       | j                  | j                  |      d       | j                  dd       y)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)r9   msgprompt_numbers      r   _pre_image_appendz#RichJupyterWidget._pre_image_append   sC    
 	6$//>Ed+r'   c                 N   | j                   j                  d|j                  dd             | j                  |      r| j	                          |d   }|j                  dd      }|d   }|d   d   }d|v rD| j                  ||       | j                  |d   d	       | j                  | j                  d	       yd
|v rp| j                  ||       t        |d
   j                  d            }| j                  |d	|j                  d
d             | j                  | j                  d	       yd|v r|| j                  rp| j                  ||       t        |d   j                  d            }| j                  |d	|j                  dd             | j                  | j                  d	       yd|v rE| j                  ||       	 | j                  |d   d	       | j                  | j                  d	       yt         | I  |      S y# t        $ r t         | E  |      cY S w xY w)/Overridden to handle rich data types, like SVG.zexecute_result: %scontent execution_countr   datametadataimage/svg+xmlT	image/pngasciiNri   
image/jpeg
text/latex)logdebugrU   include_outputflush_clearoutputrb   _append_svgr^   output_sep2r   encode_append_pngr8   _append_jpg_append_latexr    r0   _handle_display_data_handle_execute_result)	r9   r`   re   ra   rh   ri   pngjpgr<   s	           r   r{   z(RichJupyterWidget._handle_execute_result   s   +SWWY-CDs#""$)nG#KK(91=M6?D9~j1H$&&&sM:  o!6=!!$"2"2D9$&&sM:[ 1 8 8 AB  dX\\+BF6H  I!!$"2"2D9%$*=*=&&sM:\ 2 9 9' BC  dX\\,BF6H  I!!$"2"2D9%&&sM:=&&tL'94@ !!$"2"2D9 w5c::? $4 " = 77<<=s   H	 	H$#H$c                    | j                   j                  d|j                  dd             | j                  |      r0| j	                          |d   d   }|d   d   }| j                   j                  d|j                  dd             d|v r|d   }| j                  |d       yd	|v rBt        |d	   j                  d
            }| j                  |d|j                  d	d             yd|v rN| j                  rBt        |d   j                  d
            }| j                  |d|j                  dd             yd|v rt        r	 | j                  |d   d       yt        | =  |      S y# t        $ r t        | =  |      cY S w xY w)rd   zdisplay_data: %sre   rf   rh   ri   zdisplay: %srj   Trk   rl   Nrm   rn   ro   )rp   rq   rU   rr   rs   rt   r   rv   rw   r8   rx   r   ry   r    r0   rz   )r9   r`   rh   ri   rJ   r|   r}   r<   s          r   rz   z&RichJupyterWidget._handle_display_data   s   )3779b+ABs#""$y>&)D9~j1H HHNN=#'')R*@A$&?+  d+$  [ 1 8 8 AB  dX\\+t5T U%$*=*=\ 2 9 9' BC  dX\\,PT5U V%,=&&tL'94@
 w3C883 $* " = 77<<=s   E1 1FFc                 d   ddg}g d}|D cg c]  }|dz   	 }}||z   |z   }|D cg c]!  }dj                  |      j                         # }}g d}||z   D ]L  \  }	}
|t        |	      t        |
        }|	|v s|
|v r y|j                  |	      s:|j	                  |
      sL y yc c}w c c}w )	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alignat*z\begin{{{0}}} \end{{{0}}}))z\[z\])z\(z\))$$r   )$r   FT)rX   splitlen
startswithendswith)r9   latex
basic_envsstarable_envsenv	star_envsenvs
env_syntaxmath_syntaxstartendinners               r   _is_latex_mathz RichJupyterWidget._is_latex_math   s     m,
/*783S3Y8	8M)I5RVW3299#>DDFW
W

 &
2 	JE3#e*c#hY/E~&5>>#+>	 ! 9 Xs
   B(&B-c                 n    	 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	   )r9   colors     r   
_get_colorzRichJupyterWidget._get_color   s>    	0d//077 	0 i(//	0s    44c                 @   d}| j                  |      rt        |dd| j                  d            }|A|j                  d      r0|j	                  d      r	 t        |dd| j                  d            }|r| j                  |||       yt        # t
        $ r Y 'w xY w)z! Append latex data to the widget.NFdvipngfgcolor)wrapbackendr   r   
matplotlib)r   r   r   r   r   	Exceptionrw   r    )r9   r   before_promptri   r|   s        r   ry   zRichJupyterWidget._append_latex   s    u%u5(%)__Y%?AC ;5++C0U^^C5H"5ul)-)CE
 S-:  s   B 	BBc                 B    | j                  | j                  |||       y)z# Append raw JPG data to the widget.rm   N)_append_custom_insert_jpg)r9   r}   r   ri   s       r   rx   zRichJupyterWidget._append_jpg	  s    D,,c=8Tr'   c                 B    | j                  | j                  |||       y)z, Append raw PNG data to the widget.
        rm   N)r   _insert_png)r9   r|   r   ri   s       r   rw   zRichJupyterWidget._append_png  s!     	D,,c=8Tr'   c                 >    | j                  | j                  ||       y)z, Append raw SVG data to the widget.
        N)r   _insert_svg)r9   rJ   r   s      r   rt   zRichJupyterWidget._append_svg  s     	D,,c=Ar'   c                 2   | j                   j                         }t        |j                               }|j	                  t
        j                  j                  t        j                  |      |       t        j                         }|j                  |       |S )zr Adds the specified QImage to the document and returns a
            QTextImageFormat that references it.
        )rL   documentstrcacheKeyaddResourcer   QTextDocumentImageResourcer   QUrlQTextImageFormatsetName)r9   imager   rE   rX   s        r   
_add_imagezRichJupyterWidget._add_image  sp     ==))+5>>#$U00>>#[[.	7'')tr'   c                     | j                  |      }t        j                  j                         j	                  |       y)z@ Copies the ImageResource with 'name' to the clipboard.
        N)
_get_imager   QApplication	clipboardsetImage)r9   rE   r   s      r   rC   zRichJupyterWidget._copy_image#  s/     %((*33E:r'   c                     | j                   j                         }|j                  t        j                  j
                  t        j                  |            }|S )zE Returns the QImage stored as the ImageResource with 'name'.
        )rL   r   resourcer   r   r   r   r   )r9   rE   r   r   s       r   r   zRichJupyterWidget._get_image)  sE     ==))+!!%"5"5"C"C"(++d"35r'   c                 j   |dv re	 | j                  |j                  d            }|ot        |       t        j
                  j                  |      }|j                  |d|j                  d      d|d      rd|d|j                  d      d|d	S y
t        j                         }t        j                  |      }|j                  t        j                  j                         |j                  ||j                                |j                          d|dt!        j"                  ddt%        |j'                         j)                         j+                                     dS |dk(  rE	 t%        | j,                  |j                  d               }|j9                  d      }	|	dkD  sJ ||	d S y# t        $ r d|j                  d      z  cY S w xY w# t        $ rP | j.                  sAt0        j2                  j5                  | ddt0        j2                  j6                         d| _        Y yw xY w)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|   r}   rE   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
" />rJ   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   r   r   basenamesaver   
QByteArrayQBufferopen	QIODevice	WriteOnlyuppercloseresubr   toBase64rh   decoder5   r>   r   QMessageBoxwarningOkfind)
r9   matchr   rX   r   relpathbabuffer_rJ   offsets
             r   r2   z RichJupyterWidget._get_image_tag1  s   " ]"MF(;< "4(''**40::$F8KVT#%;B<AKK<OPVX X 9&&( ..,V--778

7FLLN3266*Wc"++-:L:L:N:U:U:W6XY[ [ u_7$//F0CDE, XXf%FB;;vw< 6g  M6V9LLLM0  722))11$8V6
 /8.C.C.F.FH 37D/67s$    F6 1'G 6GGAH21H2c                 .    | j                  ||d|       y)z% Insert raw PNG data into the widget.r}   rm   N_insert_img)r9   cursorr}   ri   s       r   r   zRichJupyterWidget._insert_jpgz  s    eh?r'   c                 .    | j                  ||d|       y)z. Insert raw PNG data into the widget.
        r|   rm   Nr   )r9   r   r|   ri   s       r   r   zRichJupyterWidget._insert_png~  s     	eh?r'   c                 $   |r%|j                  dd      }|j                  dd      }ndx}}	 t        j                         }|j                  ||j	                                |rY|rW|j                  t        |      t        |      t        j                  j                  t        j                  j                        }no|r6|s4|j                  t        |      t        j                  j                        }n7|r5|s3|j                  t        |      t        j                  j                        }| j                  |      }|j                          |j                  |       |j                          y# t         $ r | j#                  |d|z         Y yw xY w)z  insert a raw image, jpg or png widthNheightzReceived invalid %s data.)rU   r   QImageloadFromDatar   scaledintr   QtIgnoreAspectRatioSmoothTransformationscaledToWidthscaledToHeightr   insertBlockinsertImage
ValueError_insert_plain_text)	r9   r   imgfmtri   r   r   r   rX   s	            r   r   zRichJupyterWidget._insert_img  s:   LL$/E\\(D1F!!EF	!LLNEsCIIK0SZV%+YY%@%@%+YY%C%CE v++CJ		8V8VW,,S[&)):X:XY __U+F v&   	M##F,G,KL	Ms   C>E. .FFc                    	 t        |      }| j                  |      }|| j                  |j                         <   |j	                          |j                  |       |j	                          y# t        $ r | j                  |d       Y yw xY w)z- Insert raw SVG data into the widet.
        zReceived invalid SVG data.N)r   r   r5   rE   r   r   r   r   )r9   r   rJ   r   rX   s        r   r   zRichJupyterWidget._insert_svg  s    		! %E __U+F36D!!&++-0 v&   	J##F,HI	Js   A- -B
Bc                    t        j                  | j                  d      }|j                  t         j                  j                         |j                  |j                                |j                  |d|j                         d       |j                         r7|j                         d   }| j                  |      }|j                  ||       yy)z@ Shows a save dialog for the ImageResource with 'name'.
        z
Save Imagez	 file (*.)r   N)r   QFileDialogrL   setAcceptMode
AcceptSavesetDefaultSuffixlowersetNameFilterexec_selectedFilesr   r   )r9   rE   rX   dialogfilenamer   s         r   rH   zRichJupyterWidget._save_image  s     &&t}}lCY22==>/HI<<>++-a0HOOD)EJJx( r'   )FN)F)Nr|   rB   )r   )r"   r#   r$   r%   _payload_source_plotr   r8   r>   r1   r?   rV   rb   r{   rz   r   r   ry   rx   rw   rt   r   rC   r   r2   r   r   r   r   rH   __classcell__r<   s   @r   r+   r+   1   s     N%[N #S,2,";H9B60.UU
B

;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        |   |i | y )Nz6RichIPythonWidget is deprecated, use RichJupyterWidget)r   DeprecationWarningr0   r1   )r9   ar;   r<   s      r   r1   zRichIPythonWidget.__init__  s#    E	!!"r"r'   )r"   r#   r$   r%   r1   r  r  s   @r   r)   r)     s    2# #r'   )i  )base64r   r   r   warningsr   qtpyr   r   r   	traitletsr   pygments.utilr	   qtconsole.svgr
   r   r   jupyter_widgetr   stylesr   IPython.lib.latextoolsr   ImportErrorr   r   r    r)   r+   r&   r'   r   <module>r     s     	 	  ) )  ' B B ) 3
A"% %? ?D)) D)R#) #M  Ls   A9 9BB