o
    tf                     @   s   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	 ddl
mZ ddlmZmZmZ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 ddlmZ G dd deZG dd deeZdS )z"Frontend widget for the Qt Console    )
namedtupleN)QtCoreQtGui	QtWidgets)BaseFrontendMixin)AnyBoolInstanceUnicodeDottedObjectNamedefault   )BracketMatcher)CallTipWidget)HistoryConsoleWidget)PygmentsHighlighter)import_itemc                       sV   e Zd ZdZd fdd	Zdd Zdd Z fd	d
Z fddZ fddZ	  Z
S )FrontendHighlighterzA A PygmentsHighlighter that understands and ignores prompts.
    Nc                    s\   t  j|j |d d| _|| _d| _tdt	|j
 | _tdt	|j
 | _d S )Nlexerr   Fz!^(%s)?([ \t]*>>> |^[ \t]*\.\.\. )z0^(%s)?([ \t]*In \[\d+\]: |[ \t]*\ \ \ \.\.\.+: ))super__init___controldocument_current_offsetZ	_frontendhighlighting_onrecompileescapeZother_output_prefix_classic_prompt_re_ipy_prompt_re)selfZfrontendr   	__class__ b/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/qtconsole/frontend_widget.pyr      s   
zFrontendHighlighter.__init__c                 C   :   |r|  r|S | j|}|r|t|dd S |S )z,Handle inputs that start with '>>> ' syntax.r   N)isspacer   matchlengroupr!   linemr$   r$   r%   transform_classic_prompt&      z,FrontendHighlighter.transform_classic_promptc                 C   r&   )z7Handle inputs that start classic IPython prompt syntax.r   N)r'   r    r(   r)   r*   r+   r$   r$   r%   transform_ipy_prompt1   r/   z(FrontendHighlighter.transform_ipy_promptc                    sl   t | dr| js
dS |  }| }|dd}| |}t|t| }|dkr4|| _t 	| dS dS )zL Highlight a block of text. Reimplemented to highlight selectively.
        r   N     r   )
hasattrr   ZcurrentBlocktextreplacer0   r)   r   r   highlightBlock)r!   stringZcurrent_blockZwithout_promptdiffr"   r$   r%   r6   <   s   
z"FrontendHighlighter.highlightBlockc                    s"   | j }d| _ t | || _ dS )zG Reimplemented to temporarily enable highlighting if disabled.
        TN)r   r   rehighlightBlock)r!   blockoldr"   r$   r%   r9   T   s   
z$FrontendHighlighter.rehighlightBlockc                    s   || j 7 }t ||| dS )z1 Reimplemented to highlight selectively.
        N)r   r   	setFormat)r!   startcountformatr"   r$   r%   r<   \   s   
zFrontendHighlighter.setFormatN)__name__
__module____qualname____doc__r   r.   r0   r6   r9   r<   __classcell__r$   r$   r"   r%   r      s    r   c                       sz  e Zd ZdZeddZe ZedZedZ	e
 ZedZe
eZe
 ZeddddZeddddZeddddZedd	dZd
d Zdd Ze Zdd Ze
eZe
eZe
eZedddgZ edg dZ!edg dZ"dZ#e$e%ddZ&e#f 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/ fd*d+Z0d,d- Z1d.d/ Z2d0d1 Z3d2d3 Z4d4d5 Z5d6d7 Z6dod8d9Z7d:d; Z8dod<d=Z9d>d? Z:d@dA Z;dBdC Z<dDdE Z=dFdG Z>dHdI Z?dJdK Z@dLdM ZAdpdNdOZBdpdPdQZCdRdS ZDdTdU ZEdVdW ZFdXdY ZGdZd[ ZHd\d] ZId^d_ ZJd`da ZKdbdc ZLddde ZMdfdg ZNdhdi ZOdjdk ZPeQdldmdn ZR  ZSS )qFrontendWidgetz0 A Qt frontend for a generic Python kernel.
    T)configFz9Whether to draw information calltips on open-parentheses.)rG   helpz9Whether to clear the console when the kernel is restartedz;Whether to ask for user confirmation when restarting kernelz The pygments lexer class to use.c                 C   s   t |}| | _d S r@   )r   r   )r!   namer;   newlexer_classr$   r$   r%   _lexer_class_changed   s   z#FrontendWidget._lexer_class_changedc                 C      dS )Nzpygments.lexers.Python3Lexerr$   r!   r$   r$   r%   _lexer_class_default   s   z#FrontendWidget._lexer_class_defaultc                 C   s   t | j}| S r@   )r   rK   )r!   rK   r$   r$   r%   _lexer_default   s   
zFrontendWidget._lexer_default_CallTipRequestidpos_CompletionRequest)rR   coderS   _ExecutionRequest)rR   kindhidden)
allow_nonec                    s  t  j|i | t| j| _t| j| _tdd | _	t
| | jd| _d | _d | _i | _i | jd< i | _d| _d| _| d | j| j | j| jj | j	}|d |td |tjj |j | j! | j"|j | #| | j$ }|j%| j& || _'d| _(d S )	NzCopy (Raw Text)r   executeT   z... FzCtrl+Shift+C))r   r   r   r   Z_bracket_matcherr   _call_tip_widgetr   ZQAction_copy_raw_actionr   r   _highlighterZ_kernel_managerZ_kernel_client_request_info_callback_dict_display_bannerZ	tab_widthZ_set_continuation_promptZsetFontZfontZfont_changedconnectZ
setEnabledZsetShortcutr   QKeySequenceZsetShortcutContextr   QtZWidgetWithChildrenShortcutZ	triggeredcopy_rawZcopy_availableZ	addActionr   ZcontentsChange_document_contents_change_local_kernel_pending_clearoutput)r!   Zlocal_kernelargskwactionr   r"   r$   r%   r      s4   





zFrontendWidget.__init__c                    s   j dur j  r j   dS  j r j   }|r| ^}} j }||	  ||
  tjj |  } fdd}|| }t|}||}|t| }	|	t|k rm|t||	 d }t|dkr|d r j }||  |
 }
|
 }|
 }|| ||| d tjj |  }t|t|| }	t|d |	k rd|d< t||}d|g|}z|d dk}W n ty   d	}Y nw |r|dd }tj | dS dS  jd
 dS )zN Copy the currently selected text to the clipboard, removing prompts.
        Nc                    s    j | }  j | S )zRemove all prompts from line.)r^   r.   r0   r,   rN   r$   r%   remove_prompts   s   z+FrontendWidget.copy.<locals>.remove_promptsr   r    
Fz%frontend widget : unknown copy target)Z_page_controlZhasFocuscopyr   
textCursorZ	selectionZtoPlainText
splitlinesZsetPositionZselectionStartr:   positionr   QTextCursor
KeepAnchorr)   ZselectionEndlengthmapjoin
IndexErrorr   ZQApplication	clipboardZsetTextlogdebug)r!   r4   Zfirst_line_selectionZremaining_linescursorZpreceding_textrm   
first_lineZlen_with_promptZ
prompt_lenr:   	start_posrw   Zlast_line_fullZwas_newliner$   rN   r%   rq      s`   





9zFrontendWidget.copyc                 C   s>   | j ||}| |d|| jd |< |s| j| dS dS )z Execute 'source'. If 'hidden', do not show any output.

        See parent class :meth:`execute` docstring for full details.
        userrZ   N)kernel_clientrZ   rV   r_   	executingemit)r!   sourcerX   msg_idr$   r$   r%   _execute  s   zFrontendWidget._executec                 C      | j s	d| j_dS dS )z= Called immediately after a new prompt is displayed.
        TN_readingr^   r   rN   r$   r$   r%   _prompt_started_hook&  s   z#FrontendWidget._prompt_started_hookc                 C   r   )z Called immediately after a prompt is finished, i.e. when some input
            will be processed and a new prompt displayed.
        FNr   rN   r$   r$   r%   _prompt_finished_hook,  s   z$FrontendWidget._prompt_finished_hookc                 C   sR   |   }|du r
dS t|d|    }|o|   dk}|r&|   | S )zk Called when the tab key is pressed. Returns whether to continue
            processing the event.
        NFro   )_get_input_buffer_cursor_linebool_get_input_buffer_cursor_columnstrip_get_cursorZselectedText	_complete)r!   r4   Znon_ws_beforecompleter$   r$   r%   _tab_pressed3  s   zFrontendWidget._tab_pressedc                    sL   t  |}| D ]}| tjjtjjkr#|	|| j
  |S q
|S )z6 Reimplemented to add an action for raw copy.
        )r   _context_menu_makeactionsZshortcutmatchesr   rc   ZPasteZ
ExactMatchZinsertActionr]   )r!   rS   ZmenuZbefore_actionr"   r$   r%   r   H  s   z!FrontendWidget._context_menu_makec                 C   s   | j r	|   d S d S r@   )
_executinginterrupt_kernelrN   r$   r$   r%   request_interrupt_kernelS  s   z'FrontendWidget.request_interrupt_kernelc                 C   s   d}| j |dd d S )Nz,Are you sure you want to restart the kernel?Fnow)restart_kernel)r!   messager$   r$   r%   request_restart_kernelW  s   z%FrontendWidget.request_restart_kernelc                    s  |  }| j| ddr:|tjjkr-| jr-|  r'|t	j
jr'|   dS |   dS |tjjkr9|   dS nA| tjj@ s{|tjjkr{|  }| j }|dkr{| s{|  d| }|dr{| s{|t	jjt	jjd |  dS t |S )zG Reimplemented for execution interruption and smart backspace.
        F)Zinclude_commandT   Nz    r[   ) keyZ_control_key_down	modifiersr   rd   ZKey_Cr   Zcan_copyr   r   rc   ZCopyrq   r   Z
Key_Periodr   ZAltModifierZKey_Backspacer   r   rr   ZhasSelectionr   endswithr   movePositionru   Leftrv   ZremoveSelectedTextr   _event_filter_console_keypress)r!   eventr   colr~   r4   r"   r$   r%   r   [  s2   

z-FrontendWidget._event_filter_console_keypressc                 C   s8   |  |r|d dd}|rd| _dS |   dS dS )zHandle clear output messages.contentwaitTN)include_outputgetrh   clear_output)r!   msgr   r$   r$   r%   _handle_clear_output  s   

z#FrontendWidget._handle_clear_outputc                 C   sH   t t }| jjdd||id}|| j|< | |dd| jd |< dS )aL  Silently execute `expr` in the kernel and call `callback` with reply

        the `expr` is evaluated silently in the kernel (without) output in
        the frontend. Call `callback` with the
        `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument

        Parameters
        ----------
        expr : string
            valid string to be executed by the kernel.
        callback : function
            function accepting one argument, as a string. The string will be
            the `repr` of the result of evaluating `expr`

        The `callback` is called with the `repr()` of the result of `expr` as
        first argument. To get the object, do `eval()` on the passed value.

        See Also
        --------
        _handle_exec_callback : private method, deal with calling callback with reply

        ro   T)Zsilentuser_expressionssilent_exec_callbackFrZ   N)struuiduuid1r   rZ   r`   rV   r_   )r!   exprcallbackZ
local_uuidr   r$   r$   r%   _silent_exec_callback  s   
z$FrontendWidget._silent_exec_callbackc                 C   sB   |d  d}|sdS |D ]}|| jv r| j|||  qdS )a  Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``

        Parameters
        ----------
        msg : raw message send by the kernel containing an `user_expressions`
                and having a 'silent_exec_callback' kind.

        Notes
        -----
        This function will look for a `callback` associated with the
        corresponding message id. Association has been made by
        `_silent_exec_callback`. `callback` is then called with the `repr()`
        of the value of corresponding `user_expressions` as argument.
        `callback` is then removed from the known list so that any message
        coming again with the same id won't trigger it.
        r   r   N)r   r`   pop)r!   r   Zuser_expZ
expressionr$   r$   r%   _handle_exec_callback  s   
z$FrontendWidget._handle_exec_callbackc                 C   s  | j d|dd |d d }| jd |}d| _|r!|jr#dS |jd	krl| jj	 s4| jj
  | jr<| j  |d }|d
 }|dkrN| | n	|dkrW| | | | | j| | jd | dS |jdkr| | | jd | dS td|j )z- Handles replies for code execution.
        zexecute_reply: %sr   ro   parent_headerr   rZ   FNr   statusokZabortedr   zUnknown handler for %s)r|   r}   r   r_   r   rX   rW   r   iopub_channelclosedflushZ
ansi_codesZ_ansi_processorZ	reset_sgr_process_execute_ok_process_execute_abort"_show_interpreter_prompt_for_replyexecutedr   r   r   RuntimeError)r!   r   r   infor   r   r$   r$   r%   _handle_execute_reply  s0   






z$FrontendWidget._handle_execute_replyc                 C   s   |  | dS )z  Handle error messages.
        N)_process_execute_errorr!   r   r$   r$   r%   _handle_error     zFrontendWidget._handle_errorc                    s    j d|dd |d d } jd |}|r"|jr"td jj s. jj	   fdd	} j
r@ j d
 d _
 j|d d ||d d d dS )z( Handle requests for raw_input.
        z	input: %sr   ro   r   r   rZ   z.Request for raw input during hidden execution.c                    s        j|  d S r@   )Z_finalize_input_requestr   inputrl   rN   r$   r%   r     s   z6FrontendWidget._handle_input_request.<locals>.callbackz9Got second input request, assuming first was interrupted.Fpromptpassword)r   r   N)r|   r}   r   r_   rX   r   r   r   r   r   r   Z	_readline)r!   r   r   r   r   r$   rN   r%   _handle_input_request  s   
$z$FrontendWidget._handle_input_requestc                 C   s"   |rdnd}| j d| dd d S )NzKernel died, restartingzKernel restartingz<br>%s<hr><br>FZbefore_prompt)_append_html)r!   diedr   r$   r$   r%   _kernel_restarted_message  s   

z(FrontendWidget._kernel_restarted_messagec                 C   s<   | j d| | jr| j| dS | jdd |   dS )zAHandle the kernel's death (if we do not own the kernel).
        zkernel died: %sTr   N)r|   warningcustom_restartcustom_restart_kernel_diedr   r   reset)r!   Zsince_last_heartbeatr$   r$   r%   _handle_kernel_died  s
   z"FrontendWidget._handle_kernel_diedc                 C   s4   | j d | j|d | jr| j  |   dS )zoNotice that the autorestarter restarted the kernel.

        There's nothing to do but show a message.
        zkernel restartedr   N)r|   r   r   kernel_managerZreset_autorestart_countr   )r!   r   r$   r$   r%   _handle_kernel_restarted  s
   
z'FrontendWidget._handle_kernel_restartedc                 C   s   | j d|dd |  }| jd}|r@|j|d d krB|j| krD|d }|ddkrF|d	d
rH| j	| dS dS dS dS dS dS )zHandle replies for call tips.z	oinfo: %sr   ro   call_tipr   r   r   r   foundFN)
r|   r}   r   r   r_   rR   rS   rt   r\   Zshow_inspect_data)r!   repr~   r   r   r$   r$   r%   _handle_inspect_reply&  s   z$FrontendWidget._handle_inspect_replyc                 C   sN   | j d|dd | |r%|   |d d }| j|d dd dS dS )	z% Handle display hook output.
        zexecute_result: %sr   ro   datarp   Tr   N)r|   r}   r   r   flush_clearoutput_append_plain_text)r!   r   r4   r$   r$   r%   _handle_execute_result1  s   
z%FrontendWidget._handle_execute_resultc                 C   sB   | j d|dd | |r|   | |d d  dS dS )z+ Handle stdout, stderr, and stdin.
        z
stream: %sr   ro   r4   N)r|   r}   r   r   r   append_streamr   r$   r$   r%   _handle_stream:  s
   
zFrontendWidget._handle_streamc                 C   s   | j d|dd |di dd}|d r.|d d }| jd |}|r.|jr.d	S | |sj|r=| jdd
 d	S | jrH| j	|  d	S | 
  }tj| |dtjjtjj}|tjjkrl| j	|  d	S d	S d	S )z= Handle shutdown signal, only if from other console.
        zshutdown: %sr   ro   restartFr   r   rZ   Nr   z8Kernel has been shutdown permanently. Close the Console?)r|   r}   r   r_   rX   Z	from_herer   rg   exit_requestedr   ZwindowZwindowTitler   QMessageBoxquestionYesNo)r!   r   r   r   r   titleZreplyr$   r$   r%   _handle_shutdown_replyB  s*   


z%FrontendWidget._handle_shutdown_replyc                 C   sP   |d  dd}|dkr| jr| jdd d	S d	S |dkrd	S |dkr&	 d	S d	S )
zHandle status messager   Zexecution_statero   startingTr   idlebusyN)r   r   r   )r!   r   stater$   r$   r%   _handle_statusa  s   zFrontendWidget._handle_statusc                 C   s   | j dd dS )z Called when the KernelManager channels have started listening or
            when the frontend is assigned an already listening KernelManager.
        T)clearN)r   rN   r$   r$   r%   _started_channelso  s   z FrontendWidget._started_channelsc                 C   s   | j   dS )z Copy the currently selected text to the clipboard without attempting
            to remove prompts or otherwise alter the text.
        N)r   rq   rN   r$   r$   r%   re   y  s   zFrontendWidget.copy_rawc                 C   sB   | j rd| _| j  dS | jrd| _| j  dS | d dS )z Attempts to interrupt the running kernel.

        Also unsets _reading flag, to avoid runtime errors
        if raw_input is called again.
        Fz+Cannot interrupt a kernel I did not start.
N)custom_interruptr   custom_interrupt_requestedr   r   r   r   rN   r$   r$   r%   r     s   zFrontendWidget.interrupt_kernelc                 C   sb   | j rd| _ i | jd< d| _d| j_|r+| j  | jr+| | j	 | j
r+| | j
 |   dS )a   Resets the widget to its initial state if ``clear`` parameter
        is True, otherwise
        prints a visual indication of the fact that the kernel restarted, but
        does not clear the traces from previous usage of the kernel before it
        was restarted.  With ``clear=True``, it is similar to ``%clear``, but
        also re-writes the banner and aborts execution if necessary.
        FrZ   N)r   r_   r   r^   r   r   r   ra   r   bannerkernel_banner_show_interpreter_prompt)r!   r   r$   r$   r%   r     s   

zFrontendWidget.resetc              
   C   s   | j r
| j  dS | jri| jj  | jr.tj	j
tj	jB }tj	| d||}|tj	j
k}nd}|raz	| jj|d W n tyW } z| jd| dd W Y d}~dS d}~ww | jddd dS | jj  dS | jddd dS )	z1 Attempts to restart the running kernel.
        NzRestart kernel?Tr   zError restarting kernel: %s
r   z!<br>Restarting kernel...
<hr><br>z(Cannot restart a Kernel I did not start
)r   custom_restart_requestedr   r   r   Z
hb_channelpauseconfirm_restartr   r   r   r   r   r   r   r   r   Zunpause)r!   r   r   ZbuttonsresultZ
do_restarter$   r$   r%   r     s<   	



zFrontendWidget.restart_kernelc                 C   s   | j |dd dS )z"Appends text to the output stream.Tr   Nr   )r!   r4   r$   r$   r%   r     s   zFrontendWidget.append_streamc                 C   s   | j rd| _ |   dS dS )z(If a clearoutput is pending, execute it.FN)rh   r   rN   r$   r$   r%   r     s   z FrontendWidget.flush_clearoutputc                 C   s<   | j  }|  |tjjtjj |d |	  dS )z"Clears the current line of output.ro   N)
r   rr   ZbeginEditBlockr   r   ru   ZStartOfLinerv   Z
insertTextZendEditBlockr!   r~   r$   r$   r%   r     s   


zFrontendWidget.clear_outputc                 C   s<   |   }|tjj | | dkr|   dS dS )z{Trigger call tip automatically on open parenthesis

        Call tips can be requested explcitly with `_call_tip`.
        (N)	r   r   r   ru   r   r   ZcharacterAtrt   	_call_tipr   r$   r$   r%   _auto_call_tip  s
   zFrontendWidget._auto_call_tipc                 C   sT   | j r	| jj sdS |  }| j}| j||}|   }| 	||| j
d< dS )zAShows a call tip, if appropriate, at the current cursor location.Fr   T)enable_calltipsr   Zshell_channelis_alive_get_input_buffer_cursor_posinput_bufferinspectr   rt   rQ   r_   )r!   
cursor_posrU   r   rS   r$   r$   r%   r    s   zFrontendWidget._call_tipc                 C   s:   | j }|  }| jj||d}| |||}|| jd< dS )z= Performs completion at the current cursor location.
        )rU   r  r   N)r  r  r   r   rT   r_   )r!   rU   r  r   r   r$   r$   r%   r     s
   zFrontendWidget._completec                 C      |  d dS )z; Process a reply for an aborted execution request.
        zERROR: execution aborted
Nr   r   r$   r$   r%   r     r   z%FrontendWidget._process_execute_abortc                 C   s^   |d }|d dkr!|d dkp|d dk}|| _ | j|  d	S d|d }| | d	S )
zM Process a reply for an execution request that resulted in an error.
        r   Zename
SystemExitZevaluez-kTruero   	tracebackN)Z_keep_kernel_on_exitr   r   ry   r   )r!   r   r   Z
keepkernelr  r$   r$   r%   r     s   z%FrontendWidget._process_execute_errorc                 C   s@   |d  dg }|D ]}| |sd}t|t|d   q
dS )z= Process a reply for a successful execution request.
        r   payloadz,Warning: received unknown payload of type %sr   N)r   _process_execute_payloadprintrepr)r!   r   r  itemr   r$   r$   r%   r   &  s   
z"FrontendWidget._process_execute_okc                 C   rM   )z Process a single payload item from the list of payload items in an
            execution reply. Returns whether the payload was handled.
        Fr$   )r!   r  r$   r$   r%   r  /  s   z'FrontendWidget._process_execute_payloadc                 C   r	  )z- Shows a prompt for the interpreter.
        z>>> N)Z_show_promptrN   r$   r$   r%   r   7  r   z'FrontendWidget._show_interpreter_promptc                 C   s   |    dS )zN Shows a prompt for the interpreter given an 'execute_reply' message.
        N)r   r   r$   r$   r%   r   <  s   z1FrontendWidget._show_interpreter_prompt_for_replyc                 C   s(   ||7 }||    kr|   dS dS )zh Called whenever the document's content changes. Display a call tip
            if appropriate.
        N)r   rt   r  )r!   rt   removedaddedr$   r$   r%   rf   C  s   z(FrontendWidget._document_contents_changer   c                 C   s   d}|t jt jf S )z- Returns the standard Python banner.
        zVPython %s on %s
Type "help", "copyright", "credits" or "license" for more information.)sysversionplatform)r!   r   r$   r$   r%   _banner_defaultN  s   zFrontendWidget._banner_default)T)F)TrA   rB   rC   rD   r
   r   r   r   ra   r   r   ZSignalr   r   floatr   r   r  Zclear_on_kernel_restartr   r   rK   rL   rO   r   r   rP   objectr   r   r   r   rQ   rT   rV   rg   r	   r   r^   r   rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   re   r   r   r   r   r   r   r  r  r   r   r   r   r  r   r   rf   r   r  rE   r$   r$   r"   r%   rF   c   s    




-F'	!(


	


2
	rF   )rD   collectionsr   r  r   r   Zqtpyr   r   r   Zqtconsole.base_frontend_mixinr   Z	traitletsr   r   r	   r
   r   r   Zbracket_matcherr   Zcall_tip_widgetr   Zhistory_console_widgetr   Zpygments_highlighterr   utilr   r   rF   r$   r$   r$   r%   <module>   s     M