
    ceJc                        U 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m	Z	m
Z
mZ ddlmZ ddlmZ erddlZej        dk    rdndZej        e         ed	<   d
Zej        e         ed<    G d dej                  Z G d dej                  ZdedefdZdedefdZdedefdZdedefdZ	 	 d;dedej        eej         f         dej         de!def
dZ" G d d          Z#e
fdeded edefd!Z$e
fdeded eddfd"Z%d#de
fdeded$ed%ej&        e'         d edej(        eee'f         fd&Z)d#e
fdededed'ed$ed edefd(Z*d)d#dej+        ,                    d*          e
fdededed+ej-        ej                  d$edej&        ej        eef                  d,ed edej(        ej        eej         f         df         fd-Z.d)d#dej+        ,                    d*          e
fdededed+ej-        ej                  d$edej&        ej        eef                  d,ed edej(        ej        eej         f         df         fd.Z/d)ej+        ,                    d*          d#dd/ddfdededed+ej-        ej                  d0ed$edej&        ej        eef                  d1e!d2e!d3e!dej&        e#         fd4Z0dej+        ,                    d*          d5fd6Z1d<d7edej&        e         de!fd8Z2d=d:Z3dS )>zLaunch applications utilities.    N)	CONF_PATHLAUNCH_SCRIPTS_PATHWIN)is_program_installed)run_as_adminwin32nulz	/dev/nullDEVNULLz{package}-{level}-{index}.txtLOG_FILEc                   F    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   dS )CommandDetailsz5Dictionary with extra details about executed command.argsidcmdstdoutstderrN)__name__
__module____qualname____doc__str__annotations__int     ?lib/python3.11/site-packages/anaconda_navigator/utils/launch.pyr   r       sC         ??
IIIGGG	HHHKKKKKKKKr   r   c                      e Zd ZdZdddej                            d          efdededed	e	j
        e	j                 d
ede	j        e	j        eef                  dedede	j        e	j        ee	j        f         ef         fdZdS )
GetCommandz3Common interface for all `get_command_*` functions.r   appN~root_prefixprefixcommandextra_argumentspackage_nameenvironmentcwddefault_scripts_pathreturnc	                     dS )a  
        Generate script to launch application and return path to it.

        :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
        :param prefix: Conda prefix, which should be active.
        :param command: Actual command to launch application.
        :param extra_arguments: Additional arguments to attach to command.
        :param cwd: Custom working directory to launch application in.
        :param package_name: Name of the conda package, or alias of the external application.
        :param environment: Custom environment to launch application in.
        :param default_scripts_path: Root directory to store launch scripts in.
        :return: Path to generated launch script file.
        Nr   )	selfr!   r"   r#   r$   r%   r&   r'   r(   s	            r   __call__zGetCommand.__call__-   s      r   )r   r   r   r   ospath
expanduserr   r   typingIterableAnyOptionalMappingTupler   r,   r   r   r   r   r   *   s        == <> %EIw))#..(;   	
 $_VZ8   S)AB  #& 
fnS&*_5~E	F     r   r   valuer)   c                 `    |                      t          j        j        t          j                  S )z#Convert path to a posix-compatible.)replacer-   r.   sep	posixpathr6   s    r   to_posix_pathr<   G   s    ==im444r   c                     h d}h d|z  }t          |           |z  r$|D ]}|                     |d|           } d|  d} | S )z;Prepare argument which is safe to use in unix command line.>   "$\`>    &;<>|r@   r>   setr8   )r6   
to_replace	to_escape	characters       r   	safe_unixrM   L   sp    0E0E0EJ/M/M/MPZ/ZI
5zzI # 	? 	?IMM)-=)-=-=>>EEELr   c                     h d}t          |           |z  r0|                     dd                              dd          } d|  d} | S )z>Prepare argument which is safe to use in windows command line.>   rB   r>   %rC   rD   rE   rF   rG   r>   z""rO   z"^%"rH   )r6   rK   s     r   safe_windowsrP   [   sU    /W/W/WI
5zzI c4((00f==ELr   c                 L    t           rt          |           S t          |           S )z6Prepare argument which is safe to use in command line.)r   rP   rM   r;   s    r   safe_argumentrR   f   s&    
 #E"""Ur   Fr#   r&   default	recursivec                 H   d}	 |                      d|          }|dk     rn|                      d|          }| |dz   |         }|dz  }|                    ||          }||}at          |          }| d|         |z   | |d         z   } |}|s|t          |          z  }| S )a  
    Update command with environment variables.

    :param command: Original command to update with environment variable values.
    :param environment: Environment variables to inject into command.

                        :code:`None` values won't be expanded.
    :param default: Value to insert for all unknown variables in `command`.
    :param recursive: Allow recursive expand of the values.
    :return: String with expanded environment.
    r   Tz${}      N)findgetr   len)	r#   r&   rS   rT   cursorstartstopenvironment_keyenvironment_values	            r   expand_environmentra   m   s    " F-\\$//199LLe,,&uqy~6	(3(Q(Q$F 122&5&/$55F 	-c+,,,F%-( Nr   c                      e Zd ZdZdZ	 	 ddedej        dej	        e         dej	        e         ddf
d	Z
edej        fd
            Zedefd            Zedefd            Zedej	        e         fd            Zedej	        e         fd            Zedej	        e         fd            Zedej	        e         dej	        e         fd            ZddZdS )RunningProcessa  
    Minimal description of a process launched from the Navigator.

    Common example of such process - anything started from the Home page tiles.

    :param package: Name of the Conda package, or alias of a launched application.
    :param process: :class:`~subprocess.Popen` instance, which is used to launch the application.
    :param stdout: Path to a file with captured `stdout`.
    :param stderr: Path to a file with captured `stderr`.
    )__birth	__package	__process__return_code__stderr__stdoutNpackageprocessr   r   r)   c                     |t           k    rd}|t           k    rd}|| _        || _        d| _        || _        || _        t          j                                        | _        dS )z1Initialize new :class:`~RunningProcess` instance.N)	r
   _RunningProcess__package_RunningProcess__process_RunningProcess__return_code_RunningProcess__stdout_RunningProcess__stderrdatetimeutcnow_RunningProcess__birth)r+   rj   rk   r   r   s        r   __init__zRunningProcess.__init__   sb     WFWF,39@37<B<B8@8I8P8P8R8Rr   c                 N    t           j                                         | j        z
  S )zCurrent age of the application.)rr   rs   rt   r+   s    r   agezRunningProcess.age   s       ''))DL88r   c                     | j         S )z>Name of the Conda package, or alias of a launched application.)rm   rw   s    r   rj   zRunningProcess.package   s     ~r   c                     | j         j        S )zPID of the process.)rn   pidrw   s    r   r{   zRunningProcess.pid   s     ~!!r   c                 Z    | j         | j                                        | _         | j         S )z"Current status of the application.)ro   rn   pollrw   s    r   return_codezRunningProcess.return_code   s,     %!%!4!4!6!6D!!r   c                 6    |                      | j                  S zContent of the `stdout` log.)_RunningProcess__readrq   rw   s    r   r   zRunningProcess.stderr        {{4=)))r   c                 6    |                      | j                  S r   )r   rp   rw   s    r   r   zRunningProcess.stdout   r   r   r.   c                     | dS 	 t          | d          5 }|                                cddd           S # 1 swxY w Y   dS # t          $ r Y dS w xY w)zRead content of the file.Nrt)openreadOSError)r.   streams     r   __readzRunningProcess.__read   s     <4	dD!! %V{{}}% % % % % % % % % % % % % % % % % % 	 	 	44	s,   A 7A ;A ;A 
AAc                     t          j        t           j        t                   t	          t
          | j        | j        g                    D ]'}	 t          j	        |           # t          $ r Y $w xY wdS )zRemove all temporary content.N)r0   castr1   r   filterboolrp   rq   r-   remover   )r+   r.   s     r   cleanupzRunningProcess.cleanup   sy     K 4fTDMSWS`Ca6b6bcc 	 	D	$   	 	s   A""
A/.A/)NN)r)   N)r   r   r   r   	__slots__r   
subprocessPopenr0   r3   ru   propertyrr   	timedeltarx   rj   r   r{   r~   r   r   staticmethodr   r   r   r   r   rc   rc      s       	 	 _I ,0+/S SS  %S OC(	S
 OC(S 
S S S S( 9X' 9 9 9 X9     X "S " " " X" "V_S1 " " " X" *, * * * X* *, * * * X* 	V_S) 	foc.B 	 	 	 \	     r   rc   r!   r"   r(   c                 r   t           j                            |          }t           j                            |           } t           j                            |          }|| k    r=t           j                            |t           j                            |                    }t          j        |d           |S )a  
    Return path to directory, where all launch scripts should be placed.

    This directory can also be used for the application logs.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to directory, where launch script should be placed.
    T)exist_ok)r-   r.   abspathjoinbasenamemakedirs)r!   r"   r(   results       r   get_scripts_pathr      s     '//"677F'//+..KW__V$$Ffbg&6&6v&>&>??K&&&&Mr   c                 
   t          | ||          }t          j        |          D ][}|                    d          s	 t          j        t          j                            ||                     L# t          $ r Y Xw xY wdS )a   
    Try to remove output, error logs for launched applications.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param default_scripts_path: Root directory to store launch scripts in.
    r!   r"   r(   z.txtN)r   r-   listdirendswithr   r.   r   r   )r!   r"   r(   	logs_root	file_paths        r   remove_package_logsr     s     &1  I Z	**  	!!&)) 		Ibgll9i889999 	 	 	D	 s    2A33
B ?B r   r%   id_c                 *   t          | ||          }t                              |d|          }t                              |d|          }|}t          t	          j        |                    }t          j        d          D ]F}t                              |d|          }t                              |d|          }||vr||vr nG|rB| r@t          j        	                    ||          }t          j        	                    ||          }|||fS )a  
    Return the package log names for launched applications.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param package_name: Name of the conda package, or alias of the external application.
    :param id_: Application session identifier.

                Used to create different names for different application launch sessions.
    :param default_scripts_path: Root directory to store launch scripts in.
    r   out)rj   levelindexerrNrX   )r]   )
r   r   formatrI   r-   r   	itertoolscountr.   r   )	r!   r"   r%   r   r(   r   stdout_log_pathstderr_log_pathuseds	            r   get_package_logsr   $  s   $ &1  I $??<uTW?XXO#??<uTW?XXO
{ #BJy$9$9 : :?+++ 	 	C&ool%WZo[[O&ool%WZo[[Ot++/2M2M C+ C',,y/BB',,y/BBOS00r   	extensionc                 x   t          | ||          }d}t          r&dt          j        j                                         }t          j                            || |           }t          |d|          5 }	|	
                    |           ddd           n# 1 swxY w Y   t          j        |d           |S )a  
    Create new application launching script file.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Content of the script file.
    :param extension: Extension for the script file (`.bat`, `.sh`)
    :param package_name: Name of the conda package, or alias of the external application.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r   zutf-8cpwt)encodingN  )r   r   ctypescdllkernel32GetACPr-   r.   r   r   writechmod)
r!   r"   r#   r   r%   r(   scripts_rootr   r   r   s
             r   create_app_run_scriptr   N  s   & )1  L H
 87,335577 W\\,<0L0L0LMMI	i	1	1	1 VW               HYs   8BB!Br   r    r$   r'   c                    t          | |||          \  }}	}
t          dt          d          t          d          ff                              ||          }t	          |||| d          }t
          j                            | dd          }|D ]$}|d	t          t          |                     z  }%d
                    ddt          j
        j                                         dt          |           d	t          |           | dt          |           dt          |	           dg          }t          | ||d||          }t          j        t          j        z  ||d||
|||	dfS )a  
    Generate script to launch application and return path to it.

    This function is optimized to run on Windows.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param cwd: Custom working directory to launch application in.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r!   r"   r%   r(   )zPstart cmd.exe /K "${CONDA_ROOT_PREFIX}\\Scripts\\activate.bat" "${CONDA_PREFIX}"zNstart cmd.exe \K "${CONDA_ROOT_PREFIX}\Scripts\activate.bat" "${CONDA_PREFIX}"zstart powershell.exe -ExecutionPolicy ByPass -NoExit -Command  "& '{CONDA_ROOT_PREFIX}\\shell\\condabin\\conda-hook.ps1' ; conda activate '{CONDA_PREFIX}'"zstart powershell.exe -ExecutionPolicy ByPass -NoExit -Command "& '${CONDA_ROOT_PREFIX}\shell\condabin\conda-hook.ps1' ; conda activate '${CONDA_PREFIX}'"PREFIXCONDA_PREFIXCONDA_ROOT_PREFIXr#   r&   ScriptsactivaterB   
z	@echo offzchcp zcall  > 2> z.batr!   r"   r#   r   r%   r(   )creationflagsr'   envr   r   r   r   r   )r   dictr   rZ   ra   r-   r.   r   rP   r   r   r   r   r   r   CREATE_NO_WINDOWCREATE_NEW_PROCESS_GROUPr!   r"   r#   r$   r%   r&   r'   r(   r   r   r   r   extra_argumentscriptr   s                  r   get_command_on_winr   u  s   8 -=!1	- - -)O_c 	

 y  u 		
   s7G " !"!,
 
  G GLLiDDH * ; ;:|C$7$788:::))/$++--// 	@X&&??f)=)=??WWl?33WW_8U8UWW
  F +!1  I $4z7ZZ 
 !! 	
 
r   c                    t          | |||          \  }}	}
t          |||| d          }t          j                            | dd          }|D ]$}|dt          t          |                     z  }%d                    dd	t          |           dt          |           | d
t          |           dt          |	           dg          }t          | ||d||          }||d||
|||	dfS )a  
    Generate script to launch application and return path to it.

    This function is optimized to run on Linux/OS X.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param cwd: Custom working directory to launch application in.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param default_scripts_path: Root directory to store launch scripts in.
    :return: Path to generated launch script file.
    r   r   r   binr   rB   r   z#!/usr/bin/env bashz. r   r   r   z.shr   )r'   r   r   )r   ra   r-   r.   r   rM   r   r   r   s                  r   get_command_on_unixr     so   8 -=!1	- - -)O_c !"!,
 
  G GLLeZ@@H * 8 87y^!4!455777))6Yx  669V#4#466QQi00QQY5O5OQQ
	  F +!1  I   !! 	 	r   Tworking_directoryleave_path_alone	non_condaas_adminc
           	         t          |t                    r|f}t          }
t          rt          }
 |
| ||||||          \  }}|d         }t          rDdt          |           }|	r0t          |          rt          j        t          j	        d          S dS t          |t          j        |fi ||d         |d                   S )	aJ  
    Handle launching commands from projects.

    :param root_prefix: Path to root (base) conda prefix. Used to activate `prefix`.
    :param prefix: Conda prefix, which should be active.
    :param command: Actual command to launch application.
    :param extra_arguments: Additional arguments to attach to command.
    :param working_directory: Custom working directory to launch application in.

                              If not provided - home directory will be used.
    :param package_name: Name of the conda package, or alias of the external application.
    :param environment: Custom environment to launch application in.
    :param as_admin: Launch application with admin rights.

                     This breaks function result (changes it to :code:`True`/:code:`None`).
    :return: Description of the launched process.
    )r!   r"   r#   r$   r%   r&   r'   r   zcmd.exe /C TNr   r   )rj   rk   r   r   )
isinstancer   r   r   r   rP   r   r0   r   r2   rc   r   r   )r!   r"   r#   r$   r   r%   r&   r   r   r   get_command
popen_dict
extra_argsr   s                 r   launchr   &  s    : /3'' -*, 3K
 )( )['!  J
 6"D
 1\$//11 	D!! 5{6:t4444 4444(#(#	   r   r   c                    |}t           j        dk    r'| r
d|  d| d}nd}t          j        |d|           dS t          j        dk    r| rd	d
lm} |j        }d| d|  d| d}nd}t           j	        
                    t          d          }t          |d          5 }|                    |           ddd           n# 1 swxY w Y   t          j        |d           t          j        |gd|           dS t!          d          r.| rddddd|  dd| g}ng d}t          j        ||           dS t!          d          r+| rddd|  dd| g}ndg}t          j        ||           dS dS )z
    Open command prompt console and optionally activate the environment.
    optionally pass an application to be launched in terminal such as python,
    ipython, or jupyter as when called from py_in_console()
    ntzstart cmd.exe /k "activate "z" & r>   zstart cmd.exeT)shellr'   darwinr   	CONDA_APIzO#!/usr/bin/osascript
tell application "Terminal"
    activate
    do script ". z /bin/activate && conda activate z; z"
end tell
bashza.toolwNr   gnome-terminalz-xz-cz$bash --init-file <(echo ". activate z;"))r   -er   )r'   xtermr   )r-   namer   r   sysplatform anaconda_navigator.api.conda_apir   ROOT_PREFIXr.   r   r   r   r   r   callr   )	r   r   term_commandr'   r   r   
rootprefixfnamefs	            r   consoler   g  sc    C	w$ 	"NNN|NNNCC!CDc222222		!	! 	BBBBBB".J 	  ?G	  KW	  CC CY11% 	GGCLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	
t555555 011 	+ 
7$H8HHH''' 766Sc******!'** 	+  H8HHH'''	 iSc******	+ 	+s   B??CCprogc                     ddl m}  |            p                    d          | dv rg d}n| dv rdd	g}n| g}t          fd
|D                       S )z"Check if program exists in prefix.r   )AnacondaAPIroot)r   )notebookjupyter notebook)r   zipython-notebookzjupyter-notebook)ipythonzjupyter consoler  jupyterc              3   J   K   | ]}                     |           duV  dS ))r"   pkgN)conda_package_version).0r  apir"   s     r   	<genexpr>zcheck_prog.<locals>.<genexpr>  sO         	!!S!99E     r   )#anaconda_navigator.api.anaconda_apir   conda_get_prefix_envnameany)r   r"   r   pkgsr  s    `  @r   
check_progr    s    ??????
+--C@s333@@F///CCC	/	/	/9%v          r   pythonc                     t          ||           st          d| d|            |dk    rd}n1|dk    rd}n(d|v r"d}d	d
lm} t	          |j        | |d           dS d}t          | |           dS )zk
    Run (i)python in a new console.

    It optionally run activate first on the given env name/path.
    z&Program not available in environment: z, r  z	python -ir  z
ipython -ir   r  r   r   T)r!   r"   r#   r   N)r   r   )r  RuntimeErrorr   r   r   r   r   )r   r   r   r   s       r   py_in_consoler    s     dH%% XVDVVHVVWWWx				t		 >>>>>>!-!		
 	
 	
 	
 	XC000000r   )NF)N)Nr  )4r   rr   r   r-   r:   r   r   r0   anaconda_navigator.configr   r   r   !anaconda_navigator.utils.programsr   $anaconda_navigator.utils.win_elevater   r   r   r
   Finalr   r   r   	TypedDictr   Protocolr   r<   rM   rP   rR   r4   r2   r   ra   rc   r   r   r3   r   r5   r   r   r.   r/   r1   r   r   r   r   r  r  r   r   r   <module>r     s   % $ $      				         



  I I I I I I I I I I B B B B B B = = = = = =  MMM (+|w'>'>UU[c	 P P P=&,s
 = = =    V%          :5 5 5 5 5 5
S S               #	& &&^CO4& & 	&
 	& & & &RU U U U U U U Uv %8  " 		   : %8  " 
	   >  $ 3'1 '1'1'1 '1 
		'1
 '1 \#sC- '1 '1 '1 '1^  3$ $$$ $ 	$
 $ $ 	$ $ $ $V 8:!AE7%%c**$7b bbb b  4	b
 b _V^CH%=>b b "b \&.fj13CCDb b b bR 8:!AE7%%c**$7I III I  4	I
 I _V^CH%=>I I "I \&.fj13CCDI I I I` 8:!#!3!3C!8!8!AE!%> >>> >  4	>
 > > _V^CH%=>> > > > _^$> > > >B RW-?-?-D-DSU >+ >+ >+ >+B S &/#"6 $    (1 1 1 1 1 1r   