
    Mh_S              
       N   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ej                  Z ee          Z G d dej                  Z ee          Z G 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+        j1        Z1 ee           ee          eege1_-        ee1_.        ej*        j+        j2        Z3eeeeeee
eeeg
e3_-        ee3_.        ej*        j+        j4        Z4eege4_-        ee4_.        ej*        j+        j5        Z5g e5_-        ee5_.        ej*        j+        j6        Z6ege6_-        ee6_.        ej*        j+        j7        Z7ee
eee
ge7_-        ee7_.        ej*        j+        j8        Z8ee
eee
ge8_-        ee8_.        ej*        j+        j9        Z9e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@        jA        ZAe eejB                  geA_-         ee          eA_.        ej*        j+        jC        ZCe	geC_-        e	eC_.         G d d          ZD G d d          ZEdeFddfdZGeHdk    r# eId            eGd             eId!           dS 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                   $    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_     g/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/utils/_process_win32_controller.pyr   r      s-        E"'0!4(*HHHr   r   c                   ~    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cb
lpReserved	lpDesktoplpTitledwXdwYdwXSizedwYSizedwXCountCharsdwYCountCharsdwFillAttributedwFlagswShowWindowcbReserved2lpReserved2	hStdInput
hStdOutput	hStdErrorN)	r   r   r   r   r   r   r   r   r   r   r   r   r   r      s        uw'g&G$E"E" %( %("E*E"%%'f%v&f%#'HHHr   r   c                   *    e Zd ZdefdefdefdefgZdS )PROCESS_INFORMATIONhProcesshThreaddwProcessId
dwThreadIdN)r   r   r   r   r   r   r   r   r   r-   r-   2   s5        V$F#&u%'HHHr   r-   &   m                  i   i  i         c                   "    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)
    returnNc                     t          j                    | _        | j                            d          | _        | j        rt          j        d           | j        S d S )Nz\\zC:)osgetcwdpath
startswithis_unc_pathchdirselfs    r   	__enter__zAvoidUNCPath.__enter__   sN    IKK	9//66 	HTNNN9 4r   c                 J    | j         rt          j        | j                   d S d S N)rC   r?   rD   rA   rF   exc_type	exc_value	tracebacks       r   __exit__zAvoidUNCPath.__exit__   s/     	 HTY	  	 r   )r=   N)r   r   r   __doc__rG   rN   r   r   r   r<   r<      sF         (
 
 
 
           r   r<   c                   X    e Zd ZdZddZd Zd Zd ZddZd	 Z	d
 Z
d Zd Zd Z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                 "    || _         || _        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)rF   rS   rT   s      r   __init__z$Win32ShellCommandController.__init__   s      r   c                    | j         }| j        }d\  | _        | _        | _        d | _        	 d gdz  \  }}}}}}t                      t          j                  _	        d_
        d _        fd}	 |	d          \  }}|rft                      }t          t                      |t                      t          j        |          ddt                     st          j                    n |	d          \  }} |	d          \  }}t%                      }
t'                      }t          j        |          |_        ||_        ||_        ||_        t0          |_        t4          t6          z  }t9          d d|z   d d d|d d t          j        |          t          j        |
          
  
        st          j                    t;          |           d }t;          |           d }|t;          |           d }|| _        d }|| _        d }|s	|| _        d }|
| _        |rt;          |           |rt;          |           |rt;          |           |rt;          |           |rt;          |           |rt;          |           nl# |rt;          |           |rt;          |           |rt;          |           |rt;          |           |rt;          |           |rt;          |           w w xY w| S )	NNNN   Tc                    t                      t                      f}t          t          j        |d                   t          j        |d                   t          j                  d          st          j                    t          ||          t          d          st          j                    |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   r5   )r   
CreatePipectypesbyrefWinErrorSetHandleInformationHANDLE_FLAG_INHERITvalue)	uninherithandlessaAttrs     r   create_pipez:Win32ShellCommandController.__enter__.<locals>.create_pipe   s     !((FHH,!&,wqz":":"L44fl66J6JAO O , /++++GI,>/4 4 , /+++qz')999r   r   )ra   r5   zcmd.exe /c )rS   rT   hstdouthstdinhstderr
piProcInfor   r[   sizeofr   r   r   r   DuplicateHandleGetCurrentProcessr\   DUPLICATE_SAME_ACCESSr]   r-   r   r   r)   r*   r+   STARTF_USESTDHANDLESr%   CREATE_SUSPENDEDCREATE_NO_WINDOWCreateProcessCloseHandle)rF   rS   rT   	p_hstdout	c_hstdout	p_hstderr	c_hstderrp_hstdinc_hstdinrd   rh   siStartInfodwCreationFlagsrc   s                @r   rG   z%Win32ShellCommandController.__enter__   s{   h=2B/dk4<V	'59F1H2Iy)x )**F#]622FN$(F!*.F': : : : : $/;#;#;#; Iy  @"HH	&'8':':I 1 3 3V\)5L5L !4)>@ @ , !/+++,
 (3{Q'?'?'?$	9#.;#;#;#;Hx -..J%--K#];77KN$,K!%.K"$-K!"6K.1AAO "S($o$[ 9 9L,,	. . (
 o''' !!!H	"""I$I&&& 	 #DKH$DLI !( 	(DO  &H%%% &H%%% 'I&&& 'I&&& 'I&&& 'I&&&  &H%%% &H%%% 'I&&& 'I&&& 'I&&& 'I&&&&' s   G,J   A)K)c                 \   t                      }t          d          }	  |            }|t          |t          j        |                    st          j                    |j        t          k    rd S t          |ddt          j        |          d           st          j                    t          |t                    r|
                    d          }t          |t                    st          d          t          |          dk    rd S  ||           t          |          dk    rt          ||t          |          t          j        |          d           s,t                      t          k    rd S t          j                    ||j        d          }t          |          dk    )Nr   T utf_8z$internal stdin function string error)r   GetExitCodeProcessr[   r\   r]   r`   STILL_ACTIVE	WriteFile
isinstanceunicodeencodestrRuntimeErrorlenGetLastErrorERROR_NO_DATA)rF   handlehprocessfuncstdout_funcexitCodebytesWrittendatas           r   _stdin_threadz)Win32ShellCommandController._stdin_threadF  s   77Qxx-	1 466D |)(FL4J4JKK , /+++>\11F Q\22D: : , /+++ $(( ,{{7++ dC(( K"#IJJJ 4yyA~~ K d))q.. s4yy\22D: : , $~~66 /+++L.//0 d))q..I-	1r   c                 X   t          j        d          }	 t          d          }t          ||dt          j        |          d           s.t                      }|t          k    rd S t          j                    |j        d|j                 } ||	                    dd                     )Ni   Tr   r|   replace)
r[   create_string_bufferr   ReadFiler\   r   ERROR_BROKEN_PIPEr]   r`   decode)rF   r   r   r   	bytesReadless          r   _stdout_threadz*Win32ShellCommandController._stdout_threadx  s    *400	/aIFD$Y//7 7 ,!^^***F /+++
1Y_,-AD'9--...	/r   Nc                 R   ||||                                  S || j        rt          d          d}g }|r.t          j        | j        | j        | j        j        ||f          }|	                    t          j        | j
        | j        |f                     | j        s9||}|	                    t          j        | j
        | j        |f                     t          | j        j                  dk    rt          j                    ||                                 |D ]}|                                 t%          | j        j        t&                    t(          k    rt          j                    |D ]}|                                 ||                                 dS 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argsr9   )
_run_stdiorT   r   	threadingThreadr   rf   rh   r.   appendr   re   rg   ResumeThreadr/   r[   r]   startWaitForSingleObjectINFINITEWAIT_FAILEDjoin)rF   r   
stdin_funcstderr_funcstdin_threadthreadsthreads          r   runzWin32ShellCommandController.run  s    :#5+:M??$$$"t}"  7 8 8 8
  	:$+43E&*k4?3K *K&9: : :L 	y't/B*.,)DF F F 	G 	G 	G} 	K")NN9+43F.2lK-HJ J J K K K /00J>>/####    	 	FLLNNNNt7BB   /### 	 	FKKMMMM # $#r   c                    t          j        t          j                                                  }t          |d          }|t          k    rt          j                    |t          k    rt          dd           dS t          j        d          }t          d          }t          dd           t          ||dt          j        |          d          st          j                    t          |           |j        }|                    d	d
          }|                    dd
          }t          t%          |          dz   d           |S )z>Use the raw Win32 handle of sys.stdin to do non-blocking readsd   .r{   )endNr6   r   ?z

 )msvcrtget_osfhandlesysstdinfilenor   r   r[   r]   WAIT_TIMEOUTprintr   r   r   r\   FlushConsoleInputBufferr`   r   repr)rF   r   resultr   r   s        r   _stdin_raw_nonblockz/Win32ShellCommandController._stdin_raw_nonblock  s0   
 %ci&6&6&8&899$VS11[  /###|###24.s33DaI#2FD#Y//7 7 (o''' $F+++:D<<--D<<d++D$t**s"++++Kr   c                     	 t           j                            d          }|                    dd          }|S # t          $ r}|j        t          k    rY d}~dS |d}~ww xY w)zUse a blocking stdin readr5   r   r   N)r   r   readr   WindowsErrorwinerrorr   )rF   r   wes      r   _stdin_raw_blockz,Win32ShellCommandController._stdin_raw_block  sr    

	9>>!$$D<<d++DK 	 	 	{m++ttttt 	s   69 
A AAA c                 z    t          |dt          j                   t          j                                         dS zWrites the string to stdoutr{   )r   fileN)r   r   stdoutflushrF   r   s     r   _stdout_rawz'Win32ShellCommandController._stdout_raw  3    aRcj))))
r   c                 z    t          |dt          j                   t          j                                         dS r   )r   r   stderrr   r   s     r   _stderr_rawz'Win32ShellCommandController._stderr_raw  r   r   c                     | j         r!|                     | j        | j                  S |                     | j        | j        | j                  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.
        )r   r   )r   r   r   )rT   r   r   r   r   rE   s    r   r   z&Win32ShellCommandController._run_stdio  sb      = 	488$*:!%!6  8 8 8 88$*:!%!6"&"2  4 4 4r   c                 V   | j         rt          | j                    d | _         | j        rt          | j                   d | _        | j        rt          | j                   d | _        | j        ;t          | j        j                   t          | j        j                   d | _        d S d S rI   )rf   rq   re   rg   rh   r.   r/   rJ   s       r   rN   z$Win32ShellCommandController.__exit__  s    ; 	$$$DK< 	 %%%DL< 	 %%%DL?&0111/000"DOOO '&r   )TrW   )r   r   r   rO   rU   rG   r   r   r   r   r   r   r   r   rN   r   r   r   rQ   rQ      s         6
! 
! 
! 
!^ ^ ^@01 01 01d/ / /"1  1  1  1 f  >  "  
  
4 4 4:# # # # #r   rQ   rS   r=   c                     t                      5 }|d|d| } t          |           5 }|                                 ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   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 z &&")r<   rQ   r   )rS   rA   sccs      r   systemr   #  s      
 4'+ttSS1C(-- 	GGIII	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                 s3   A"A
A"
A	A"A	A""A&)A&__main__zTest starting!z	python -izTest finished!)JrO   r?   r   r   r[   r   r   ctypes.wintypesr   r   r   r   r   r	   r
   r   LPDWORDLPHANDLE	ULONG_PTR	Structurer   LPSECURITY_ATTRIBUTESr   LPSTARTUPINFOr-   LPPROCESS_INFORMATIONERROR_HANDLE_EOFr   r   r_   rm   rn   CREATE_NEW_CONSOLEro   r~   r   r   r   rl   ENABLE_ECHO_INPUTENABLE_LINE_INPUTENABLE_PROCESSED_INPUTwindllkernel32r   argtypesrestypeCreateFileW
CreateFilerZ   CreateProcessWrp   r}   rk   r   r   r   GetConsoleModeSetConsoleModer   r   rj   r^   rq   shell32CommandLineToArgvWc_int	LocalFreer<   rQ   r   r   r   r   r   r   r   <module>r      s                                                
'%..76??GENN	* * * * *&* * * *   344 ' ' ' ' '&" ' ' '& $$' ' ' ' '&* ' ' '
   344         "     }%2  ]#/
ufeUFK
 
 ]#.
wvu&
 
 &5!7,AtUFG]   ]+> %w/  !  M*<   "  }%2  =!*VUGV<  M",	feWf=	 	 '6!7+  '6!5/   -0H $*8   "&  m,@  &  #  -(8"FFHtU  }-B !' 6  #  m$0x  ]*= &(=(=>  $WW--  M",	X	 	 #  #  #  #  #  #  #  # Lb# b# b# b# b# b# b# b#J     . z	E

F;	E
	 r   