B
    #õå[R^  ã               @   s"  d Z ddlmZ ddlZddlZddlmZ ddlZddl	Z	ddl
mZ ddlmZ ddlmZmZ ddl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 ddlmZ ddlm Z  dZ!dZ"dZ#dZ$dZ%dZ&ej' (d¡rêdZ)ndZ)G dd„ deƒZ*G dd„ de*ƒZ+G dd„ de+ƒZ*dS )z„A FrontendWidget that emulates a repl for a Jupyter kernel.

This supports the additional functionality provided by Jupyter kernel.
é    )Ú
namedtupleN)ÚPopen)Údedent)Úwarn)ÚQtCoreÚQtGui)ÚIPythonLexerÚIPython3Lexer)Úget_lexer_by_name)ÚClassNotFound)Ú__version__)ÚBoolÚUnicodeé   )ÚFrontendWidget)Ústylesz/In [<span class="in-prompt-number">%i</span>]: z0Out[<span class="out-prompt-number">%i</span>]: Ú
Ú z&ipykernel.zmqshell.ZMQInteractiveShellÚwinZnotepadc               @   s   e Zd ZdZdS )ÚIPythonWidgetz4Dummy class for config inheritance. Destroyed below.N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   ú7lib/python3.7/site-packages/qtconsole/jupyter_widget.pyr   4   s   r   c                   s®  e Zd ZdZedƒZe ee¡Z	e
edddZe
dddZe
dddZe
dddZe
edd	Ze
edd	Ze
edd	Ze
edd	Ze
edd	Zed
dddgƒZdZdZdZdZdZ dZ!‡ fdd„Z"dd„ Z#‡ fdd„Z$dd„ Z%dd„ Z&dd„ Z'dd„ Z(d d!„ Z)‡ fd"d#„Z*d$d%„ Z+d&d'„ Z,d(d)„ Z-dJd+d,„Z.d-d.„ Z/d/d0„ Z0dKd2d3„Z1dLd4d5„Z2dMd6d7„Z3dNd8d9„Z4dOd:d;„Z5d<d=„ Z6d>d?„ Z7d@dA„ Z8dBdC„ Z9dDdE„ Z:dFdG„ Z;dHdI„ Z<‡  Z=S )PÚJupyterWidgetz&A FrontendWidget for a Jupyter kernel.FTaN  
        A command for invoking a GUI text editor. If the string contains a
        {filename} format specifier, it will be used. Otherwise, the filename
        will be appended to the end the command. To use a terminal text editor,
        the command should launch a new terminal, e.g.
        ``"gnome-terminal -- vim"``.
        )ÚconfigÚhelpa  
        The editor command to use when a specific line number is requested. The
        string should contain two format specifiers: {line} and {filename}. If
        this parameter is not specified, the line number option to the %edit
        magic will be ignored.
        a  
        A CSS stylesheet. The stylesheet can contain classes for:
            1. Qt: QPlainTextEdit, QFrame, QWidget, etc
            2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
            3. QtConsole: .error, .in-prompt, .out-prompt, etc
        z¦
        If not empty, use this Pygments style for syntax highlighting.
        Otherwise, the style sheet is queried for Pygments style
        information.
        )r   Ú_PromptBlockÚblockÚlengthÚnumberZ
edit_magicZask_exitZset_next_inputZpagec                sh   t t| ƒj||Ž | j| j| j| j| j| j| j	| j
i| _d | _d | _| jr\|  ¡  |  ¡  n|  ¡  d S )N)Úsuperr   Ú__init__Ú_payload_source_editÚ_handle_payload_editÚ_payload_source_exitÚ_handle_payload_exitÚ_payload_source_pageÚ_handle_payload_pageÚ_payload_source_next_inputÚ_handle_payload_next_inputÚ_payload_handlersÚ_previous_prompt_objÚ_keep_kernel_on_exitÚstyle_sheetÚ_style_sheet_changedÚ_syntax_style_changedÚset_default_style)ÚselfÚargsÚkw)Ú	__class__r   r   r$   u   s    
zJupyterWidget.__init__c       
      C   sþ   | j  d| dd¡¡ |  ¡ }| j d¡}|rú|j|d d krú|j| ¡ krú|d }|d }|d }|d	 }t|d
ƒ}t||ƒ}|  	¡ }||k rª|j
tjj|| d n||krÈ|j
tjj|| d | j |¡ || }	|j
tjj|	d |  ||¡ dS )z9Support Jupyter's improved completion machinery.
        zcomplete: %sÚcontentr   ZcompleteÚparent_headerÚmsg_idÚmatchesZcursor_startZ
cursor_endr   )ÚnN)ÚlogÚdebugÚgetZ_get_cursorÚ_request_infoÚidÚposÚpositionÚmaxZ_get_input_buffer_cursor_posÚmovePositionr   ÚQTextCursorZLeftÚRightÚ_controlZsetTextCursorZ_complete_with_items)
r4   ÚrepÚcursorÚinfor8   r;   ÚstartÚendZ
cursor_posÚoffsetr   r   r   Ú_handle_complete_reply   s,    



z$JupyterWidget._handle_complete_replyc                s†   |d   d¡}| jd   |¡}|rr|jdkrr|d }|d dkrJ|  ¡  n|d d	 }|  |¡ | jd  |¡ ntt| ƒ |¡ d
S )z!Support prompt requests.
        r9   r:   ÚexecuteÚpromptr8   ÚstatusÚabortedÚexecution_countr   N)r?   r@   ÚkindÚ_show_interpreter_promptÚpopr#   r   Ú_handle_execute_reply)r4   Úmsgr:   rK   r8   r"   )r7   r   r   rX   °   s    

z#JupyterWidget._handle_execute_replyc             C   sÖ   |d }d|krn| j  d| ¡ | dd¡dkrd| jsd| j  d¡ d| _t d	¡ | jjd
dd nd| _dS d| _|d }| j  dt	|ƒ¡ g }d}x0|D ](\}}}| 
¡ }||krœ| |¡ |}qœW |  |¡ dS )z_ Handle history tail replies, which are only supported
            by Jupyter kernels.
        r8   ÚhistoryzHistory request failed: %rrR   r   rS   z Retrying aborted history requestTg      Ð?Útailiè  )Úhist_access_typer<   FNz&Received history reply with %i entries)r=   Úerrorr?   Ú_retrying_history_requestÚtimeZsleepÚkernel_clientrZ   r>   ÚlenÚrstripÚappendZ_set_history)r4   rY   r8   Zhistory_itemsÚitemsZ	last_cellÚ_Zcellr   r   r   Ú_handle_history_replyÀ   s,    

z#JupyterWidget._handle_history_replyc             C   sœ   |  dd¡}| j|dd}| j| jdd}| d¡ xTt|d  ¡  d¡ƒD ]:\}}|dkrj|  ||¡ n|  ||¡ |  	||d ¡ qLW |  
|d ¡ dS )	z.Insert function for input from other frontendsrT   r   T)Úremoter   Úcoder   N)r?   Ú_make_in_promptÚ_make_continuation_promptÚ_promptZ
insertTextÚ	enumerateÚstripÚsplitZ_insert_htmlZ_insert_plain_textÚ_update_prompt)r4   rJ   r8   r<   rQ   Zcont_promptÚiÚliner   r   r   Ú_insert_other_inputá   s    
 z!JupyterWidget._insert_other_inputc             C   s:   | j  d| dd¡¡ |  |¡r6| j| j|d dd dS )zHandle an execute_input messagezexecute_input: %sr8   r   T)Úbefore_promptN)r=   r>   r?   Úinclude_outputZ_append_customrr   )r4   rY   r   r   r   Ú_handle_execute_inputñ   s    
z#JupyterWidget._handle_execute_inputc             C   sÖ   | j  d| dd¡¡ |  |¡rÒ|  ¡  |d }| dd¡}|d }d|krÒ| j| jdd	 | j| j||  	|¡ d
dd	 |d }d|kr¦| j 
d¡s¦| jddd	 | j|| j dd	 |  	|¡sÒ| jddd	 dS )z Handle an execute_result messagezexecute_result: %sr8   r   rT   r   Údataz
text/plainT)rs   )rg   r   N)r=   r>   r?   rt   Úflush_clearoutputÚ_append_plain_textÚ
output_sepZ_append_htmlÚ_make_out_promptÚ	from_hereÚendswithÚoutput_sep2)r4   rY   r8   Zprompt_numberrv   Útextr   r   r   Ú_handle_execute_result÷   s"    

z$JupyterWidget._handle_execute_resultc             C   sV   |   |¡rR|  ¡  |d d }|d d }d|krF|d }|  |d¡ |  dd¡ dS )z2The base handler for the ``display_data`` message.r8   rv   Úmetadataz
text/plainTr   N)rt   rw   rx   )r4   rY   rv   r€   r~   r   r   r   Ú_handle_display_data  s    
z"JupyterWidget._handle_display_datac                sš   |d }|d d }|d   dd¡}y4|dkr6tƒ }n|dkrFtƒ }nt|ƒ}|| j_W n tk
rl   Y nX |  dd¡| _| jr–d	| _t	t
| ƒ ¡  d
S )zHandle kernel info replies.r8   Zlanguage_infoÚnameÚpygments_lexerr   Zipython3Zipython2ZbannerFN)r?   r	   r   r
   Ú_highlighterZ_lexerr   Zkernel_bannerÚ	_startingr#   r   Ú_started_channels)r4   rI   r8   Zlanguage_namerƒ   Zlexer)r7   r   r   Ú_handle_kernel_info_reply   s     z'JupyterWidget._handle_kernel_info_replyc             C   s$   d| _ | j ¡  | jjddd dS )zMake a history requestTr[   iè  )r\   r<   N)r…   r`   Zkernel_inforZ   )r4   r   r   r   r†   9  s    
zJupyterWidget._started_channelsc             C   sJ   | j  d| dd¡¡ |d }d |d ¡d }| j||  |¡ d dS )zHandle an execute_error messagezexecute_error: %sr8   r   r   Ú	traceback)rs   N)r=   r>   r?   Újoinrx   r{   )r4   rY   r8   rˆ   r   r   r   Ú_process_execute_errorD  s    z$JupyterWidget._process_execute_errorc             C   s,   | j  |d ¡}|dkrdS ||ƒ dS dS )z@ Reimplemented to dispatch payloads to handler methods.
        ÚsourceNFT)r-   r?   )r4   ÚitemZhandlerr   r   r   Ú_process_execute_payload]  s
    z&JupyterWidget._process_execute_payloadNc             C   s”   |dkr6| j jddd}|  |d¡}|| jd |< dS | j| _| j|  |¡dd | j 	¡  
¡ }t| jƒ}|  |||¡| _| j|  | j¡dd dS )z2 Reimplemented for IPython-style prompts.
        Nr   T)ZsilentrQ   rP   )Úhtml)r`   rP   Z_ExecutionRequestr@   Ú	input_sepZ_prompt_sepZ_show_promptri   rH   ÚdocumentZ	lastBlockra   rk   r   r.   Z_set_continuation_promptrj   )r4   r"   r:   rK   r    r!   r   r   r   rV   h  s    
z&JupyterWidget._show_interpreter_promptc             C   s|   | j j}| ¡ rx| ¡ rxt |¡}| tjjtjj| j j	¡ |  
|¡}|  ||¡| _| j | ¡ ¡ | j | ¡ d ¡ dS )z1Replace the last displayed prompt with a new one.r   N)r.   r    ZisValidr~   r   rF   rE   rG   Z
KeepAnchorr!   ri   Z _insert_html_fetching_plain_textrk   r„   ZrehighlightBlockZ_prompt_cursorZsetPositionrC   )r4   Znew_prompt_numberr    rJ   rQ   r   r   r   ro   ~  s    




zJupyterWidget._update_promptc             C   sf   |d }|d dkr*| j r$| j j}q2d}n|d }| j rT| j j|krT|  |¡ d| _ |  |d ¡ dS )z2 Reimplemented for IPython-style prompts.
        r8   rR   rS   r   rT   Nr   )r.   r"   ro   rV   )r4   rY   r8   Zprevious_prompt_numberr   r   r   Ú"_show_interpreter_prompt_for_reply–  s    

z0JupyterWidget._show_interpreter_prompt_for_replyÚlightbgc             C   sf   |  ¡ }|dkr"tj| _tj| _n@|dkr<tj| _tj| _n&|dkrVtj| _tj	| _nt
d| ƒ‚dS )zó Sets the widget style to the class defaults.

        Parameters
        ----------
        colors : str, optional (default lightbg)
            Whether to use the default light background or dark
            background or B&W style.
        r’   ZlinuxZnocolorzNo such color scheme: %sN)Úlowerr   Zdefault_light_style_sheetr0   Zdefault_light_syntax_styleÚsyntax_styleZdefault_dark_style_sheetZdefault_dark_syntax_styleZdefault_bw_style_sheetZdefault_bw_syntax_styleÚKeyError)r4   Zcolorsr   r   r   r3   ¯  s    	


zJupyterWidget.set_default_stylec             C   sê   | j r| j ||¡ nÐ| js(|  d¡ n¾yfd| }|rN| jrN| jj||d}n>y| j ¡ }W n" tk
r~   | jj|d}Y nX |d| 7 }W n tk
r¬   |  d¡ Y n:X yt|dd W n& t	k
rä   d	}|  || ¡ Y nX d
S )zß Opens a Python script for editing.

        Parameters
        ----------
        filename : str
            A path to a local system file.

        line : int, optional
            A line of interest in the file.
        z{No default editor available.
Specify a GUI text editor in the `JupyterWidget.editor` configurable to enable the %edit magicz"%s")Úfilenamerq   )r–   ú zInvalid editor command.
T)Úshellz)Opening editor with command "%s" failed.
N)
Úcustom_editÚcustom_edit_requestedÚemitÚeditorrx   Úeditor_lineÚformatr•   r   ÚOSError)r4   r–   rq   ZcommandrY   r   r   r   Ú_editÉ  s*    

zJupyterWidget._editc             C   sP   y| j | }W n* tk
r8   ddlm} || j ƒ}Y nX |rH| j| }d| S )z; Given a prompt number, returns an HTML In prompt.
        r   )Úescapez!<span class="in-prompt">%s</span>)Ú	in_promptÚ	TypeErrorÚxml.sax.saxutilsr¡   Úother_output_prefix)r4   r"   rg   Úbodyr¡   r   r   r   ri   ð  s    
zJupyterWidget._make_in_promptc             C   sJ   d}t | d¡ƒt |ƒ }|r6|t | j d¡d ƒ7 }d| | }d| S )zf Given a plain text version of an In prompt, returns an HTML
            continuation prompt.
        z...: r   éÿÿÿÿz&nbsp;z!<span class="in-prompt">%s</span>)ra   Úlstripr¥   Úrsplit)r4   rQ   rg   Z	end_charsZspace_countr¦   r   r   r   rj   ý  s    z'JupyterWidget._make_continuation_promptc             C   sP   y| j | }W n* tk
r8   ddlm} || j ƒ}Y nX |rH| j| }d| S )z< Given a prompt number, returns an HTML Out prompt.
        r   )r¡   z"<span class="out-prompt">%s</span>)Ú
out_promptr£   r¤   r¡   r¥   )r4   r"   rg   r¦   r¡   r   r   r   rz     s    
zJupyterWidget._make_out_promptc             C   s   |   |d |d ¡ d S )Nr–   Zline_number)r    )r4   rŒ   r   r   r   r&     s    z"JupyterWidget._handle_payload_editc             C   s   |d | _ | j | ¡ d S )NZ
keepkernel)r/   Zexit_requestedr›   )r4   rŒ   r   r   r   r(     s    
z"JupyterWidget._handle_payload_exitc             C   s   |d | _ d S )Nr~   )Zinput_buffer)r4   rŒ   r   r   r   r,   "  s    z(JupyterWidget._handle_payload_next_inputc             C   sD   |d }d|kr.| j dkr.| j|d dd n| j|d dd d S )Nrv   z	text/htmlZrichT)rŽ   z
text/plainF)rU   Z_page)r4   rŒ   rv   r   r   r   r*   %  s    z"JupyterWidget._handle_payload_pagec             C   sH   |   | j¡ | jdk	r(| j ¡  | j¡ | jdk	rD| j ¡  | j¡ dS )z9 Set the style sheets of the underlying widgets.
        N)ZsetStyleSheetr0   rH   r   ZsetDefaultStyleSheetZ_page_control)r4   r   r   r   r1   1  s
    

z"JupyterWidget._style_sheet_changedc             C   sD   | j dkrdS | jr2| j  | j¡ | j | j¡ n| j  | j¡ dS )z3 Set the style for the syntax highlighter.
        N)r„   r”   Z	set_styleZ_ansi_processorZset_background_colorZset_style_sheetr0   )r4   r   r   r   r2   ;  s    
z#JupyterWidget._syntax_style_changedc             C   s   dj tdS )NzJupyter QtConsole {version}
)Úversion)rž   r   )r4   r   r   r   Ú_banner_defaultI  s    zJupyterWidget._banner_default)N)r’   )N)F)F)F)>r   r   r   r   r   r™   r   ZSignalÚobjectrš   r   Údefault_editorrœ   r   r0   r”   Údefault_in_promptr¢   Údefault_out_promptrª   Údefault_input_sepr   Údefault_output_sepry   Údefault_output_sep2r}   r   r   r%   r'   r+   r)   r^   r…   r$   rO   rX   rf   rr   ru   r   r   r‡   r†   rŠ   r   rV   ro   r‘   r3   r    ri   rj   rz   r&   r(   r,   r*   r1   r2   r¬   Ú__classcell__r   r   )r7   r   r   8   sd   !!


'



r   c                   s    e Zd ZdZ‡ fdd„Z‡  ZS )r   z$Deprecated class; use JupyterWidget.c                s    t dtƒ tt| ƒj||Ž d S )Nz.IPythonWidget is deprecated; use JupyterWidget)r   ÚDeprecationWarningr#   r   r$   )r4   Úar6   )r7   r   r   r$   Q  s    zIPythonWidget.__init__)r   r   r   r   r$   r´   r   r   )r7   r   r   O  s   ),r   Úcollectionsr   Úos.pathÚosÚreÚ
subprocessr   Úsysr_   Útextwrapr   Úwarningsr   Zqtconsole.qtr   r   ZIPython.lib.lexersr   r	   Zpygments.lexersr
   Zpygments.utilr   Z	qtconsoler   Z	traitletsr   r   Zfrontend_widgetr   r   r   r¯   r°   r±   r²   r³   Zzmq_shell_sourceÚplatformÚ
startswithr®   r   r   r   r   r   r   Ú<module>   s@       