
    BPcj'                     >   d Z ddlZddlZddlmZ ddlmZmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ ej                            d
          Zeej        dk    rdZndZ G d de          Z G d de          Zd Zd Zd"dZd Zd Zd Zd Zd Zd#dZ d$d Z!d! Z"dS )%a]  
This API provides methods for calling Inkscape to execute a given
Inkscape command. This may be needed for various compiling options
(e.g., png), running other extensions or performing other options only
available via the shell API.

Best practice is to avoid using this API except when absolutely necessary,
since it is resource-intensive to invoke a new Inkscape instance.

However, in any circumstance when it is necessary to call Inkscape, it
is strongly recommended that you do so through this API, rather than calling
it yourself, to take advantage of the security settings and testing functions.

    N)which)PopenPIPE)TemporaryDirectory)List)ElementTree   )SvgDocumentElementINKSCAPE_COMMANDwin32zinkscape.exeinkscapec                       e Zd ZdZdS )CommandNotFoundzCommand is not foundN)__name__
__module____qualname____doc__     //usr/share/inkscape/extensions/inkex/command.pyr   r   6   s        r   r   c                   h     e Zd ZU dZeed<   	 eed<   	 eed<   	 eed<   	 eed<   	 d
 fd	Zd	 Z	 xZ
S )ProgramRunErroraI  A specialized ValueError that is raised when a call to an external command fails.
    It stores additional information about a failed call to an external program.

    If only the ``program`` parameter is given, it is interpreted as the error message.
    Otherwise, the error message is compiled from all constructor parameters.program
returncodestderrstdout	argumentsNc                     || _         || _        || _        || _        || _        t                                          t          |                      d S N)r   r   r   r   r   super__init__str)selfr   r   r   r   args	__class__s         r   r!   zProgramRunError.__init__P   sJ    $T#####r   c                 b    | j         | j        S d| j          d| j         d| j         d| j         S )NzReturn Code: z: 
z
args: )r   r   r   r   r$   )r#   s    r   __str__zProgramRunError.__str__X   sU    ?"<#DO # #t{ # #dk # #y# #	
r   )NNNN)r   r   r   r   r"   __annotations__intr   r!   r(   __classcell__)r%   s   @r   r   r   :   s         Q Q LLL4OOO)KKK*KKK*OOO$ $ $ $ $ $
 
 
 
 
 
 
r   r   c                    t           j                            |           r!t           j                            |           r| S 	 t          j        dk    r5t          | t           j        d         dz   t           j        z             }|r|S n# t          $ r Y nw xY w	 t          |           }|r|S n# t          $ r Y nw xY wt          d|  d          )zL
    Attempt different methods of trying to find if the program exists.
    r   PATH;)pathzCan not find the command: '')osr/   isabsisfilesysplatformwarlockenvironcurdirImportErrorr   )r   progs     r   r   r   a   s     
w}}W "'.."9"9 <7""7F);c)ABI)MNNND    w 	K	    BBBB
C
CCs%   AB 
BBB- -
B:9B:c                    t          j        j        | }t           j                            |          r|S t	          |d          5 }t          | t                    rt          |           } t          | d          r| 	                    |           n:t          | t                    r|	                    |            nt          d          ddd           n# 1 swxY w Y   |S )z#Writes an svg to the given filenamewbwritez'Not sure what type of SVG data this is.N)r1   r/   joinr3   open
isinstancer
   r   hasattrr=   bytes
ValueError)svgfilenamefhls      r   	write_svgrG      s   w|X&H	w~~h 	h		 	Hc-.. 	#c""C3   	HIIcNNNNU## 	HIIcNNNNFGGG	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H Os   BCCCFc                     t          | t          t          f          rD| \  } }d| z   } t          |           dk    r|sd| z   } |du r| S |du rdS |  dt	          |           S t	          |           S )z4Convert a python argument to a command line argument-   TFN=)r@   tuplelistlenr"   )argoldievals      r   to_argrR      s    #t}%% 	#
cCis88a<<<)C$;;J%<<4""C"""s88Or   c                    | g}|                     dd          |                                D ]\  }}|                    dd                                          }t	          |t
                    rt          |          }nt	          |t                    s|g}|D ]'}|                    t          ||f                     (|fd|D             z  }d |D             S )a  Compile arguments and keyword arguments into a list of strings which Popen will
    understand.

    :param prog:
        Program executable prepended to the output.
    :type first: ``str``

    :Arguments:
        * (``str``) -- String added as given
        * (``tuple``) -- Ordered version of Kwyward Arguments, see below

    :Keyword Arguments:
        * *name* (``str``) --
          Becomes ``--name="val"``
        * *name* (``bool``) --
          Becomes ``--name``
        * *name* (``list``) --
          Becomes ``--name="val1"`` ...
        * *n* (``str``) --
          Becomes ``-n=val``
        * *n* (``bool``) --
          Becomes ``-n``

    :return: Returns a list of compiled arguments ready for Popen.
    :rtype: ``list[str]``
    rP   F_rI   c                 4    g | ]}|t          |          S r   )rR   ).0posrP   s     r   
<listcomp>zto_args.<locals>.<listcomp>   s$    JJJC#/VC///r   c                     g | ]}||S r   r   )rV   rO   s     r   rX   zto_args.<locals>.<listcomp>   s    333C3?C???r   )	popitemsreplacestripr@   rL   rM   appendrR   )r:   positionalsr   r$   rO   valuerQ   rP   s          @r   to_argsra      s    6 6DMM'5))Eoo'' 	3 	3
Ukk#s##))++eU## 	KKEEE4(( 	GE 	3 	3CKKSz5112222	3 	JJJJ;JJJJD3343333r   c           
      z    t          | g|R i t          t          |                                                    S )z_same as :func:`to_args`, but keyword arguments are sorted beforehand

    .. versionadded:: 1.2)ra   dictsortedr[   )r:   r_   r   s      r   to_args_sortedre      s<     4I+IIIfY__5F5F.G.G)H)HIIIr   c                    |                     dd           }t          |t                    r|                    d          }|rt          nd }t          t          |           g|R i |}i }t          j        dk    rd|d<   t          |fd|t          t          d|5 }|
                    |          \  }}|j        d	k    r|cd d d            S t          | |j        |||          # 1 swxY w Y   d S )
Nstdinutf-8r   i   creationflagsF)shellrg   r   r   )inputr   )rZ   r@   r"   encoder   ra   r   r4   r5   r   communicater   r   )r   r$   kwargsrg   inpipeprocessr   r   s           r   _callrq      sv   JJw%%E% &W%%$TTF5>>3D333F33DF
|w",	

 
 
 
 Q 
"..U.;;""Q Q Q Q Q Q Q Q gw'9664PPPQ Q Q Q Q Q Q Q Q Qs   &C'C''C+.C+c                     |                     dd          }t          | g|R i |}|s;t          |t                    r&|                    t
          j        j        pd          S |S )a  
    Generic caller to open any program and return its stdout::

        stdout = call('executable', arg1, arg2, dash_dash_arg='foo', d=True, ...)

    Will raise :class:`ProgramRunError` if return code is not 0.

    Keyword arguments:
        return_binary: Should stdout return raw bytes (default: False)

            .. versionadded:: 1.1
        stdin: The string or bytes containing the stdin (default: None)

    All other arguments converted using :func:`to_args` function.
    return_binaryFrh   )rZ   rq   r@   rB   decoder4   r   encoding)r   r$   rn   binaryr   s        r   callrw      sp    " ZZ//F7,T,,,V,,F  =j// =}}SZ0;G<<<Mr   c                 .    t          t          | g|R i |S )zS
    Call Inkscape with the given svg_file and the given arguments, see call()
    )rw   INKSCAPE_EXECUTABLE_NAME)svg_filer$   rn   s      r   r   r     s%     ((DTDDDVDDDr   r   c           	      r   t          d          5 }t          | |d          }|rd|fnd}|dz  }t          ||dd                    |          	           t	          |d
          5 }|                                cddd           cddd           S # 1 swxY w Y   	 ddd           dS # 1 swxY w Y   dS )z
    Executes a list of commands, a mixture of verbs, selects etc.

    inkscape_command('<svg...>', ('verb', 'VerbName'), ...)
    zinkscape-command)prefixz	input.svgselectN)FileSaveFileQuitTr.   )batch_processverbrb)r   rG   r   r>   r?   read)rD   r}   verbstmpdirrz   rF   s         r   inkscape_commandr     sb    
#5	6	6	6 &S&+66'-7(F##4))6CHHUOOLLLL(D!! 	S88::	 	 	 	 	 	 	       
	 	 	 	 	 	 	 	 	                 s6   AB,&B:B,B	B,B	B,,B03B0snapshotpng`   c                     t          | ||dz             }t          j                            ||dz   t	          |                                          z             }t          |f|||d| |S )z
    Take a snapshot of the given svg file.

    Resulting filename is yielded back, after generator finishes, the
    file is deleted so you must deal with the file inside the for loop.
    z.svg.)
export_dpiexport_filenameexport_type)rG   r1   r/   r>   r"   lowerr   )rD   dirnamenameextdpirn   rz   ext_files           r   take_snapshotr   !  s|     gtf}55Hw||GTCZ#c((..2B2B%BCCH ( OU   Or   c                  h    	 t          t          t                              S # t          $ r Y dS w xY w)z4Return true if the Inkscape executable is available.F)boolr   ry   r   r   r   r   is_inkscape_availabler   0  s@    E233444   uus    # 
11)F)Nr   )r   r   r   )#r   r1   r4   shutilr   r6   
subprocessr   r   tempfiler   typingr   
lxml.etreer   elementsr
   r7   getry   r5   IOErrorr   rC   r   rG   rR   ra   re   rq   rw   r   r   r   r   r   r   r   <module>r      s  &  
			 



 # # # # # # " " " " " " " " ' ' ' ' ' '       " " " " " " ( ( ( ( ( (:>>*<== #
|w#1  #-     g   $
 $
 $
 $
 $
j $
 $
 $
ND D DB  $   *4 *4 *4ZJ J JQ Q Q4  4E E E          r   