3
7ßL]œY  ã               @   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
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! d dl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)Ú	cStringIO)Útime)ÚQtCoreÚQtGui)ÚPythonLexer)ÚEventÚprovides)Úpython_nameé   )ÚPygmentsHighlighter)ÚBracketMatcherÚCallTipWidgetÚCompletionLexerÚHistoryConsoleWidget)ÚIPythonShellÚMPythonShell)ÚKeyPressedEvent)ÚWidgetc                   sˆ   e Zd ZdZeZeeƒZ‡ 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.
    c                s&   t t| ƒjf d|i|—Ž | jƒ  d S )NÚparent)Úsuperr   Ú__init__Z_create)Úselfr   Ztraits)Ú	__class__© ú>/tmp/pip-install-5sebvq2j/pyface/pyface/ui/qt4/python_shell.pyr   9   s    zPythonShell.__init__c             C   s   | j jS )N)ÚcontrolÚinterpreter)r   r   r   r   r   C   s    zPythonShell.interpreterTc             C   s   | j j||d� d S )N)Úhidden)r   Úexecute)r   Úcommandr    r   r   r   Úexecute_commandF   s    zPythonShell.execute_commandc             C   s   | j j||d� d S )N)r    )r   Úexecute_file)r   Úpathr    r   r   r   r$   I   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_index)r   r   r   r   Úget_historyL   s    
zPythonShell.get_historyc             C   s6   d|  kot |ƒkn  s$t |ƒ}| j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_historyX   s    
zPythonShell.set_historyc             C   s
   t | |ƒS )N)ÚPyfacePythonWidget)r   r   r   r   r   Ú_create_controlj   s    zPythonShell._create_controlc                s2   t t| ƒjƒ  | jjj| jƒ | jjj| j	ƒ d S )N)
r   r   Ú_add_event_listenersr   ÚexecutedÚconnectÚ_on_command_executedÚ_event_filterÚsignalÚ_on_obj_drop)r   )r   r   r   r,   m   s    z PythonShell._add_event_listenersc                s<   | j d k	r*| j jj| jƒ | jjj| jƒ tt	| ƒj
ƒ  d S )N)r   r-   r.   r/   r0   r1   Z
disconnectr2   r   r   Ú_remove_event_listeners)r   )r   r   r   r3   t   s    
z#PythonShell._remove_event_listenersc             C   s
   t | jƒS )N)Ú_DropEventEmitterr   )r   r   r   r   Z__event_filter_default|   s    z"PythonShell.__event_filter_defaultc             C   sŠ   d}t |dƒr`t|jtjƒr`t|jƒdkr`t|jƒ}yt||diƒrH|}W n tk
r^   Y nX || j	j
j|< | j	j|ƒ | j	jjƒ  dS )z@ Handle dropped objects and add to interpreter local namespace. ZdraggedÚnamer   TN)ÚhasattrÚ
isinstancer5   ÚsixÚstring_typesr'   r   ÚevalÚ	Exceptionr   r   Úlocalsr!   Ú_controlZsetFocus)r   Úobjr5   Zpy_namer   r   r   r2   ƒ   s    

zPythonShell._on_obj_drop)T)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r	   Zcommand_executedr   Úkey_pressedr   r   r#   r$   r&   r)   r+   r,   r3   Z"_PythonShell__event_filter_defaultr2   Ú__classcell__r   r   )r   r   r   &   s   


r   c                   sÜ   e Zd ZdZejƒ Zd/‡ fdd„	Zdd„ Zd0dd„Z	d1d
d„Z
d2d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d3dd„Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd4d'd(„Zd)d*„ Zd+d,„ Zd-d.„ Z‡  ZS )5ÚPythonWidgetz, A basic in-process Python interpreter.
    Nc                sÈ   t t| ƒj|ƒ tdd d�| _t| jƒ| _tƒ | _t	| j
ƒ| _t| j
ƒ| _ttƒ ƒ| _d| _t| ƒ| _d| _tjj| _d| _| jdƒ | jj| jƒ | jj| jjƒ | j
jƒ }|jj| j ƒ | j!ƒ  d S )NZ__console__)r?   rB   Fr   é   z... )"r   rE   r   Údictr<   r   r   ÚStringIOÚ_bufferr   r=   Z_bracket_matcherr   Ú_call_tip_widgetr   r   Ú_completion_lexerÚ_hiddenÚPythonWidgetHighlighterÚ_highlighterÚ_last_refresh_timeÚsysÚstdinÚencodingZ	tab_widthZ_set_continuation_promptZsetFontÚfontZfont_changedr.   ÚdocumentZcontentsChangeÚ_document_contents_changeÚreset)r   r   rT   )r   r   r   r   ¤   s$    



zPythonWidget.__init__c             C   sF   | j jdƒ | j jƒ }| j jƒ  tƒ | _ | j|ƒ | jjtj	j
ƒ dS )zA Flush the buffer by writing its contents to the screen.
        r   N)rI   ÚseekÚgetvalueÚcloserH   Ú_append_plain_textr=   Z
moveCursorr   ÚQTextCursorZEnd)r   Útextr   r   r   ÚflushÊ   s    


zPythonWidget.flushc             C   s
   | j |ƒ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j|ƒ |r8tƒ }|| j dkr8| jƒ  || _dS )zM Write text to the buffer, possibly flushing it if 'refresh' is set.
        gš™™™™™©?N)rL   rI   Úwriter   rO   r]   )r   r\   ÚrefreshÚcurrent_timer   r   r   r`   Ú   s    zPythonWidget.writec             C   s    x|D ]}| j ||d� qW dS )z. Write a list of lines to the buffer.
        )ra   N)r`   )r   Úlinesra   Úliner   r   r   Ú
writelineså   s    
zPythonWidget.writelinesc          	   C   sL   |rD|j ƒ }t|ƒdkr2yt|ƒdk	S    dS qH|d jƒ 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Ú éÿÿÿÿ)Ú
splitlinesr'   r   Ústrip)r   ÚsourceÚinteractiverc   r   r   r   Ú_is_completeï   s    zPythonWidget._is_completec             C   sŠ   t j}t j}t j}|  t _ t _t _|| _z| jj|ƒ}W dd| _t j| krR|t _t j| krb|t _t j| krr|t _| jjƒ  | j	ƒ  X dS )z† Execute 'source'. If 'hidden', do not show any output.

        See parent class :meth:`execute` docstring for full details.
        NF)
rP   rQ   ÚstdoutÚstderrrL   r   Z	runsourcer-   ÚemitÚ_show_interpreter_prompt)r   rj   r    Z	old_stdinZ
old_stdoutZ
old_stderrZmorer   r   r   Ú_execute  s     



zPythonWidget._executec             C   s   | j sd| j_dS )z= Called immediately after a new prompt is displayed.
        TN)Ú_readingrN   Úhighlighting_on)r   r   r   r   Ú_prompt_started_hook  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.
        FN)rr   rN   rs   )r   r   r   r   Ú_prompt_finished_hook$  s    z"PythonWidget._prompt_finished_hookc             C   s>   | j ƒ }|dkrdS t|d| jƒ … jƒ ƒ}|r8| jƒ  | 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_columnri   Ú	_complete)r   r\   Zcompleter   r   r   Ú_tab_pressed+  s    zPythonWidget._tab_pressedc                sœ   |j ƒ tjjkrŒ|jƒ tjj@  rŒ| jƒ }| jjƒ }|dkrŒ|j	ƒ  rŒ| j
ƒ d|… }|jdƒrŒ|jƒ  rŒ|jtjjtjjdƒ |jƒ  dS tt| ƒj|ƒS )z, Reimplemented for smart backspace.
        é   Nz    rF   T)Úkeyr   ÚQtZKey_BackspaceÚ	modifiersÚAltModifierrx   r=   Z
textCursorZhasSelectionrv   Úendswithri   ÚmovePositionr   r[   ÚLeftÚ
KeepAnchorZremoveSelectedTextr   rE   Ú_event_filter_console_keypress)r   ÚeventÚcolÚcursorr\   )r   r   r   r„   >  s    

z+PythonWidget._event_filter_console_keypressc                s~   t t| ƒj|ƒ | j}d}x:|jƒ d D ]*}|dkr>|d7 }q(|dkrP|d7 }q(P q(W |jƒ jdƒrl|d7 }|jd| ƒ dS )	z- Reimplemented for auto-indentation.
        r   r   ú	rF   ú ú:Nrg   )r   rE   Ú_insert_continuation_promptZinput_bufferrh   Úrstripr€   Ú
insertText)r   r‡   rj   ÚspaceÚc)r   r   r   r‹   R  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!   Úrepr)r   r%   r    r   r   r   r$   g  s    zPythonWidget.execute_filec             C   s2   d| _ d| j_| jjƒ  | j| jƒ ƒ | jƒ  dS )zr Resets the widget to its initial state. Similar to ``clear``, but
            also re-writes the banner.
        FN)rr   rN   rs   r=   ÚclearrZ   Ú_get_bannerrp   )r   r   r   r   rV   n  s
    
zPythonWidget.resetc             C   s€   | j ƒ }|jtjjƒ |jƒ j|jƒ ƒdkr0dS | j|ƒ}|sBdS | j	|ƒ\}}t
|ddƒ}|dk	r|| r|| jj|d� dS dS )zK Shows a call tip, if appropriate, at the current cursor location.
        ú(FrB   N)ÚdocT)Ú_get_cursorr�   r   r[   r‚   rT   ZcharacterAtÚpositionÚ_get_contextÚ_get_symbol_from_contextÚgetattrrJ   Zshow_call_info)r   r‡   ÚcontextÚsymbolÚleftoverr”   r   r   r   Ú	_call_tip}  s    
zPythonWidget._call_tipc                s®   | j ƒ }|rª| j|ƒ\}‰ tˆ ƒdkrªˆ d ‰ |dkr^t| jjjƒ ƒ}|ttjj	j
jƒ ƒ7 }nt|ƒ}‡ fdd„|D ƒ}|rª| jƒ }|jtjjt|d ƒd� | j||ƒ dS )z= Performs completion at the current cursor location.
        r   r   Nc                s   g | ]}|j ˆ ƒr|‘qS r   )Ú
startswith)Ú.0Ún)rœ   r   r   ú
<listcomp>ž  s    z*PythonWidget._complete.<locals>.<listcomp>)r    rg   )r—   r˜   r'   Úlistr   r<   Úkeysr8   ÚmovesÚbuiltinsÚ__dict__Údirr•   r�   r   r[   r‚   Z_complete_with_items)r   rš   r›   ÚnamesZcompletionsr‡   r   )rœ   r   ry   ‘  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.)rP   ÚversionÚplatform)r   Zbannerr   r   r   r’   ¥  s    zPythonWidget._get_bannerc             C   s<   |dkr| j ƒ }|jtjjtjjƒ |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   r[   ZStartOfBlockrƒ   Z	selectionZtoPlainTextrK   Zget_context)r   r‡   r\   r   r   r   r—   ¬  s    

zPythonWidget._get_contextc             C   s¶   t tt|ƒƒ}t|ƒdkr"d|fS |d }| jjj|dƒ}|dkrTtjj	j
j|dƒ}|dkrdd|fS |dd… }x<t|ƒD ]0\}}t||dƒ}|dkr¦|||d… fS |}qzW |g fS )zh Find a python object in the interpeter namespace from a context (a
            list of names).
        r   Nr   )r¢   ÚmapÚstrr'   r   r<   Úgetr8   r¤   r¥   r¦   Ú	enumerater™   )r   rš   Zbase_symbol_stringr›   Úir5   Z
new_symbolr   r   r   r˜   ·  s     z%PythonWidget._get_symbol_from_contextc             C   s   | j ƒ  | jdƒ dS )z- Shows a prompt for the interpreter.
        z>>> N)r]   Z_show_prompt)r   r   r   r   rp   Ð  s    z%PythonWidget._show_interpreter_promptc             C   s.   ||7 }| j jƒ }|| jƒ jƒ kr*| jƒ  dS )zh Called whenever the document's content changes. Display a call tip
            if appropriate.
        N)r=   rT   r•   r–   r�   )r   r–   ÚremovedÚaddedrT   r   r   r   rU   Ø  s    
z&PythonWidget._document_contents_change)N)N)T)T)F)N)r?   r@   rA   rB   r   ÚSignalr-   r   r]   r_   r`   re   rl   rq   rt   ru   rz   r„   r‹   r$   rV   r�   ry   r’   r—   r˜   rp   rU   rD   r   r   )r   r   rE   ™   s.   &





rE   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 )
rM   z[ A PygmentsHighlighter that can be turned on and off and that ignores
        prompts.
    c                s,   t t| ƒj|jjƒ ƒ d| _|| _d| _d S )Nr   F)r   rM   r   r=   rT   Ú_current_offsetÚ_python_widgetrs   )r   Zpython_widget)r   r   r   r   ì  s
    
z PythonWidgetHighlighter.__init__c                s~   | j s
dS | jƒ }| jj|ƒ}|j| jjƒr6| jj}n| jj}|j|ƒrdt	|ƒ| _
|t	|ƒd… }nd| _
tt| ƒj|ƒ dS )zL Highlight a block of text. Reimplemented to highlight selectively.
        Nr   )rs   ZcurrentBlockr´   Z_get_block_plain_textÚcontainsZ_prompt_posZ_promptZ_continuation_promptrž   r'   r³   r   rM   ÚhighlightBlock)r   ÚstringZcurrent_blockr^   )r   r   r   r¶   ó  s    


z&PythonWidgetHighlighter.highlightBlockc                s&   | j }d| _ tt| ƒj|ƒ || _ dS )zG Reimplemented to temporarily enable highlighting if disabled.
        TN)rs   r   rM   ÚrehighlightBlock)r   ÚblockÚold)r   r   r   r¸     s    z(PythonWidgetHighlighter.rehighlightBlockc                s"   || j 7 }tt| ƒj|||ƒ dS )z1 Reimplemented to highlight selectively.
        N)r³   r   rM   Ú	setFormat)r   ÚstartÚcountÚformat)r   r   r   r»     s    
z!PythonWidgetHighlighter.setFormat)	r?   r@   rA   rB   r   r¶   r¸   r»   rD   r   r   )r   r   rM   ç  s
   rM   c                   s,   e Zd ZdZ‡ fdd„Z‡ fdd„Z‡  ZS )r*   zF A PythonWidget customized to support the IPythonShell interface.
    c                s   || _ tt| ƒj||Ž dS )zj Reimplemented to store a reference to the Pyface widget which
            contains this control.
        N)Ú_pyface_widgetr   r*   r   )r   Zpyface_widgetÚargsÚkw)r   r   r   r   (  s    zPyfacePythonWidget.__init__c                sŒ   |j ƒ }ytt|ƒƒ}W n   d}Y nX |jƒ }t|tjj@ tjjk|tjj@ tjjk|tjj	@ tjj	k||d�| j
_tt| ƒj|ƒ dS )z< Reimplemented to generate Pyface key press events.
        r   )Zalt_downZcontrol_downZ
shift_downZkey_coder…   N)r\   Úordr¬   r~   r   r   r}   r   ZControlModifierZShiftModifierr¿   rC   r   r*   ÚkeyPressEvent)r   r…   ZkstrZkcodeZmods)r   r   r   rÃ   4  s     



z PyfacePythonWidget.keyPressEvent)r?   r@   rA   rB   r   rÃ   rD   r   r   )r   r   r*      s   r*   c               @   s*   e Zd ZdZejeƒZdd„ Zdd„ Z	dS )r4   z  Handle object drops on widget. c             C   s,   t jj| |ƒ || _|jdƒ |j| ƒ d S )NT)r   ÚQObjectr   ÚwidgetZsetAcceptDropsZinstallEventFilter)r   rÅ   r   r   r   r   Q  s    
z_DropEventEmitter.__init__c             C   sš   |j ƒ }|tjjkrDt|jƒ dƒrŠ|jƒ jƒ }|dk	rŠ|jƒ  dS nF|tjjkrŠt|jƒ dƒrŠ|jƒ jƒ }|dk	rŠ| j	j
|ƒ |jƒ  dS tjj| ||ƒS )z Handle drop events on widget. ÚinstanceNT)Útyper   ZQEventZ	DragEnterr6   ZmimeDatarÆ   ÚacceptZDropr1   ro   rÄ   ÚeventFilter)r   rj   r…   Útypr>   r   r   r   rÉ   X  s    z_DropEventEmitter.eventFilterN)
r?   r@   rA   rB   r   r²   Úobjectr1   r   rÉ   r   r   r   r   r4   M  s   
r4   )(Zsix.moves.builtinsr8   Úcoder   r   Z	six.movesr   rH   rP   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   rÅ   r   r   rE   rM   r*   rÄ   r4   r   r   r   r   Ú<module>   s,   
r  P9-