a
    §ˆcè[  ã                   @   s$  d dl Z d dlmZmZ d dlmZ d dlZd dlmZ d dlZd dl	m
Z
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	dlmZmZmZmZ d dlmZmZ d dlmZ d	dlm Z  eeƒG dd„ dee ƒƒZ!G dd„ deƒZ"G dd„ deƒZ#G dd„ de"ƒZ$G dd„ de
j%ƒZ&dS )é    N)Úcompile_commandÚInteractiveInterpreter)ÚStringIO)Útime)ÚQtCoreÚQtGui)ÚPythonLexer)ÚEventÚprovides)Úpython_nameé   )ÚPygmentsHighlighter)ÚBracketMatcherÚCallTipWidgetÚCompletionLexerÚHistoryConsoleWidget)ÚIPythonShellÚMPythonShell)ÚKeyPressedEvent)ÚLayoutWidgetc                       sŒ   e Zd ZdZeƒ ZeeƒZd‡ fdd„	Zdd„ Z	ddd	„Z
dd
d„Zdd„ Zdd„ Zdd„ Z‡ fdd„Z‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚPythonShellzz The toolkit specific implementation of a PythonShell.  See the
    IPythonShell interface for the API documentation.
    Nc                    s>   |  dd¡}tƒ jf d|i|¤Ž |r:|  ¡  t dt¡ d S )NÚcreateTÚparentzšautomatic widget creation is deprecated and will be removed in a future Pyface version, use create=False and explicitly call create() for future behaviour)ÚpopÚsuperÚ__init__r   ÚwarningsÚwarnÚPendingDeprecationWarning)Úselfr   Ztraitsr   ©Ú	__class__© ú]/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/pyface/ui/qt4/python_shell.pyr   <   s    üzPythonShell.__init__c                 C   s   | j jS ©N)ÚcontrolÚinterpreter©r   r"   r"   r#   r&   P   s    zPythonShell.interpreterTc                 C   s   | j j||d� d S ©N©Úhidden)r%   Úexecute)r   Úcommandr*   r"   r"   r#   Úexecute_commandS   s    zPythonShell.execute_commandc                 C   s   | j j||d� d S r(   )r%   Úexecute_file©r   Úpathr*   r"   r"   r#   r.   V   s    zPythonShell.execute_filec                 C   s   | j j| j jfS )a   Return the current command history and index.

        Returns
        -------
        history : list of str
            The list of commands in the new history.
        history_index : int from 0 to len(history)
            The current item in the command history navigation.
        )r%   Z_historyZ_history_indexr'   r"   r"   r#   Úget_historyY   s    
zPythonShell.get_historyc                 C   s4   d|  krt |ƒks"n t |ƒ}| j ||¡ dS )a   Replace the current command history and index with new ones.

        Parameters
        ----------
        history : list of str
            The list of commands in the new history.
        history_index : int
            The current item in the command history navigation.
        r   N)Úlenr%   Z_set_history)r   ÚhistoryZhistory_indexr"   r"   r#   Úset_historye   s    
zPythonShell.set_historyc                 C   s
   t | |ƒS r$   )ÚPyfacePythonWidget)r   r   r"   r"   r#   Ú_create_controlw   s    zPythonShell._create_controlc                    s.   t ƒ  ¡  | jj | j¡ | jj | j¡ d S r$   )	r   Ú_add_event_listenersr%   ÚexecutedÚconnectÚ_on_command_executedÚ_event_filterÚsignalÚ_on_obj_dropr'   r    r"   r#   r7   z   s    
z PythonShell._add_event_listenersc                    sB   | j d ur4| j j | j¡ | jj | j¡ | j  ¡  tƒ  ¡  d S r$   )	r%   r8   Ú
disconnectr:   r;   r<   r=   Ú_remove_event_listenersr   r'   r    r"   r#   r?   �   s
    

z#PythonShell._remove_event_listenersc                 C   s
   t | jƒS r$   )Ú_DropEventEmitterr%   r'   r"   r"   r#   Z__event_filter_default‹   s    z"PythonShell.__event_filter_defaultc                 C   s†   d}t |dƒr\t|jtƒr\t|jƒdkr\t|jƒ}zt||diƒrF|}W n tyZ   Y n0 || jj	j
|< | j |¡ | jj ¡  dS )z@ Handle dropped objects and add to interpreter local namespace. ZdraggedÚnamer   TN)ÚhasattrÚ
isinstancerA   Ústrr2   r   ÚevalÚ	Exceptionr%   r&   Úlocalsr+   Ú_controlZsetFocus)r   ÚobjrA   Zpy_namer"   r"   r#   r=   ’   s     ÿ
þý
zPythonShell._on_obj_drop)N)T)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r	   Zcommand_executedr   Úkey_pressedr   r&   r-   r.   r1   r4   r6   r7   r?   Z"_PythonShell__event_filter_defaultr=   Ú__classcell__r"   r"   r    r#   r   *   s   


r   c                       sè   e Zd ZdZe ¡ Zd1‡ fdd„	Z‡ fdd„Zdd„ Z	d2d	d
„Z
d3dd„Zd4dd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Z‡ fdd„Z‡ fdd„Zd5dd „Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd6d)d*„Zd+d,„ Zd-d.„ Zd/d0„ Z‡  ZS )7ÚPythonWidgetz, A basic in-process Python interpreter.
    Nc                    sÄ   t ƒ  |¡ tdd d�| _t| jƒ| _tƒ | _t| j	ƒ| _
t| j	ƒ| _ttƒ ƒ| _d| _t| ƒ| _d| _tjj| _d| _|  d¡ | j | j¡ | j | jj¡ | j	 ¡ }|j | j¡ |   ¡  d S )NZ__console__)rJ   rM   Fr   é   z... )!r   r   ÚdictrG   r   r&   r   Ú_bufferr   rH   Ú_bracket_matcherr   Ú_call_tip_widgetr   r   Ú_completion_lexerÚ_hiddenÚPythonWidgetHighlighterÚ_highlighterÚ_last_refresh_timeÚsysÚstdinÚencodingZ	tab_widthZ_set_continuation_promptÚsetFontÚfontÚfont_changedr9   ÚdocumentÚcontentsChangeÚ_document_contents_changeÚreset)r   r   ra   r    r"   r#   r   ¶   s$    



zPythonWidget.__init__c                    s@   | j  | jj¡ | j ¡ }|j | j¡ | j 	¡  t
ƒ  	¡  d S r$   )r`   r>   rU   r^   rH   ra   rb   rc   rT   r?   r   )r   ra   r    r"   r#   r?   Ø   s
    

z$PythonWidget._remove_event_listenersc                 C   sH   | j  d¡ | j  ¡ }| j  ¡  tƒ | _ |  |¡ | j tj	j
j¡ dS )zA Flush the buffer by writing its contents to the screen.
        r   N)rS   ÚseekÚgetvalueÚcloser   Ú_append_plain_textrH   Z
moveCursorr   ÚQTextCursorÚMoveOperationZEnd)r   Útextr"   r"   r#   Úflushå   s    


zPythonWidget.flushc                 C   s
   |   |¡S )z: Read and return one line of input from the user.
        )Z	_readline)r   Úpromptr"   r"   r#   Úreadlineð   s    zPythonWidget.readlineTc                 C   s<   | j s8| j |¡ |r8tƒ }|| j dkr8|  ¡  || _dS )zM Write text to the buffer, possibly flushing it if 'refresh' is set.
        gš™™™™™©?N)rW   rS   Úwriter   rZ   rl   )r   rk   ÚrefreshÚcurrent_timer"   r"   r#   ro   õ   s    zPythonWidget.writec                 C   s   |D ]}| j ||d� qdS )z. Write a list of lines to the buffer.
        )rp   N)ro   )r   Úlinesrp   Úliner"   r"   r#   Ú
writelines   s    zPythonWidget.writelinesc                 C   sR   |rJ|  ¡ }t|ƒdkr8zt|ƒduW S    Y dS 0 qN|d  ¡ dkS ndS dS )zÌ Returns whether 'source' can be completely processed and a new
            prompt created. When triggered by an Enter/Return key press,
            'interactive' is True; otherwise, it is False.
        r   NTéÿÿÿÿÚ )Ú
splitlinesr2   r   Ústrip)r   ÚsourceÚinteractiverr   r"   r"   r#   Ú_is_complete
  s    
zPythonWidget._is_completec                 C   sÒ   t j}t j}t j}|  t _ t _t _|| _zX| j |¡ W d| _t j| u rP|t _t j| u r`|t _t j| u rp|t _| j ¡  |  	¡  nJd| _t j| u rš|t _t j| u rª|t _t j| u rº|t _| j ¡  |  	¡  0 dS )z† Execute 'source'. If 'hidden', do not show any output.

        See parent class :meth:`execute` docstring for full details.
        FN)
r[   r\   ÚstdoutÚstderrrW   r&   Z	runsourcer8   ÚemitÚ_show_interpreter_prompt)r   ry   r*   Z	old_stdinZ
old_stdoutZ
old_stderrr"   r"   r#   Ú_execute  s2    




õ



zPythonWidget._executec                 C   s   | j sd| j_dS )z= Called immediately after a new prompt is displayed.
        TN©Ú_readingrY   Úhighlighting_onr'   r"   r"   r#   Ú_prompt_started_hook9  s    z!PythonWidget._prompt_started_hookc                 C   s   | j sd| j_dS )z‡ Called immediately after a prompt is finished, i.e. when some input
            will be processed and a new prompt displayed.
        FNr�   r'   r"   r"   r#   Ú_prompt_finished_hook?  s    z"PythonWidget._prompt_finished_hookc                 C   s>   |   ¡ }|du rdS t|d|  ¡ …  ¡ ƒ}|r8|  ¡  | S )zk Called when the tab key is pressed. Returns whether to continue
            processing the event.
        NF)Ú_get_input_buffer_cursor_lineÚboolÚ_get_input_buffer_cursor_columnrx   Ú	_complete)r   rk   Zcompleter"   r"   r#   Ú_tab_pressedF  s    zPythonWidget._tab_pressedc                    sš   |  ¡ tjjjkrŽ| ¡ tjjj@ sŽ|  ¡ }| j	 
¡ }|dkrŽ| ¡ sŽ|  ¡ d|… }| d¡rŽ| ¡ sŽ| tjjjtjjjd¡ | ¡  dS tƒ  |¡S )z, Reimplemented for smart backspace.
        é   Nz    rQ   T)Úkeyr   ÚQtZKeyZKey_BackspaceÚ	modifiersÚKeyboardModifierÚAltModifierrˆ   rH   Z
textCursorZhasSelectionr†   Úendswithrx   ÚmovePositionr   ri   rj   ÚLeftÚMoveModeÚ
KeepAnchorZremoveSelectedTextr   Ú_event_filter_console_keypress)r   ÚeventÚcolÚcursorrk   r    r"   r#   r–   Y  s    ÿþ
ÿz+PythonWidget._event_filter_console_keypressc                    sx   t ƒ  |¡ | j}d}| ¡ d D ],}|dkr8|d7 }q"|dkrJ|d7 }q" qPq"| ¡  d¡rf|d7 }| d| ¡ dS )	z- Reimplemented for auto-indentation.
        r   ru   ú	rQ   ú r   ú:N)r   Ú_insert_continuation_promptZinput_bufferrw   Úrstripr‘   Ú
insertText)r   r™   ry   ÚspaceÚcr    r"   r#   r�   p  s    

z(PythonWidget._insert_continuation_promptFc                 C   s   | j dt|ƒ |d� dS )z\ Attempts to execute file with 'path'. If 'hidden', no output is
            shown.
        zexec(open(%s).read())r)   N)r+   Úreprr/   r"   r"   r#   r.   …  s    zPythonWidget.execute_filec                 C   s2   d| _ d| j_| j ¡  |  |  ¡ ¡ |  ¡  dS )zr Resets the widget to its initial state. Similar to ``clear``, but
            also re-writes the banner.
        FN)r‚   rY   rƒ   rH   Úclearrh   Ú_get_bannerr   r'   r"   r"   r#   rd   Œ  s
    
zPythonWidget.resetc                 C   s€   |   ¡ }| tjjj¡ | ¡  | ¡ ¡dkr2dS |  	|¡}|sDdS |  
|¡\}}t|ddƒ}|dur||s|| jj|d� dS dS )zK Shows a call tip, if appropriate, at the current cursor location.
        ú(FrM   N)ÚdocT)Ú_get_cursorr’   r   ri   rj   r“   ra   ZcharacterAtÚpositionÚ_get_contextÚ_get_symbol_from_contextÚgetattrrU   Zshow_call_info)r   r™   ÚcontextÚsymbolÚleftoverr¦   r"   r"   r#   Ú	_call_tip›  s    
zPythonWidget._call_tipc                    s¬   |   ¡ }|r¨|  |¡\}‰ tˆ ƒdkr¨ˆ d ‰ |du rZt| jj ¡ ƒ}|ttj ¡ ƒ7 }nt	|ƒ}‡ fdd„|D ƒ}|r¨|  
¡ }|jtjjjt|d ƒd� |  ||¡ dS )z= Performs completion at the current cursor location.
        r   r   Nc                    s   g | ]}|  ˆ ¡r|‘qS r"   )Ú
startswith)Ú.0Ún©r®   r"   r#   Ú
<listcomp>¼  ó    z*PythonWidget._complete.<locals>.<listcomp>ru   )r²   )r©   rª   r2   Úlistr&   rG   ÚkeysÚbuiltinsÚ__dict__Údirr§   r’   r   ri   rj   r“   Z_complete_with_items)r   r¬   r­   ÚnamesZcompletionsr™   r"   r³   r#   r‰   ¯  s     ÿzPythonWidget._completec                 C   s   d}|t jt jf S )zA Gets a banner to display at the beginning of a session.
        zVPython %s on %s
Type "help", "copyright", "credits" or "license" for more information.)r[   ÚversionÚplatform)r   Zbannerr"   r"   r#   r¤   Ä  s    ÿzPythonWidget._get_bannerc                 C   s@   |du r|   ¡ }| tjjjtjjj¡ | ¡  	¡ }| j
 |¡S )zm Gets the context for the specified cursor (or the current cursor
            if none is specified).
        N)r§   r’   r   ri   rj   ZStartOfBlockr”   r•   Z	selectionZtoPlainTextrV   Zget_context)r   r™   rk   r"   r"   r#   r©   Í  s    ÿzPythonWidget._get_contextc                 C   s²   t tt|ƒƒ}t|ƒdkr"d|fS |d }| jj |d¡}|du rPtj |d¡}|du r`d|fS |dd… }t	|ƒD ]4\}}t
||dƒ}|du r¤|||d… f  S |}qt|g fS )zh Find a python object in the interpeter namespace from a context (a
            list of names).
        r   Nr   )r¶   ÚmaprD   r2   r&   rG   Úgetr¸   r¹   Ú	enumerater«   )r   r¬   Zbase_symbol_stringr­   ÚirA   Z
new_symbolr"   r"   r#   rª   Ù  s     z%PythonWidget._get_symbol_from_contextc                 C   s   |   ¡  |  d¡ dS )z- Shows a prompt for the interpreter.
        z>>> N)rl   Z_show_promptr'   r"   r"   r#   r   ò  s    z%PythonWidget._show_interpreter_promptc                 C   s$   ||7 }||   ¡  ¡ kr |  ¡  dS )zh Called whenever the document's content changes. Display a call tip
            if appropriate.
        N)r§   r¨   r¯   )r   r¨   ÚremovedÚaddedr"   r"   r#   rc   ú  s    z&PythonWidget._document_contents_change)N)N)T)T)F)N)rJ   rK   rL   rM   r   ÚSignalr8   r   r?   rl   rn   ro   rt   r{   r€   r„   r…   rŠ   r–   r�   r.   rd   r¯   r‰   r¤   r©   rª   r   rc   rO   r"   r"   r    r#   rP   «   s0   "




	
rP   c                       sD   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡ fdd„Z‡ fdd	„Z‡  ZS )
rX   z[ A PygmentsHighlighter that can be turned on and off and that ignores
        prompts.
    c                    s(   t ƒ  |j ¡ ¡ d| _|| _d| _d S )Nr   F)r   r   rH   ra   Ú_current_offsetÚ_python_widgetrƒ   )r   Zpython_widgetr    r"   r#   r     s    z PythonWidgetHighlighter.__init__c                    sz   | j s
dS |  ¡ }| j |¡}| | jj¡r6| jj}n| jj}| |¡rdt	|ƒ| _
|t	|ƒd… }nd| _
tƒ  |¡ dS )zL Highlight a block of text. Reimplemented to highlight selectively.
        Nr   )rƒ   ZcurrentBlockrÆ   Z_get_block_plain_textÚcontainsZ_prompt_posZ_promptZ_continuation_promptr°   r2   rÅ   r   ÚhighlightBlock)r   ÚstringZcurrent_blockrm   r    r"   r#   rÈ     s    


z&PythonWidgetHighlighter.highlightBlockc                    s"   | j }d| _ tƒ  |¡ || _ dS )zG Reimplemented to temporarily enable highlighting if disabled.
        TN)rƒ   r   ÚrehighlightBlock)r   ÚblockÚoldr    r"   r#   rÊ   0  s    z(PythonWidgetHighlighter.rehighlightBlockc                    s   || j 7 }tƒ  |||¡ dS )z1 Reimplemented to highlight selectively.
        N)rÅ   r   Ú	setFormat)r   ÚstartÚcountÚformatr    r"   r#   rÍ   8  s    
z!PythonWidgetHighlighter.setFormat)	rJ   rK   rL   rM   r   rÈ   rÊ   rÍ   rO   r"   r"   r    r#   rX   
  s
   rX   c                       s,   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡  ZS )r5   zF A PythonWidget customized to support the IPythonShell interface.
    c                    s   || _ tƒ j|i |¤Ž dS )zj Reimplemented to store a reference to the Pyface widget which
            contains this control.
        N)Ú_pyface_widgetr   r   )r   Zpyface_widgetÚargsÚkwr    r"   r#   r   L  s    zPyfacePythonWidget.__init__c                    s”   |  ¡ }ztt|ƒƒ}W n   d}Y n0 | ¡ }t|tjjj@ tjjjk|tjjj	@ tjjj	k|tjjj
@ tjjj
k||d�| j_tƒ  |¡ dS )z< Reimplemented to generate Pyface key press events.
        r   )Zalt_downZcontrol_downZ
shift_downZkey_coder—   N)rk   ÚordrD   rŽ   r   r   r�   r�   r�   ZControlModifierZShiftModifierrÑ   rN   r   ÚkeyPressEvent)r   r—   ZkstrZkcodeZmodsr    r"   r#   rÕ   X  s    
÷
z PyfacePythonWidget.keyPressEvent)rJ   rK   rL   rM   r   rÕ   rO   r"   r"   r    r#   r5   D  s   r5   c                   @   s*   e Zd ZdZe e¡Zdd„ Zdd„ Z	dS )r@   z  Handle object drops on widget. c                 C   s,   t j | |¡ || _| d¡ | | ¡ d S )NT)r   ÚQObjectr   ÚwidgetZsetAcceptDropsZinstallEventFilter)r   r×   r"   r"   r#   r   x  s    
z_DropEventEmitter.__init__c                 C   sž   |  ¡ }|tjjjkrFt| ¡ dƒrŽ| ¡  ¡ }|durŽ| ¡  dS nH|tjjj	krŽt| ¡ dƒrŽ| ¡  ¡ }|durŽ| j
 |¡ | ¡  dS tj | ||¡S )z Handle drop events on widget. ÚinstanceNT)Útyper   ZQEventÚTypeZ	DragEnterrB   ZmimeDatarØ   ÚacceptZDropr<   r~   rÖ   ÚeventFilter)r   ry   r—   ÚtyprI   r"   r"   r#   rÜ     s    z_DropEventEmitter.eventFilterN)
rJ   rK   rL   rM   r   rÄ   Úobjectr<   r   rÜ   r"   r"   r"   r#   r@   s  s   
r@   )'r¸   Úcoder   r   Úior   r[   r   r   Z	pyface.qtr   r   Zpygments.lexersr   Z
traits.apir	   r
   Ztraits.util.clean_stringsr   Z code_editor.pygments_highlighterr   Zconsole.apir   r   r   r   Zpyface.i_python_shellr   r   Zpyface.key_pressed_eventr   Zlayout_widgetr   r   rP   rX   r5   rÖ   r@   r"   r"   r"   r#   Ú<module>   s.      a:/