
    BPc3                     H   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZ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 d	dlmZ ddlmZmZ 	  G d dee	e          Zd Zd Z e  eed                    e_         e  eed                    e_        dS )z?
Provide a way to load lxml attributes with an svg API on top.
    N)etree   )ConditionalRule)ISVGDocumentElement)DeprecatedSvgMixin	deprecate)discover_unit
parse_unit   )ElementList)BoundingBox)StyleSheets)BaseElement)StyleElement)OptionalListFc            	       2   e Zd ZU dZdZeed<   	 d Zd Zd Z		 	 d+de
d	ee         d
eee
                  fdZd Zd Zd Z	 d,de
fdZd-dZd Z	 d.de
fdZd/dZed             Zed             Zed             Zed             Zd Zedefd            Zedefd            Zedefd             Z edefd!            Z!ed"             Z"ed#             Z#d0d%Z$edefd&            Z%ed'             Z&ed(             Z'ed)             Z(ed*             Z)dS )1SvgDocumentElementz6Provide access to the document level svg functionalitysvg	selectionc                 X    d | _         d| _        t          |           | _        i | _        d S )N)        r   )current_layerview_centerr   r   idsselfs    5/usr/share/inkscape/extensions/inkex/elements/_svg.py_initzSvgDocumentElement._init=   s,    !%$T**    c                 N    t          j        t          j        |                     S )zConvert document to string)r   tostringElementTreer   s    r   r"   zSvgDocumentElement.tostringC   s    ~e/55666r    c                 l    | j         s't          |                     d                    | _         | j         S )z$Returns a set of unique document idsz//@id)r   setxpathr   s    r   get_idszSvgDocumentElement.get_idsG   s.    x 	04::g..//DHxr    Nprefixsize	blacklistc           	         |                                  }|Ft          t          j        t          j        t          |          pd                    dz   d          }||                    |           d}d|z  dz
  }d|z  }|||v r?|t          t          t          j	                    |z  |z
            |z             z   }|;||v ?| j
                            |           |S )a  Generate a new id from an existing old_id

        The id consists of a prefix and an appended random integer with size digits.

        If size is not given, it is determined automatically from the length of
        existing ids, i.e. those in the document plus those in the blacklist.

        Args:
            prefix (str): the prefix of the new ID.
            size (Optional[int], optional): number of digits of the second part of the
                id. If None, the length is chosen based on the amount of existing
                objects. Defaults to None.

                .. versionchanged:: 1.1
                    The default of this parameter has been changed from 4 to None.
            blacklist (Optional[Iterable[str]], optional): An additional iterable of ids
                that are not allowed to be used. This is useful when bulk inserting
                objects.
                Defaults to None.

                .. versionadded:: 1.2

        Returns:
            _type_: _description_
        Ni  r      
   )r'   maxmathceillog10lenupdatestrintrandomr   add)r   r(   r)   r*   r   new_id_from_tos           r   get_unique_idz SvgDocumentElement.get_unique_idM   s    > llnn<tyCHH,<!=!=>>BAFFD JJy!!!D1$hn#c#fmoo&=&C"D"Ds"JKKKF n# 	Vr    c                 r    t          dt          | j                  fdt          | j                  f          S )z"Gets the page dimensions as a bboxr   )r   floatviewbox_widthviewbox_heightr   s    r   get_page_bboxz SvgDocumentElement.get_page_bboxz   s9    d())*Qd6I0J0J,K
 
 	
r    c                 N    |                      | j        j        d          }|| S |S )z$Returns the currently selected layerzsvg:g)getElementById	namedviewr   )r   layers     r   get_current_layerz$SvgDocumentElement.get_current_layer   s+    ##DN$@'JJ=Kr    c                 ,    |                      |          S )z:Gets a single element from the given xpath or returns None)findone)r   r&   s     r   
getElementzSvgDocumentElement.getElement   s    ||E"""r    *Feidc                     |J|sH|                     d          r|                                dd         n|}|                    d          }|                     d| d| d          S )	a  Get an element in this svg document by it's ID attribute.

        Args:
            eid (str): element id
            elm (str, optional): element type, including namespace, e.g. ``svg:path``.
                Defaults to "*".
            literal (bool, optional): If ``False``, ``#url()`` is stripped from ``eid``.
                Defaults to False.

                .. versionadded:: 1.1

        Returns:
            Union[BaseElement, None]: found element
        Nzurl(r,   #//z[@id=""])
startswithstriplstriprH   )r   rJ   elmliterals       r   rB   z!SvgDocumentElement.getElementById   sn    " ?7?'*~~f'='=F#))++ad##3C**S//C6C66s666777r    c                 :    |                      d| d| d          S )z0Get an element by it's inkscape:label (aka name)rN   z[@inkscape:label="rO   )rH   )r   namerS   s      r   getElementByNamez#SvgDocumentElement.getElementByName   s(    CCCC4CCCDDDr    c                 p    |                      t          d|                                                     S )zGet elements by it's class name.)r&   r   to_xpath)r   
class_names     r   getElementsByClassz%SvgDocumentElement.getElementsByClass   s3     zz/*:j*:*:;;DDFFGGGr    
xlink:hrefc                     |dk    r|                      d| d          S |dk    r|                      d| d          S |dk    r|                      d| d          S d	S )
av  Get elements that reference the element with id eid.

        Args:
            eid (str): _description_
            attribute (str, optional): Attribute to look for.
                Valid choices: "xlink:href", "mask", "clip-path".
                Defaults to "xlink:href".

                .. versionadded:: 1.2

        Returns:
            Any: list of elements
        r]   z//*[@xlink:href="#rO   maskz//*[@mask="url(#z)"]z	clip-pathz//*[@clip-path="url(#Nr&   )r   rJ   	attributes      r   getElementsByHrefz$SvgDocumentElement.getElementsByHref   s      $$:::3:::;;;&  ::9999:::+%%::>c>>>??? &%r    c                 T    d| d}||dz   |z   }|                      d| d          S )z%Get elements by a style attribute urlzurl(#)N:z//*[contains(@style,"z")]r`   )r   rJ   styleurls       r   getElementsByStyleUrlz(SvgDocumentElement.getElementsByStyleUrl   sA    cnnn#+#Czz:#:::;;;r    c                 .    |                      dd          S )zReturns the Document Namezsodipodi:docname )getr   s    r   rV   zSvgDocumentElement.name   s     xx*B///r    c                 0    |                      dd          S )z0Return the sp namedview meta information elementz//sodipodi:namedviewTprependget_or_creater   s    r   rC   zSvgDocumentElement.namedview   s     !!"8$!GGGr    c                 0    |                      dd          S )z.Return the svg metadata meta element containerz//svg:metadataTrm   ro   r   s    r   metadatazSvgDocumentElement.metadata   s     !!"2D!AAAr    c                 0    |                      dd          S )z*Return the svg defs meta element containerz
//svg:defsTrm   ro   r   s    r   defszSvgDocumentElement.defs   s     !!,!===r    c                     	 d t          j        d|                     dd                    D             }n# t          $ r d}Y nw xY wt	          |          dk    rg dS |S )z1Parse and return the document's viewBox attributec                 ,    g | ]}t          |          S  )r=   ).0units     r   
<listcomp>z2SvgDocumentElement.get_viewbox.<locals>.<listcomp>   s+        $d  r    z,\s*|\s+viewBox0rj   r,   )r   r   r   r   )resplitrk   
ValueErrorr2   )r   rets     r   get_viewboxzSvgDocumentElement.get_viewbox   s    	 (*dhhyRU>V>V(W(W  CC  	 	 	CCC	s88q==<<
s   36 AAreturnc                 D    |                                  d         p| j        S )ab  Returns the width of the `user coordinate system
        <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e.
        the width of the viewbox, as defined in the SVG file. If no viewbox is defined,
        the value of the width attribute is returned. If the height is not defined,
        returns 0.

        .. versionadded:: 1.2r   )r   viewport_widthr   s    r   r>   z SvgDocumentElement.viewbox_width   s#     !!!$;(;;r    c                     |                      |                     d                    p|                                 d         S )zReturns the width of the `viewport coordinate system
        <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
        width attribute of the svg element converted to px

        .. versionadded:: 1.2widthr   to_dimensionlessrk   r   r   s    r   r   z!SvgDocumentElement.viewport_width   s:     $$TXXg%6%677P4;K;K;M;Ma;PPr    c                 D    |                                  d         p| j        S )ae  Returns the height of the `user coordinate system
        <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
        height of the viewbox, as defined in the SVG file. If no viewbox is defined, the
        value of the height attribute is returned. If the height is not defined,
        returns 0.

        .. versionadded:: 1.2   )r   viewport_heightr   s    r   r?   z!SvgDocumentElement.viewbox_height   s#     !!!$<(<<r    c                     |                      |                     d                    p|                                 d         S )zReturns the width of the `viewport coordinate system
        <https://www.w3.org/TR/SVG2/coords.html#Introduction>`_ in user units, i.e. the
        height attribute of the svg element converted to px

        .. versionadded:: 1.2heightr   r   r   s    r   r   z"SvgDocumentElement.viewport_height  s:     $$TXXh%7%788QD<L<L<N<Nq<QQr    c                 *    |                                  S )a?  Returns the ratio between the viewBox width and the page width.

        .. versionchanged:: 1.2
            Previously, the scale as shown by the document properties was computed,
            but the computation of this in core Inkscape changed in Inkscape 1.2, so
            this was moved to :attr:`inkscape_scale`.)_base_scaler   s    r   scalezSvgDocumentElement.scale  s     !!!r    c                     t          |                     d                    p#t          |                     d                    pdd         }|                     |          S )zReturns the ratio between the viewBox width (in width/height units) and the
        page width, which is displayed as "scale" in the Inkscape document
        properties.

        .. versionadded:: 1.2r   r   )r   pxr   )r
   rk   r   )r   viewbox_units     r   inkscape_scalez!SvgDocumentElement.inkscape_scale  sY     txx(())XZ8J8J-K-KXy
 ---r    r   c                     	 |                      | j        |          | j        z  }|                      | j        |          | j        z  }t          ||g          }|dk    rdn|S # t          t          f$ r Y dS w xY w)zUReturns what Inkscape shows as "user units per `unit`"

        .. versionadded:: 1.2r   g      ?)to_dimensionalr   r>   r   r?   r.   r   ZeroDivisionError)r   ry   scale_xscale_yvalues        r   r   zSvgDocumentElement._base_scale'  s    
	##D$7>>ASS  ##D$8$??$BUU  '*++E1**33%/-. 	 	 	33	s   A A# #A87A8c                     | j         S )zReturn the scale of the equivalent transform of the svg tag, as defined by
        https://www.w3.org/TR/SVG2/coords.html#ComputingAViewportsTransform
        (highly simplified)

        .. versionadded:: 1.2)r   r   s    r   equivalent_transform_scalez-SvgDocumentElement.equivalent_transform_scale7  s     zr    c                     t          | d          sad| _        |                                 }|rDt          |          dhk    r0t	          |                     d          |d         d          | _        | j        S )a!  Returns the unit used for in the SVG document.
        In the case the SVG document lacks an attribute that explicitly
        defines what units are used for SVG coordinates, it tries to calculate
        the unit from the SVG width and viewBox attributes.
        Defaults to 'px' units._unitr   r   r   r   )default)hasattrr   r   r%   r	   rk   )r   viewboxs     r   ry   zSvgDocumentElement.unit@  sy     tW%% 	XDJ&&((G X3w<<A3..*488G+<+<gajRVWWW
zr    c                 8    | j                             dd          S )zeReturns the display unit (Inkscape-specific attribute) of the document

        .. versionadded:: 1.2zinkscape:document-unitsr   )rC   rk   r   s    r   document_unitz SvgDocumentElement.document_unitN  s    
 ~!!";TBBBr    c                     t          |           }|                     d          D ])}|                    |                                           *|S )z=Get all the stylesheets, bound together to one, (for reading)z//svg:style)r   r&   append
stylesheet)r   sheetsnodes      r   stylesheetszSvgDocumentElement.stylesheetsU  sP     T""JJ}-- 	- 	-DMM$//++,,,,r    c                     | j         D ]}|c S t                      }| j                            |           |                                S )zAReturn the first stylesheet or create one if needed (for writing))r   r   rt   r   r   )r   sheet
style_nodes      r   r   zSvgDocumentElement.stylesheet]  sP     % 	 	ELLL!^^
	$$$$$&&&r    )NN)rI   F)rI   )r]   )N)r   )*__name__
__module____qualname____doc__tag_namer   __annotations__r   r"   r'   r4   r   r5   r   r;   r@   rE   rH   rB   rW   r\   rb   rh   propertyrV   rC   rr   rt   r   r=   r>   r   r?   r   r   r   r   r   ry   r   r   r   rw   r    r   r   r   4   sn        @@ H8  7 7 7   #)-	+ ++ sm+ DI&	+ + + +Z
 
 
  # # #
 */8 88 8 8 8,E E E EH H H #/@ @@ @ @ @.< < < < 0 0 X0 H H XH B B XB > > X>
 
 
 <u < < < X< Q Q Q Q XQ = = = = X= R R R R XR " " X" 
. 
. X
.     E    X   X C C XC   X ' ' X' ' 'r    r   c                     | j         S )z"Use :func:`viewport_width` instead)r   r   s    r   r   r   h  s    r    c                     | j         S )z#Use :func:`viewport_height` instead)r   r   s    r   r   r   m  s    r    z1.2)!r   r6   r/   r}   lxmlr   cssr   interfaces.IElementr   deprecated.metar   r   unitsr	   r
   	_selectedr   
transformsr   stylesr   _baser   _metar   typingr   r   r   r   r   r   rw   r    r   <module>r      s  0    				       ! ! ! ! ! ! 5 5 5 5 5 5 ; ; ; ; ; ; ; ; - - - - - - - - " " " " " " $ $ $ $ $ $                         ! ! ! ! ! ! ! !q' q' q' q' q'+-@+ q' q' q'h	  
     
 $8IIeU$;$;<<  $HYYvu%=%=>>    r    