U
    -eQS                  
   @   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mZ ddlmZm	Z	m
Z
mZmZmZmZmZ eeZeeZeeZG dd dejZeeZG dd dejZeeZG d	d
 d
ejZeeZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)ej*j+j,Z,g e,_-ee,_.ej*j+j/Z0eeee
eeege0_-ee0_.ej*j+j1Z1eeeeeege1_-ee1_.ej*j+j2Z3eeeeeee
eeeg
e3_-ee3_.ej*j+j4Z4eege4_-ee4_.ej*j+j5Z5g e5_-ee5_.ej*j+j6Z6ege6_-ee6_.ej*j+j7Z7ee
eee
ge7_-ee7_.ej*j+j8Z8ee
eee
ge8_-ee8_.ej*j+j9Z9eege9_-ee9_.ej*j+j:Z:eege:_-ee:_.ej*j+j;Z;ege;_-ee;_.ej*j+j<Z<eege<_-ee<_.ej*j+j=Z=eeeeeeege=_-ee=_.ej*j+j>Z>eeege>_-ee>_.ej*j+j?Z?ege?_-ee?_.ej*j@jAZAeeejBgeA_-eeeA_.ej*j+jCZCe	geC_-e	eC_.G dd deDZEG dd deDZFdd ZGeHdkr\eId eGd eId  dS )!zvWindows-specific implementation of process utilities with direct WinAPI.

This file is meant to be used by process.py
    N)POINTER)HANDLEHLOCALLPVOIDWORDDWORDBOOLULONGLPCWSTRc                   @   s"   e Zd ZdefdefdefgZdS )SECURITY_ATTRIBUTESnLengthlpSecurityDescriptorbInheritHandleN)__name__
__module____qualname__r   r   r   _fields_ r   r   h/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/IPython/utils/_process_win32_controller.pyr      s   r   c                   @   s|   e Zd Zdefdefdefdefdefdefdefdefd	efd
efdefdefdefdefdefdefdefdefgZdS )STARTUPINFOcbZ
lpReservedZ	lpDesktopZlpTitleZdwXZdwYZdwXSizeZdwYSizeZdwXCountCharsZdwYCountCharsZdwFillAttributedwFlagsZwShowWindowZcbReserved2ZlpReserved2	hStdInput
hStdOutput	hStdErrorN)	r   r   r   r   r
   r   r   r   r   r   r   r   r   r      s&   r   c                   @   s(   e Zd ZdefdefdefdefgZdS )PROCESS_INFORMATIONhProcesshThreadZdwProcessIdZ
dwThreadIdN)r   r   r   r   r   r   r   r   r   r   r   2   s
   r   &   m                  i   i  i         c                   @   s    e Zd ZdZdd Zdd ZdS )AvoidUNCPatha  A context manager to protect command execution from UNC paths.

    In the Win32 API, commands can't be invoked with the cwd being a UNC path.
    This context manager temporarily changes directory to the 'C:' drive on
    entering, and restores the original working directory on exit.

    The context manager returns the starting working directory *if* it made a
    change and None otherwise, so that users can apply the necessary adjustment
    to their system calls in the event of a change.

    Examples
    --------
    ::
        cmd = 'dir'
        with AvoidUNCPath() as path:
            if path is not None:
                cmd = '"pushd %s &&"%s' % (path, cmd)
            os.system(cmd)
    c                 C   s6   t  | _| jd| _| jr.t d | jS d S d S )Nz\\zC:)osgetcwdpath
startswithis_unc_pathchdirselfr   r   r   	__enter__   s    

zAvoidUNCPath.__enter__c                 C   s   | j rt| j d S N)r,   r(   r-   r*   r/   exc_type	exc_value	tracebackr   r   r   __exit__   s    zAvoidUNCPath.__exit__N)r   r   r   __doc__r0   r6   r   r   r   r   r'      s   r'   c                   @   sl   e Zd ZdZdddZdd Zdd Zd	d
 ZdddZdd Z	dd Z
dd Zdd Zdd Zdd ZdS )Win32ShellCommandControllera  Runs a shell command in a 'with' context.

    This implementation is Win32-specific.

    Example:
        # Runs the command interactively with default console stdin/stdout
        with ShellCommandController('python -i') as scc:
            scc.run()

        # Runs the command using the provided functions for stdin/stdout
        def my_stdout_func(s):
            # print or save the string 's'
            write_to_stdout(s)
        def my_stdin_func():
            # If input is available, return it as a string.
            if input_available():
                return get_input()
            # If no input available, return None after a short delay to
            # keep from blocking.
            else:
                time.sleep(0.01)
                return None
      
        with ShellCommandController('python -i') as scc:
            scc.run(my_stdout_func, my_stdin_func)
    Tc                 C   s   || _ || _dS )aU  Initializes the shell command controller.

        The cmd is the program to execute, and mergeout is
        whether to blend stdout and stderr into one output
        in stdout. Merging them together in this fashion more
        reliably keeps stdout and stderr in the correct order
        especially for interactive shell usage.
        N)cmdmergeout)r/   r9   r:   r   r   r   __init__   s    	z$Win32ShellCommandController.__init__c                    s  | j }| j}d\| _| _| _d | _zdd gd \}}}}}}t  t	  _
d _d  _ fdd}	|	dd\}}|rt }tt |t t|ddtst n|	dd\}}|	dd\}}t }
t }t	||_||_||_||_t|_ttB }td d	| d d d|d d t|t|

s.t t| d }t| d }|d k	r\t| d }|| _d }|| _d }|s|| _d }|
| _W 5 |rt| |rt| |rt| |rt| |rt| |rt| X | S )
N)NNN   Tc                    sh   t  t  f}tt|d t|d t ds<t t||  tdsTt |d j|d jfS )zCreates a Windows pipe, which consists of two handles.

                The 'uninherit' parameter controls which handle is not
                inherited by the child process.
                r   r!   )r   
CreatePipectypesbyrefWinErrorSetHandleInformationHANDLE_FLAG_INHERITvalue)	uninheritZhandlesZsaAttrr   r   create_pipe   s       z:Win32ShellCommandController.__enter__.<locals>.create_piper   )rD   r!   zcmd.exe /c )r9   r:   hstdouthstdinhstderr
piProcInfoCloseHandler   r>   Zsizeofr   r   r   r   DuplicateHandleGetCurrentProcessr?   DUPLICATE_SAME_ACCESSr@   r   r   r   r   r   r   STARTF_USESTDHANDLESr   CREATE_SUSPENDEDCREATE_NO_WINDOWCreateProcess)r/   r9   r:   Zp_hstdinZc_hstdinZ	p_hstdoutZ	c_hstdoutZ	p_hstderrZ	c_hstderrrF   rJ   ZsiStartInfoZdwCreationFlagsr   rE   r   r0      s         
     


z%Win32ShellCommandController.__enter__c                 C   s   t  }t d}| }|d krbt|t|s4t |jtkrBd S t|ddt|d st qt|t	rv|
d}t|tstdt|dkrd S || t|dkrt||t|t|d st tkrd S t ||jd  }qqd S )Nr    utf_8z$internal stdin function string error)r   GetExitCodeProcessr>   r?   r@   rC   STILL_ACTIVE	WriteFile
isinstanceunicodeencodestrRuntimeErrorlenGetLastErrorERROR_NO_DATA)r/   handleZhprocessfuncstdout_funcZexitCodeZbytesWrittendatar   r   r   _stdin_threadE  s<    
 


 
z)Win32ShellCommandController._stdin_threadc                 C   sh   t d}td}t||dt |d sBt }|tkr:d S t  |jd|j }||	dd q
d S )Ni   r   rT   replace)
r>   create_string_bufferr   ReadFiler?   r^   ERROR_BROKEN_PIPEr@   rC   decode)r/   r`   ra   rc   	bytesReadlesr   r   r   _stdout_threadw  s    
 z*Win32ShellCommandController._stdout_threadNc                 C   s(  |dkr |dkr |dkr |   S |dk	r6| jr6tdd}g }|r`tj| j| j| jj||fd}|	tj| j
| j|fd | js|dkr|}|	tj| j
| j|fd t| jjdkrt |dk	r|  |D ]}|  qt| jjttkrt |D ]}|  q|dk	r$|  dS )a  Runs the process, using the provided functions for I/O.

        The function stdin_func should return strings whenever a
        character or characters become available.
        The functions stdout_func and stderr_func are called whenever
        something is printed to stdout or stderr, respectively.
        These functions are called from different threads (but not
        concurrently, because of the GIL).
        NzqShell command was initiated with merged stdin/stdout, but a separate stderr_func was provided to the run() method)targetargsr%   )
_run_stdior:   r\   	threadingThreadrd   rH   rJ   r   appendrm   rG   rI   ResumeThreadr   r>   r@   startWaitForSingleObjectINFINITEWAIT_FAILEDjoin)r/   rb   
stdin_funcstderr_funcZstdin_threadthreadsthreadr   r   r   run  sH    

 

zWin32ShellCommandController.runc                 C   s   t tj }t|d}|tkr,t n|t	krDt
ddd dS td}td}t
ddd t||dt|dst t| |j}|d	d
}|dd
}t
t|d dd |S dS )z>Use the raw Win32 handle of sys.stdin to do non-blocking readsd   .rS   )endNr"   r   ?z

 )msvcrtZget_osfhandlesysstdinfilenorv   rx   r>   r@   WAIT_TIMEOUTprintrf   r   rg   r?   FlushConsoleInputBufferrC   re   repr)r/   r`   resultrc   rj   r   r   r   _stdin_raw_nonblock  s*    


 z/Win32ShellCommandController._stdin_raw_nonblockc              
   C   s^   zt jd}|dd}|W S  tk
rX } z|jtkrDW Y dS |W 5 d}~X Y nX dS )zUse a blocking stdin readr!   r   r   N)r   r   readre   ZWindowsErrorwinerrorr_   )r/   rc   Zwer   r   r   _stdin_raw_block  s    

z,Win32ShellCommandController._stdin_raw_blockc                 C   s   t |dtjd tj  dS zWrites the string to stdoutrS   )r   fileN)r   r   stdoutflushr/   rl   r   r   r   _stdout_raw  s    z'Win32ShellCommandController._stdout_rawc                 C   s   t |dtjd tj  dS r   )r   r   stderrr   r   r   r   r   _stderr_raw  s    z'Win32ShellCommandController._stderr_rawc                 C   s2   | j r| j| j| jdS | j| j| j| jdS dS )zRuns the process using the system standard I/O.

        IMPORTANT: stdin needs to be asynchronous, so the Python
                   sys.stdin object is not used. Instead,
                   msvcrt.kbhit/getwch are used asynchronously.
        )rb   rz   )rb   rz   r{   N)r:   r~   r   r   r   r.   r   r   r   rp     s    z&Win32ShellCommandController._run_stdioc                 C   sn   | j rt| j  d | _ | jr,t| j d | _| jrBt| j d | _| jd k	rjt| jj t| jj d | _d S r1   )rH   rK   rG   rI   rJ   r   r   r2   r   r   r   r6     s    



z$Win32ShellCommandController.__exit__)T)NNN)r   r   r   r7   r;   r0   rd   rm   r~   r   r   r   r   rp   r6   r   r   r   r   r8      s   
`2
3r8   c              
   C   sF   t  6}|dk	rd|| f } t| }|  W 5 Q R X W 5 Q R X dS )a  Win32 version of os.system() that works with network shares.

    Note that this implementation returns None, as meant for use in IPython.

    Parameters
    ----------
    cmd : str
        A command to be executed in the system shell.

    Returns
    -------
    None : we explicitly do NOT return the subprocess status code, as this
    utility is meant to be used extensively in IPython, where any return value
    would trigger : func:`sys.displayhook` calls.
    Nz"pushd %s &&"%s)r'   r8   r~   )r9   r*   Zsccr   r   r   system"  s
    
r   __main__zTest starting!z	python -izTest finished!)Jr7   r(   r   rq   r>   r   r   Zctypes.wintypesr   r   r   r   r   r   r	   r
   ZLPDWORDZLPHANDLEZ	ULONG_PTRZ	Structurer   ZLPSECURITY_ATTRIBUTESr   ZLPSTARTUPINFOr   ZLPPROCESS_INFORMATIONZERROR_HANDLE_EOFrh   r_   rB   rO   rP   ZCREATE_NEW_CONSOLErQ   rV   r   rx   rw   rN   ZENABLE_ECHO_INPUTZENABLE_LINE_INPUTZENABLE_PROCESSED_INPUTwindllkernel32r^   ZargtypesrestypeZCreateFileWZ
CreateFiler=   ZCreateProcessWrR   rU   rM   rt   rg   rW   ZGetConsoleModeZSetConsoleModer   rv   rL   rA   rK   Zshell32ZCommandLineToArgvWc_intZ	LocalFreeobjectr'   r8   r   r   r   r   r   r   r   <module>   s   (


 
     













  




%  g
