a
    ©ˆcÄ1  ã                   @   s¨   d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z
ddlZddlmZ ejdk oje
jdk ZesŠede
j› dej› d�ƒ‚eƒ ZG d	d
„ d
ejjƒZdS )zŽ
This module contains an extended version of the upstream ipykernel IPKernelApp.

The main reason for extending is to support clean shutdown.
é    N)Ú	Heartbeat)é   )é   zŸThe IPython-related Envisage components are currently compatible with ipykernel<6 and IPython<8. The versions installed in the current environment are IPython z and ipykernel zH. See https://github.com/enthought/envisage/issues/448 for more details.c                       s¨   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Z‡ fd
d„Z‡ fdd„Z	‡ fdd„Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Z‡  ZS )$ÚIPKernelAppzO
    Patched version of the IPKernelApp, mostly to support clean shutdown.
    c                 C   sJ   t  ¡ }t|| j| j| jfƒ| _| jj| _| j 	d| j ¡ | j 
¡  dS )a;  start the heart beating

        Overridden from the base class in order to swap in our own
        Heartbeat class in place of the official one. Our Heartbeat class
        is modified to allow the heartbeat thread to be shut down cleanly.

        This override can be removed once we're on ipkernel 5.x.
        z!Heartbeat REP Channel on port: %iN)ÚzmqÚContextr   Ú	transportÚipÚhb_portÚ	heartbeatÚportÚlogÚdebugÚstart)ÚselfZhb_ctx© r   úl/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/envisage/plugins/ipython_kernel/kernelapp.pyÚinit_heartbeat9   s    ÿ
zIPKernelApp.init_heartbeatc                 C   s   dS )a  Patch important libraries that can't handle sys.stdout forwarding.

        Overridden from the base class to do nothing.

        The base class method monkeypatches faulthandler so that calling
        faulthandler.enable() while streams are redirected doesn't fail.

        This override bypasses that patching. Users of the Envisage plugin
        are advised to enable faulthandler (if desired) as part of
        application setup, before the plugin is started.

        Related: https://github.com/ipython/ipykernel/issues/91
        Nr   ©r   r   r   r   Úpatch_ioM   s    zIPKernelApp.patch_ioc                 C   s"   t  d¡}|js| t  ¡ ¡ dS )ac  
        Configure tornado logging.

        Adds a NullHandler to the tornado root logger, if there are
        no handlers already present on that logger. If no tornado
        handler is present at the time the IO loop is started, tornado
        will call logging.basicConfig, which isn't what we want to happen.

        Overridden from the base class, which unconditionally adds a new
        StreamHandler every time.

        See also:
        - https://github.com/tornadoweb/tornado/blob/v6.0.3/tornado/ioloop.py#L427-L445  # noqa: E501
        - https://github.com/tornadoweb/tornado/pull/741
        ZtornadoN)ÚloggingÚ	getLoggerÚhandlersÚ
addHandlerÚNullHandler)r   Úloggerr   r   r   Úconfigure_tornado_logger]   s    
z$IPKernelApp.configure_tornado_loggerc                 C   s|   t j | j¡}|| jks,t j | j¡| jkr2|}n| j}dd| g}|D ]}| j |¡ qHt| j	| j
| j| j| jd�| _dS )a  
        Display connection info, and store ports.

        Overridden to not write information to __stdout__. We don't usually
        want this in applications that embed an IPython kernel (as opposed
        to the case where IPython effectively *is* the application).
        z.To connect another client to this kernel, use:z    --existing %s)ÚshellZiopubÚstdinZhbÚcontrolN)ÚosÚpathÚbasenameZconnection_fileÚdirnameZconnection_dirr   ÚinfoÚdictZ
shell_portZ
iopub_portZ
stdin_portr
   Zcontrol_portZports)r   r"   ÚtailÚlinesÚliner   r   r   Úlog_connection_infoq   s&    ÿþþûzIPKernelApp.log_connection_infoc                    s   t j| _tƒ  ¡  dS )z£
        Set up a suitable exception hook.

        Extended to keep track of the original sys.excepthook value, so that it
        can be restored later.
        N)ÚsysÚ
excepthookÚ_original_sys_excepthookÚsuperÚinit_crash_handlerr   ©Ú	__class__r   r   r.   —   s    zIPKernelApp.init_crash_handlerc                    s2   | j rtj| _tj| _| jr$tj| _t	ƒ  
¡  dS )z£
        Redirect input streams and set a display hook.

        Extended to store the original sys attributes so that they
        can be restored later.
        N)Úoutstream_classr*   ÚstdoutÚ_original_sys_stdoutÚstderrÚ_original_sys_stderrÚdisplayhook_classÚdisplayhookÚ_original_sys_displayhookr-   Úinit_ior   r/   r   r   r9   ¡   s    zIPKernelApp.init_ioc                    s2   t tjjdtƒ| _t tjjdtƒ| _tƒ  ¡  dS )zÅ
        Create the kernel object itself.

        Extended to store the original values of IPython.utils.io.stdout
        and IPython.utils.io.stderr, so that they can be restored later.
        r2   r4   N)	ÚgetattrÚIPythonÚutilsÚioÚ_MISSINGÚ!_original_ipython_utils_io_stdoutÚ!_original_ipython_utils_io_stderrr-   Úinit_kernelr   r/   r   r   rA   ±   s    
ÿ
ÿzIPKernelApp.init_kernelc                 C   sX   |   ¡  |  ¡  |  ¡  |  ¡  |  ¡  |  ¡  t | j¡ |  ¡  |  	¡  |  
¡  dS )z�
        Undo the effects of the initialize method:

        - free resources allocated during initialization
        - undo changes to global state
        N)Úclose_shellÚclose_kernelÚclose_ioÚclose_heartbeatÚclose_socketsZcleanup_connection_fileÚatexitÚ
unregisterÚclose_crash_handlerÚclose_profile_dirÚcleanup_singletonsr   r   r   r   ÚcloseÂ   s    zIPKernelApp.closec                 C   s¢   | j j}|j}|jd }| ¡  t |j¡ |j ¡  d|_d|_	| 
¡  | ¡  t |j¡ |jj ¡  t |jjj¡ |jj ¡  |jdd…= |`|`|`dS )z<
        Clean up resources allocated by the shell.
        ZScriptMagicsN)Úkernelr   Úmagics_managerÚregistryZkill_bg_processesrG   rH   ZmagicsÚclearÚparentÚcleanupZatexit_operationsZhistory_managerZsave_threadÚstopÚdbrL   ZconfigurablesÚsys_excepthookZ_orig_sys_module_stateZ_orig_sys_modules_main_mod)r   r   rN   Zscript_magicsr   r   r   rB   Ú   s$    

zIPKernelApp.close_shellc                 C   sz   | j }|jr(|j ¡ }| ¡  | ¡  qd|_| jtu rBtj	j
`n| jtj	j
_| `| jtu rftj	j
`n| jtj	j
_| `dS )z.
        Undo setup from init_kernel.
        N)rM   Zshell_streamsÚpopZstop_on_recvrL   Zstdin_socketr@   r>   r;   r<   r=   r4   r?   r2   )r   rM   Ústreamr   r   r   rC   ÿ   s    





zIPKernelApp.close_kernelc                 C   sH   | j r| jt_| `| jrDtj ¡  | jt_| `tj ¡  | j	t_| `	dS )zj
        Undo the effects of init_io.

        Restores sys module attributes altered by init_io.
        N)
r6   r8   r*   r7   r1   r4   rL   r5   r2   r3   r   r   r   r   rD     s    

zIPKernelApp.close_ioc                 C   s,   | j j}| j  ¡  t | j j¡ | ¡  dS )z0
        Close iopub-related resources.
        N)Ziopub_threadÚsocketrS   rG   rH   rL   )r   Ziopub_socketr   r   r   Úclose_iopub0  s    
zIPKernelApp.close_iopubc                 C   s   | j t_| ` dS )zv
        Undo the global state change from init_crash_handler.

        Restore the sys.excepthook attribute.
        N)r,   r*   r+   r   r   r   r   rI   <  s    zIPKernelApp.close_crash_handlerc                 C   s   | j j ¡  | j  ¡  dS )zb
        Stop the heartbeat thread, by terminating the corresponding
        zmq.Context.
        N)r   ÚcontextÚtermÚjoinr   r   r   r   rE   E  s    zIPKernelApp.close_heartbeatc                 C   sr   |   ¡  dD ]4}| j d|¡ t| |d dƒ}|r|js| ¡  qt| dƒrn| j d¡ | j ¡  | j d¡ dS )zL
        Unbind, close and destroy sockets created by init_sockets.
        )r   r   r   zClosing %s channelÚ_socketNrZ   zTerminating zmq contextzTerminated zmq context)	rY   r   r   r:   ÚclosedrL   ÚhasattrrZ   r[   )r   ZchannelrX   r   r   r   rF   N  s    



zIPKernelApp.close_socketsc                 C   s(   t j | j¡}|tjv r$tj |¡ dS )z8
        Undo changes made in init_profile_dir.
        N)r    r!   ÚabspathZipython_dirr*   Úremove)r   Zipython_dir_entryr   r   r   rJ   a  s    
zIPKernelApp.close_profile_dirc                 C   s   t jj ¡  t jj ¡  dS )z8
        Clear SingletonConfigurable instances.
        N)Ú	ipykernelZzmqshellZZMQInteractiveShellZclear_instanceZipkernelZIPythonKernelr   r   r   r   rK   i  s    zIPKernelApp.cleanup_singletons)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r)   r.   r9   rA   rL   rB   rC   rD   rY   rI   rE   rF   rJ   rK   Ú__classcell__r   r   r/   r   r   2   s$   &
%		r   )rf   rG   r   r    r*   Zipykernel.ipkernelrb   Zipykernel.kernelappZipykernel.zmqshellZIPython.utils.ior;   r   Z)envisage.plugins.ipython_kernel.heartbeatr   Úversion_infoZipykernel_availableÚImportErrorÚ__version__Úobjectr>   Z	kernelappr   r   r   r   r   Ú<module>
   s.   
þþýÿ	