o
    e                     @   sf   d Z dg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ZddlZG d	d dejjZdS )
zCSSStyleSheet implements DOM Level 2 CSS CSSStyleSheet.

Partly also:
    - http://dev.w3.org/csswg/cssom/#the-cssstylesheet
    - http://www.w3.org/TR/2006/WD-css3-namespace-20060828/

TODO:
    - ownerRule and ownerNode
CSSStyleSheet    )
Deprecated)_Namespaces_readUrl   )CSSRule)CSSVariablesDeclarationNc                       sN  e Zd ZdZ									d> fdd	Zdd	 Zd
d Zdd Zdd Zdd Z	e
dd Zejdd Zdd Zdd Ze
eedZdd Z	d?ddZd@ddZd d! Zd"d# Ze
eed$Ze
d%d& Zd'd( Ze
d)d* d+d,Zd-d. Zd/d0 ZdAd1d2Ze
d3d* d4d,Zd5d6 Ze
ed7d,Zed8d9d: Z ed;d<d= Z!  Z"S )Br   a  CSSStyleSheet represents a CSS style sheet.

    Format::

        stylesheet
          : [ CHARSET_SYM S* STRING S* ';' ]?
            [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
            [ namespace [S|CDO|CDC]* ]* # according to @namespace WD
            [ [ ruleset | media | page ] [S|CDO|CDC]* ]*

    ``cssRules``
        All Rules in this style sheet, a :class:`~cssutils.css.CSSRuleList`.
    N FTc
           
   
      s\   t  jd|||||||	d || _tj | _t| | jd| _	t
 | _|| _d| _d| _dS )zN
        For parameters see :class:`~cssutils.stylesheets.StyleSheet`
        ztext/css)
validatingparentStyleSheetlogN)super__init__
_ownerRulecssutilscssCSSRuleListcssRulesr   _log_namespacesr   
_variablesZ	_readonly _CSSStyleSheet__encodingOverride_fetcher)
selfhrefmediatitledisabled	ownerNoder   readonly	ownerRuler
   	__class__ JD:\Projects\ConvertPro\env\Lib\site-packages\cssutils/css/cssstylesheet.pyr   #   s"   
zCSSStyleSheet.__init__c                 c   s    | j E dH  dS )z'Generator which iterates over cssRules.N	_cssRulesr   r$   r$   r%   __iter__G   s   zCSSStyleSheet.__iter__c                 C   s,   | j r| j j}nd }d| jj| j|| jS )Nz2cssutils.css.{}(href={!r}, media={!r}, title={!r}))r   	mediaTextformatr#   __name__r   r   r   r*   r$   r$   r%   __repr__K   s   
zCSSStyleSheet.__repr__c              	   C   s<   | j r| j j}nd }d| jj| j| j|| j| jjt| f S )NzT<cssutils.css.%s object encoding=%r href=%r media=%r title=%r namespaces=%r at 0x%x>)	r   r*   r#   r,   encodingr   r   
namespacesidr-   r$   r$   r%   __str__W   s   
zCSSStyleSheet.__str__c                 C   sp   | j }t| j }d}|t|k r6|| }|j|jkr*|j|jf|vr*| 	| n|d7 }|t|k sdS dS )z;Remove all namespace rules with same namespaceURI but last.r   r   N)
r   listr0   itemslentypeNAMESPACE_RULEprefixnamespaceURI
deleteRule)r   rulesZnamespaceitemsiruler$   r$   r%   _cleanNamespacesj   s   zCSSStyleSheet._cleanNamespacesc                 C   sd   t  }| D ]*}|j|jkr||j  q|j|jkr/|D ]}|j|jkr.||j  qq|S )z%Return set of URIs used in the sheet.)set
STYLE_RULEr6   updateZselectorListZ_getUsedUris
MEDIA_RULE)r   usedurisr1r2r$   r$   r%   _getUsedURIsy   s   zCSSStyleSheet._getUsedURIsc                 C      | j S )zDAll Rules in this style sheet, a :class:`~cssutils.css.CSSRuleList`.r&   r(   r$   r$   r%   r         zCSSStyleSheet.cssRulesc                 C   s2   | j |_| j |_| j|_|D ]}| |_q|| _dS )z1Set new cssRules and update contained rules refs.N)
insertRuleappendextendr:   __delitem___parentStyleSheetr'   )r   r   r=   r$   r$   r%   r      s   
c                 C   s   t j| S )z9Textual representation of the stylesheet (a byte string).)r   serZdo_CSSStyleSheetr(   r$   r$   r%   _getCssText   s   zCSSStyleSheet._getCssTextc                    sH       |\}} |}ddd}d fdd	} fdd} fdd	} fd
d} fdd}	 fdd}
 fdd} fdd} fdd} fdd} j} j}tj  _| _t  _	g } j
d||||dd dd ||
|||||	|d|d\}}|rt  jd _   dS | _| _      dS ) a   Parse `cssText` and overwrites the whole stylesheet.

        :param cssText:
            a parseable string or a tuple of (cssText, dict-of-namespaces)
        :exceptions:
            - :exc:`~xml.dom.NamespaceErr`:
              If a namespace prefix is found which is not declared.
            - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if the rule is readonly.
            - :exc:`~xml.dom.SyntaxErr`:
              Raised if the specified CSS string value has a syntax error and
              is unparsable.
        Nc                 S   s   t d| pdS )Nr   r   )maxexpectedseqtoken	tokenizerr$   r$   r%   S   s   z$CSSStyleSheet._setCssText.<locals>.Sc                    s&     tjj|g d td| pdS )zspecial: sets parent*r   r   r   )rI   r   r   Z
CSSCommentrP   rQ   r(   r$   r%   COMMENT   s   z*CSSStyleSheet._setCssText.<locals>.COMMENTc                    sP   t jj d} |||_| dkr jd|tjj	 | S |j
r& | dS )NrW   r   zFCSSStylesheet: CSSCharsetRule only allowed at beginning of stylesheet.r   )r   r   CSSCharsetRule_tokensupto2cssTextr   errorxmldomHierarchyRequestErr
wellformedrI   rR   rS   rT   rU   r=   r(   r$   r%   charsetrule   s   
z.CSSStyleSheet._setCssText.<locals>.charsetrulec                    sP   t jj d} |||_| dkr jd|tjj	 | S |j
r& | dS )NrW   r   z.CSSStylesheet: CSSImportRule not allowed here.)r   r   ZCSSImportRulerZ   r[   r   r\   r]   r^   r_   r`   rI   ra   r(   r$   r%   
importrule   s   
z-CSSStyleSheet._setCssText.<locals>.importrulec                    s   t jj || d}| dkr jd|tjj | S |j	rJ|j
 jvr- j|dd n j|jD ]}|j
|j
krB||j q4|j j|j
< dS )N)r[   r      z1CSSStylesheet: CSSNamespaceRule not allowed here.F)_clean)r   r   ZCSSNamespaceRulerZ   r   r\   r]   r^   r_   r`   r8   r0   rI   r   rulesOfTyper7   Z_replaceNamespaceURIr9   r   )rR   rS   rT   rU   r=   rr(   r$   r%   namespacerule   s&   z0CSSStyleSheet._setCssText.<locals>.namespacerulec                    sX   t jj d} |||_| dkr jd|tjj	 | S |j
r* |    dS )NrW   rd   z1CSSStylesheet: CSSVariablesRule not allowed here.)r   r   ZCSSVariablesRulerZ   r[   r   r\   r]   r^   r_   r`   rI   _updateVariablesra   r(   r$   r%   variablesrule   s   
z0CSSStyleSheet._setCssText.<locals>.variablesrulec                    0   t jj d} |||_|jr | dS NrW      )r   r   ZCSSFontFaceRulerZ   r[   r`   rI   ra   r(   r$   r%   fontfacerule  
   
z/CSSStyleSheet._setCssText.<locals>.fontfacerulec                    rk   rl   )r   r   ZCSSMediaRulerZ   r[   r`   rI   ra   r(   r$   r%   	mediarule  ro   z,CSSStyleSheet._setCssText.<locals>.mediarulec                    rk   rl   )r   r   ZCSSPageRulerZ   r[   r`   rI   ra   r(   r$   r%   pagerule  ro   z+CSSStyleSheet._setCssText.<locals>.pagerulec                    s   |d t jjjv r! jjd|dd t jj d} |||_n jjd|dd t jj	 d} |||_|j
r@ | td| pEdS )Nr   z*CSSStylesheet: MarginRule out CSSPageRule.T)Z
neverraiserW   z#CSSStylesheet: Unknown @rule found.r   )r   r   Z
MarginRuleZmarginsr   r\   rZ   r[   warnZCSSUnknownRuler`   rI   rP   ra   r(   r$   r%   unknownrule   s   
z.CSSStyleSheet._setCssText.<locals>.unknownrulec                    rk   rl   )r   r   ZCSSStyleRulerZ   r[   r`   rI   ra   r(   r$   r%   ruleset5  ro   z*CSSStyleSheet._setCssText.<locals>.rulesetr   c                  W      d S Nr$   Zignoredr$   r$   r%   <lambda>Q      z+CSSStyleSheet._setCssText.<locals>.<lambda>c                  W   ru   rv   r$   rw   r$   r$   r%   rx   R  ry   )rV   rX   ZCDOZCDCZCHARSET_SYMZFONT_FACE_SYMZ
IMPORT_SYMZNAMESPACE_SYMZPAGE_SYMZ	MEDIA_SYMZVARIABLES_SYMZ	ATKEYWORD)defaultr   rv   )_checkReadonlyZ_splitNamespacesOffZ
_tokenize2r   r   r   r   r   r   r   _parser   r   r>   r'   ri   )r   r[   r0   rU   rV   rX   rb   rc   rh   rj   rn   rp   rq   rs   rt   ZoldCssRulesZoldNamespacesZnewseqr`   rR   r$   r(   r%   _setCssText   s\   

	
zCSSStyleSheet._setCssTextz8Textual representation of the stylesheet (a byte string)c                 C   s^   z| j }W n ty$   z| jd j}W n ttfy!   d}Y nw Y nw t|| j| j|dS )zORead (encoding, enctype, decodedContent) from `url` for @import
        sheets.r   N)fetcherZoverrideEncodingparentEncoding)_CSSStyleSheet__newEncodingAttributeErrorr'   r/   
IndexErrorr   r   r   )r   urlr   r$   r$   r%   _resolveImportq  s    
zCSSStyleSheet._resolveImportc                 C   s^   |r|| _ |r
|| _|| _|r| j | _d| _ dS |r-|| _z| `W dS  ty,   Y dS w dS )zSet `cssText` but use `encodingOverride` to overwrite detected
        encoding. This is used by parse and @import during setting of cssText.

        If `encoding` is given use this but do not save as `encodingOverride`.
        N)r   r   r[   r/   r   )r   r[   ZencodingOverrider/   r$   r$   r%   _setCssTextWithEncodingOverride  s    

z-CSSStyleSheet._setCssTextWithEncodingOverridec                 C   s
   || _ dS )z4Set @import URL loader, if None the default is used.N)r   )r   r~   r$   r$   r%   _setFetcher  s   
zCSSStyleSheet._setFetcherc              	   C   s(   z| j d jW S  ttfy   Y dS w )zEncoding set in :class:`~cssutils.css.CSSCharsetRule` or if ``None``
        resulting in default ``utf-8`` encoding being used.r   zutf-8)r'   r/   r   r   r(   r$   r$   r%   _getEncoding  s
   zCSSStyleSheet._getEncodingc                 C   st   z| j d }W n ty   d}Y nw |r)|j|jkr)|r"||_dS | d dS |r8| tjj	|dd dS dS )zSet `encoding` of charset rule if present in sheet or insert a new
        :class:`~cssutils.css.CSSCharsetRule` with given `encoding`.
        If `encoding` is None removes charsetrule if present resulting in
        default encoding of utf-8.
        r   N)r/   )
r'   r   CHARSET_RULEr6   r/   r:   rI   r   r   rY   )r   r/   r=   r$   r$   r%   _setEncoding  s   
zCSSStyleSheet._setEncodingzW(cssutils) Reflect encoding of an @charset rule or 'utf-8' (default) if set to ``None``c                 C   rG   )z*All Namespaces used in this CSSStyleSheet.)r   r(   r$   r$   r%   r0     rH   zCSSStyleSheet.namespacesc                 C   sv   | j tjD ]}|j}|r|jD ]}| j||j|  qq| j tjD ]}|jD ]}| j||j|  q+q&dS )zdUpdates self._variables, called when @import or @variables rules
        is added to sheet.
        N)	r   rf   r   IMPORT_RULEZ
styleSheet	variablesr   ZsetVariableVARIABLES_RULE)r   rg   svarZvrr$   r$   r%   ri     s   

zCSSStyleSheet._updateVariablesc                 C   rG   rv   )r   r(   r$   r$   r%   rx         zCSSStyleSheet.<lambda>zA :class:`cssutils.css.CSSVariablesDeclaration` containing all available variables in this CSSStyleSheet including the ones defined in imported sheets.)docc                 C   s   | j |dddS )zoAdd `rule` to style sheet at appropriate position.
        Same as ``insertRule(rule, inOrder=True)``.
        NT)indexinOrder)rI   r   r=   r$   r$   r%   add  s   zCSSStyleSheet.addc                 C   s   |    t|tr#t| jD ]\}}||kr|} n	qtjd| z| j| }W n t	y=   tjd|| jj
f w |j|jkrbdd | D }|  }|j|v rb||jdkrbtjdd|_| j|= dS )a~  Delete rule at `index` from the style sheet.

        :param index:
            The `index` of the rule to be removed from the StyleSheet's rule
            list. For an `index` < 0 **no** :exc:`~xml.dom.IndexSizeErr` is
            raised but rules for normal Python lists are used. E.g.
            ``deleteRule(-1)`` removes the last rule in cssRules.

            `index` may also be a CSSRule object which will then be removed
            from the StyleSheet.

        :exceptions:
            - :exc:`~xml.dom.IndexSizeErr`:
              Raised if the specified index does not correspond to a rule in
              the style sheet's rule list.
            - :exc:`~xml.dom.NamespaceErr`:
              Raised if removing this rule would result in an invalid StyleSheet
            - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if this style sheet is readonly.
        z<CSSStyleSheet: Not a rule in this sheets'a cssRules list: %szCCSSStyleSheet: %s is not a valid index in the rulelist of length %ic                 S   s   g | ]}|j |jkr|jqS r$   )r6   r7   r9   .0rg   r$   r$   r%   
<listcomp>  s    z,CSSStyleSheet.deleteRule.<locals>.<listcomp>r   zHCSSStyleSheet: NamespaceURI defined in this rule is used, cannot remove.N)r{   
isinstancer   	enumerater   r]   r^   IndexSizeErrr'   r   lengthr6   r7   rF   r9   countZNoModificationAllowedErrrM   )r   r   r<   rg   r=   urisrC   r$   r$   r%   r:     s<   

zCSSStyleSheet.deleteRulec           
   	   C   s<  |    |du rt| j}n|dk s|| jjkr$tjd|| jjf t|trt	| j
| j| j| j| jd}| j|_| j|_|ds`| jr`| jd j| jd jkr`d\}}| jd j| }nd\}}|| jf|_t|j|ks{t|j| tjjs| jd|  dS |j| }d|_nt|tjjrt|D ]\}}	|  |	||  q|S |j!s| jd	 dS |j|jkr|rd}| jr| jd j|jkr|j"| jd _"n| j#d| n|dks| jr| jd j|jkr| jjd
tjj$d dS | j#|| n|j|j%|j&fv r6|s6|dkr-| jr-| jd j|jkr-| jjdtjj$d dS | j#|| nT|j|j'kr|r|jdd | D v ritt(| jD ]\}}	|	j|jkrft| j| } nqRnb| jr}| jd j|j|j&fv r}d}nNd}nK|dkr| jr| jd j|jkr| jjdtjj$d dS | jd| D ]$}	|	j|	j)|	j*|	j+|	j,|	j-|	j.fv r| jjd| tjj$d  dS q| j#|| | /  n|j|j)kr|r/|jdd | D v rtt(| jD ]\}}	|	j|jkrt| j| } nqnrt| jD ]\}}	|	j|	j*|	j+|	j,|	j-|	j.|	j%|	j&fv r,|} nqnN| j|d D ]}	|	j|	j|	j'fv rQ| jjd| tjj$d  dS q6| jd| D ]"}	|	j|	j*|	j+|	j,|	j-|	j.fv r{| jjd| tjj$d  dS qZ|j0| j1v r| j1|j0 |j2ks| j#|| |r| 3  n|j|j*krL|r|jdd | D v rtt(| jD ]\}}	|	j|jkrt| j| } nqnpt| jD ]\}}	|	j|	j+|	j,|	j-|	j.|	j%|	j&fv r|} nqnN| j|d D ]}	|	j|	j|	j'|	j)fv r| jjd| tjj$d  dS q| jd| D ] }	|	j|	j+|	j,|	j-|	j.fv r>| jjd| tjj$d  dS q| j#|| | /  n>|r]| j4| t| jd }n-| j|d D ]}	|	j|	j|	j'|	j)fv r| jjd| tjj$d  dS qd| j#|| | |_|j'|jkr|j5s|j
|_
|S )a(  
        Used to insert a new rule into the style sheet. The new rule now
        becomes part of the cascade.

        :param rule:
            a parsable DOMString, in cssutils also a
            :class:`~cssutils.css.CSSRule` or :class:`~cssutils.css.CSSRuleList`
        :param index:
            of the rule before the new rule will be inserted.
            If the specified `index` is equal to the length of the
            StyleSheet's rule collection, the rule will be added to the end
            of the style sheet.
            If `index` is not given or ``None`` rule will be appended to rule
            list.
        :param inOrder:
            if ``True`` the rule will be put to a proper location while
            ignoring `index` and without raising
            :exc:`~xml.dom.HierarchyRequestErr`.
            The resulting index is returned nevertheless.
        :returns: The index within the style sheet's rule collection
        :Exceptions:
            - :exc:`~xml.dom.HierarchyRequestErr`:
              Raised if the rule cannot be inserted at the specified `index`
              e.g. if an @import rule is inserted after a standard rule set
              or other at-rule.
            - :exc:`~xml.dom.IndexSizeErr`:
              Raised if the specified `index` is not a valid insertion point.
            - :exc:`~xml.dom.NoModificationAllowedErr`:
              Raised if this style sheet is readonly.
            - :exc:`~xml.dom.SyntaxErr`:
              Raised if the specified rule has a syntax error and is
              unparsable.
        Nr   zDCSSStyleSheet: Invalid index %s for CSSRuleList with a length of %s.)r   r   r   r   r!   z@charset)rd   r   )r   r   z CSSStyleSheet: Not a CSSRule: %sz-CSSStyleSheet: Invalid rules cannot be added.zKCSSStylesheet: @charset only allowed once at the beginning of a stylesheet.)r\   z/CSSStylesheet: @charset must be the first rule.c                 s       | ]}|j V  qd S rv   r6   r   r$   r$   r%   	<genexpr>      z+CSSStyleSheet.insertRule.<locals>.<genexpr>r   z)CSSStylesheet: Found @charset at index 0.zwCSSStylesheet: Cannot insert @import here, found @namespace, @variables, @media, @page or CSSStyleRule before index %s.c                 s   r   rv   r   r   r$   r$   r%   r     r   zWCSSStylesheet: Cannot insert @namespace here, found @charset or @import after index %s.znCSSStylesheet: Cannot insert @namespace here, found @variables, @media, @page or CSSStyleRule before index %s.c                 s   r   rv   r   r   r$   r$   r%   r     r   zcCSSStylesheet: Cannot insert @variables here, found @charset, @import or @namespace after index %s.zbCSSStylesheet: Cannot insert @variables here, found @media, @page or CSSStyleRule before index %s.z^CSSStylesheet: Cannot insert rule here, found @charset, @import or @namespace before index %s.)6r{   r5   r'   r   r]   r^   r   r   strr   r   r   r   r   r!   r   Z
_ownerNoder   
startswithr6   r   r[   r   r   r   r   r   r   r\   rM   r   r   rI   r`   r/   insertr_   ZUNKNOWN_RULErX   r   reversedr7   r   rB   Z	PAGE_RULEr@   ZFONT_FACE_RULEri   r8   r0   r9   r>   rJ   Z	hrefFound)
r   r=   r   r   re   Z	tempsheetZnewrulescountZnewruleindexr<   rg   r$   r$   r%   rI   '  s  "





		
zCSSStyleSheet.insertRulec                 C   rG   rv   )r   r(   r$   r$   r%   rx   h  r   z:A ref to an @import rule if it is imported, else ``None``.c                 C   s&   | j D ]}t|dr|js dS qdS )z&Check if each contained rule is valid.validFT)r   hasattrr   r   r$   r$   r%   	_getValidl  s
   
zCSSStyleSheet._getValidz)``True`` if all contained rules are validz3Use ``cssutils.setSerializer(serializer)`` instead.c                 C   s   t |tjr|t_dS td)z7Set the cssutils global Serializer used for all output.z9Serializer must be an instance of cssutils.CSSSerializer.N)r   r   ZCSSSerializerrN   
ValueError)r   Zcssserializerr$   r$   r%   setSerializerv  s
   
zCSSStyleSheet.setSerializerz+Set pref in ``cssutils.ser.prefs`` instead.c                 C   s   t jj|| dS )zSet a Preference of CSSSerializer used for output.
        See :class:`cssutils.serialize.Preferences` for possible
        preferences to be set.
        N)r   rN   Zprefs__setattr__)r   Zprefvaluer$   r$   r%   setSerializerPref  s   zCSSStyleSheet.setSerializerPref)	NNr	   NNNFNT)NNrv   )NFT)#r,   
__module____qualname____doc__r   r)   r.   r2   r>   rF   propertyr   setterrO   r}   r[   r   r   r   r   r   r/   r0   ri   r   r   r:   rI   r!   r   r   r   r   r   __classcell__r$   r$   r"   r%   r      s|    $

 R



8  B
	)r   __all__Zcssutils.helperr   Zcssutils.utilr   r   Zcssruler   Zcssvariablesdeclarationr   Zcssutils.stylesheetsr   Zxml.domr]   ZstylesheetsZ
StyleSheetr   r$   r$   r$   r%   <module>   s    	