U
    /ew                     @  s   d dl mZ d dl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
mZmZmZ d dlmZmZmZ G dd dejZdd	 Zd
d ZdS )    )annotationsN)adaptercommonlauncher)jsonlog	messagingsockets)
componentsserverssessionsc                      s  e Zd ZU dZejjZded< G dd dejZG dd dejZ	 fdd	Z
d
d Zdd Zedd Zedd Zedd Zdd Zedd Zedd Zedd Zedd Zedd Zed d! Zed"d# Zed$d% Zed&d' Z fd(d)Zd*d+ Z  ZS ),Clientz+Handles the client side of a debug session.zset[servers.Connection]known_subprocessesc                   @  s   e Zd ZdddddddZdS )zClient.CapabilitiesF)ZsupportsVariableTypeZsupportsVariablePagingZsupportsRunInTerminalRequestZsupportsMemoryReferences#supportsArgsCanBeInterpretedByShellsupportsStartDebuggingRequestN)__name__
__module____qualname__
PROPERTIES r   r   ;/tmp/pip-unpacked-wheel-dg3irmqq/debugpy/adapter/clients.pyCapabilities   s   r   c                   @  s$   e Zd ZdddejddddZdS )zClient.Expectationszen-USTpathoptional)localeZlinesStartAt1ZcolumnsStartAt1Z
pathFormatN)r   r   r   r   enumr   r   r   r   r   Expectations$   s
   r   c              	     s  |dkrbt d|  d| _tj }ttjd t	_
}t|j ttjd t	_}t|j nd| _tj|}t T}t || d | _d| _d | _d| _d | _g | _d| _t | _| |_|  W 5 Q R X | jddd	d
t j!id | jdddd
t j!id d S )NZstdioz"Connecting to client over stdio...TrwFoutputZ	telemetryZptvsdZpackageVersion)categoryr    datadebugpy)"r   infousing_stdior   ZJsonIOStreamZ
from_stdioopenosdevnullsysstdinatexitregisterclosestdoutZfrom_socketr   Sessionsuper__init__	client_idhas_startedstart_requestrestart_requested_initialize_request_deferred_events_forward_terminate_requestsetr   clientchannel
send_eventr#   __version__)selfsockstreamr*   r.   session	__class__r   r   r1   ,   sH    

zClient.__init__c                 C  s4   | j d k	r"| j | td n| jj| d S )NzPropagation deferred.)r7   appendr   debugr:   r;   	propagater>   eventr   r   r   propagate_after_startr   s    
zClient.propagate_after_startc                 C  sP   t d| j | jD ]"}t d|  | jj| qt d| j d | _d S )Nz%Propagating deferred events to {0}...zPropagating deferred {0}z&All deferred events propagated to {0}.)r   rE   r:   r7   Zdescriber;   rF   r$   rG   r   r   r   _propagate_deferred_events}   s    
z!Client._propagate_deferred_eventsc                 C  s   | j r| j j| d S N)serverr;   rF   rG   r   r   r   rH      s    zClient.eventc                 C  s   | j j|S rK   )rL   r;   delegater>   requestr   r   r   rO      s    zClient.requestc                 C  s   | j d k	r|d|dd| _| | || _| | || _|| _ dddddd	d
ddddddddg}dddddddddddddddddd|ddS )NzSession is already initializedZclientID ZraisedzRaised ExceptionsFz'Break whenever any exception is raised.)filterlabeldefaultdescriptionZuncaughtzUncaught ExceptionsTz=Break when the process is exiting due to unhandled exception.ZuserUnhandledzUser Uncaught Exceptionsz/Break when exception escapes into library code.)ZsupportsCompletionsRequestZsupportsConditionalBreakpointsZ supportsConfigurationDoneRequestZsupportsDebuggerPropertiesZ supportsDelayedStackTraceLoadingZsupportsEvaluateForHoversZsupportsExceptionInfoRequestZsupportsExceptionOptionsZsupportsFunctionBreakpointsZ!supportsHitConditionalBreakpointsZsupportsLogPointsZsupportsModulesRequestZsupportsSetExpressionZsupportsSetVariableZsupportsValueFormattingOptionsZsupportsTerminateRequestZsupportsGotoTargetsRequestZsupportsClipboardContextZexceptionBreakpointFiltersZsupportsStepInTargetsRequest)r6   
isnt_validr2   r   capabilitiesr   Zexpectations)r>   rO   Zexception_breakpoint_filtersr   r   r   initialize_request   sV    

zClient.initialize_requestc                   s   t jj fdd}|S )Nc                   s  | ddst| jd kr$|d| js0| jr:|d|dtd| j_	| jj	r^t
  t|dtt | j_} | | |jd k	rd S | jr| j| j d | _|j}| jr|dd	k}d
|krt|}t|d
h |d< d}|drt|}|d= d}||d< z| jj|j| W np tjk
rn   |i  | jd| jt|j Y d S  tjk
r } z| | W 5 d }~X Y nX | jj	r|| _!d| _"|i  | #  d S | j$d || _!tj%S )NZlaunchattachzSession is not initialized yetzSession is already startedZnoDebugFdebugOptionsconsoleinternalConsoleZRedirectOutputTZredirectOutputZisOutputRedirected){0} disconnected before responding to {1}Zinitialized)&Z
is_requestAssertionErrorr6   rU   r   rL   r   rS   rA   no_debugr   Zdont_wait_for_first_connectionr9   arraystrdebug_optionsresponseZ
initialize	argumentsgetdictlistr;   rO   commandr   NoMoreMessagesrespondfinalizeformatreprMessageHandlingErrorrF   r4   r3   rJ   r<   NO_RESPONSE)r>   rO   ra   rc   Zredirectingexcfr   r   handle   sj    








z-Client._start_message_handler.<locals>.handle)r
   	Componentmessage_handler)rq   rr   r   rp   r   _start_message_handler   s    LzClient._start_message_handlerc                   s^  ddl m} | jjdks$tt r.dtdt	
t  fdd}d}|krpd	kr|d
nd	kr|d	}|t	j
tddd}t|stjg}|dt	j
tdd7 }|dd  jd< |jd< dtdd}|dkr|d }d } }}	dkr$dt}|g}
|jd< dkrJdt}d|g}
|jd< dkrdt	j
tddd}	dd|	g}
djd< tdd |||	fD }|dkrdn|dkrĈddt	jd d!d"dd}d#t	d$}d%t	j
tdd&}|
|7 }
t|dko$tjd% t}|rV| jd' sBd(|d krVd)d*tdd}|dkr|dkr|d ntj|pd }t|d+d,}|rtjd-krd.d/tdd}|r|d0k| _d1tjtj}d2d3}zt| W n4 tk
r6 } zd4| j|W 5 d }~X Y nX || j|g|||
||||| d S )5Nr   )	launchers   z"attach" expectedrY   c                   sh   | d   r|d  st| tdd}|dkr6d }| krd|dkr`dt| t|d}|S )Nr   Tr   r   Fz9{0}:false and "debugOptions":[{1}] are mutually exclusive)islowerisupperr]   boolrU   r   rl   )Z	prop_nameZ	flag_namevaluera   rO   r   r   property_or_debug_option(  s    z7Client.launch_request.<locals>.property_or_debug_optionpythonZ
pythonPathz2"pythonPath" is not valid if "python" is specifiedT)r   )	vectorizesize
pythonArgs)r   ZdebugLauncherPythonr   r   programprocessNamemodulez-mcode)rw   z-c
c                 S  s   g | ]}|d kr|qS )r   r   ).0xr   r   r   
<listcomp>^  s      z)Client.launch_request.<locals>.<listcomp>z7either "program", "module", or "code" must be specifiedz6"program", "module", and "code" are mutually exclusiverZ   r[   ZintegratedTerminalZexternalTerminalZconsoleTitlezPython Debug Consoleargs)r   r   z8Shell expansion in "args" is not supported by the clientzJShell expansion in "args" is not available for "console":"internalConsole"cwdsudoZSudowin32z("sudo":true is not supported on Windows.onTerminateKeyboardInterruptZdebugLauncherPathZdebugAdapterHost	127.0.0.1z4{0} couldn't create listener socket for servers: {1}) debugpy.adapterrv   rA   idlenr   connectionscant_handler9   r   r_   r`   rU   r)   
executablerc   joinr   rS   
isinstancerV   r'   r   dirnamerz   platformr8   r   __file__serve	ExceptionZspawn_debuggee)r>   rO   rv   r}   Z
python_keyr~   Zlauncher_pythonr   r   r   r   Znum_targetsrZ   Zconsole_titleZtarget_argsZshell_expand_argsr   r   on_terminateZlauncher_pathZadapter_hostro   r   r|   r   launch_request  s    











	 

 


zClient.launch_requestc              
     s:  j jr|d|dtdd}|dtdd}|dtdd}|dtdd}|dttfdd |d	tdd|d
tdd}|r|dk_|dks|dkr|dkr|d|dkr|d|dkr|dkr|d dkr|ddkr|d dkrdkr|d|dkrlt	 r4|d|dd}|dt}d t
_|dd_t||\}}n t	 s~t  tj \}} dkr\t tszt  W n  tk
r   |dY nX |dtt}fdd}zt || W nH tk
rF }	 z(t  j dt|	f  W Y d S d }	~	X Y nX tj}
 fdd}n8dkrdd }|dkr~tjnd }
nfdd}d }
jd!||d" tj ||
}|d krdkr|i  j d# d S ||
rd$nd%z| j  W n" t!k
r4   |d&| Y nX d S )'Nz'"noDebug" is not supported for "attach"hostTr   portlistenconnect	processIdsubProcessIdr   r   r   z1"listen" and "host"/"port" are mutually exclusivez2"connect" and "host"/"port" are mutually exclusivez-"listen" and "connect" are mutually exclusivez/"listen" and "processId" are mutually exclusivez2"listen" and "subProcessId" are mutually exclusivez5"processId" and "subProcessId" are mutually exclusivez7Multiple concurrent "listen" sessions are not supportedr   restartFz$"processId" must be parseable as intZdebugpyArgsc                   s    j d| |d d S )Nr    r!   r    )r;   r<   r   r>   r   r   	on_output	  s    z(Client.attach_request.<locals>.on_outputz&Error when trying to attach to PID:
%sc                   s
   | j  kS rK   pidconnr   r   r   <lambda>      z'Client.attach_request.<locals>.<lambda>c                 S  s   dS )NTr   r   r   r   r   r     r   c                   s
   | j  kS rK   r   r   )sub_pidr   r   r   "  r   r   ZdebugpyWaitingForServerr   r   z+No known subprocess with "subProcessId":{0}z.Timed out waiting for debug server to connect.z3There is no debug server connected to this adapter.z{0} is already being debugged.)"rA   r^   rU   r`   intre   rz   r8   r   Z
is_servingr   Zaccess_tokenr5   r   listenergetsocknamer   r   r   r_   Zinjectr   swallow_exceptionrj   r   ZPROCESS_SPAWN_TIMEOUTr;   r<   Zwait_for_connectionri   rk   r   Zattach_to_session
ValueError)r>   rO   r   r   r   r   r   Zdebugpy_argsr   etimeoutpredr   r   )r   r>   r   r   attach_request  s    







	



	zClient.attach_requestc                 C  s&  | j d ks| jr|d zzzd| _z| jj|}W nR t	j
k
r   |i  | j i  | jd| jt|j Y W W Ld S X || W n4 t	jk
r } z| j t| W 5 d }~X Y nX W 5 | j jd kr| j i  |   X t D ]&}|jd kr|j| jjkr| | qd S )NzX"configurationDone" is only allowed during handling of a "launch" or an "attach" requestTr\   )r4   r3   r   rb   ri   rJ   rL   r;   rM   r   rh   rA   rj   rk   r   rl   rg   rm   r`   r   r   Zppidr   notify_of_subprocess)r>   rO   resultro   r   r   r   r   configurationDone_requestA  s6    

&
z Client.configurationDone_requestc                   s*   | j j } fdd}|| tjS )Nc                   s     | j d S rK   )ri   body)rb   rO   r   r   handle_responsen  s    z0Client.evaluate_request.<locals>.handle_response)rL   r;   rF   Zon_responser   rn   )r>   rO   Zpropagated_requestr   r   r   r   evaluate_requestj  s    
zClient.evaluate_requestc                 C  s   d|j d< | jj|S )N*threadId)rc   rL   r;   rM   rN   r   r   r   pause_requestu  s    
zClient.pause_requestc                 C  s>   d|j d< z| jj|W S  tjk
r8   ddi Y S X d S )Nr   r   ZallThreadsContinuedT)rc   rL   r;   rM   r   rh   rN   r   r   r   continue_requestz  s
    
zClient.continue_requestc                 C  sJ   ddt jii}| jrFz| jjd}W n tk
r:   Y nX || |S )Nr#   versionZpydevdSystemInfo)r#   r=   rL   r;   rO   r   update)r>   rO   r   Zpydevd_infor   r   r   debugpySystemInfo_request  s    
z Client.debugpySystemInfo_requestc                 C  s.   d| _ | jr| jj|S | jjddd i S )NFzclient requested "terminate"T)terminate_debuggee)r5   r8   rL   r;   rM   rA   rj   rN   r   r   r   terminate_request  s
    zClient.terminate_requestc              	   C  s   d| _ |dtdd}|dkr d }| jd| |i  | jrt  t	d|  t
 D ]0}z|j  W qZ tk
r   t  Y qZX qZd S )NFZterminateDebuggeeTr   r   zclient requested "disconnect"zB{0} disconnected from stdio; closing remaining server connections.)r5   rz   rA   rj   ri   r%   r   stop_servingr   r$   r   r;   r-   r   r   )r>   rO   r   r   r   r   r   disconnect_request  s    
zClient.disconnect_requestc                   s   t    d S rK   )r0   
disconnectr   rB   r   r   r     s    zClient.disconnectc              	   C  s  t d| | | j | jd ks*|| jkr8W 5 Q R  d S d| jjkr`t d| j W 5 Q R  d S t d| | t| jj}| j| | j	  W 5 Q R X dD ]}|
|d  qd|j|d< |j|d< d	D ]}|
|d  q|
d
d }|
dd }d|kr
i |d< d
|d kr2|d k	r&|nd|d d
< d|d krb|d krVt \}}||d d< | jd r| jdd|d nd|d< | jd| d S )Nz{1} is a subprocess of {0}.r   zrNot reporting subprocess for {0}, because the parent process was attached to using "processId" rather than "port".zNotifying {0} about {1}.)r   r   ZpreLaunchTaskZpostDebugTaskrO   r   zSubprocess {0}namer   )r   r   r   r   r   r   r   r   ZstartDebuggingrX   )rO   configurationrO   ZdebugpyAttach)r   r$   rA   r4   r   rc   warningre   addZnotify_changedpoprk   r   r   r   rV   r;   rO   r<   )r>   r   r   keyr   r   _r   r   r   r     sJ    



zClient.notify_of_subprocess)r   r   r   __doc__r
   rs   rt   __annotations__r   r   r1   rI   rJ   rH   rO   rW   ru   r   r   r   r   r   r   r   r   r   r   r   __classcell__r   r   rB   r   r      sJ   

F


9P
 
 
(






r   c                 C  s   t dt| |at S )Nr   )r	   r   r   r   r   r   r   r   r   r     s    r   c                   C  s2   zt   W n  tk
r,   tjdd Y nX d S )Nr   )level)r   r-   r   r   r   r   r   r   r   r     s    r   )
__future__r   r+   r'   r)   r#   r   r   r   Zdebugpy.commonr   r   r   r	   r   r
   r   r   rs   r   r   r   r   r   r   r   <module>   s        d