o
    /hm6                     @   sr  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
mZmZmZ ddlmZ ddlmZ ddlmZ g dZe Ze Zeed	Zd
ZG dd dZe	jde dd ZedZedZedZ edZ!dd Z"dd Z#dd Z$dd Z%ej&j'Z(ej)d,ddZ*e*+ej,d,dd Z-G d!d" d"Z.d-d#d$Z/G d%d& d&e0Z1d'd( Z2d)d* Z3e4d+kre5e  dS dS ).aD  
CSS Cascading Style Sheets library for Python

A Python package to parse and build CSS Cascading Style Sheets. DOM only, not
any rendering facilities!

Based upon and partly implementing the following specifications :

`CSS 2.1 <http://www.w3.org/TR/CSS2/>`__
    General CSS rules and properties are defined here
`CSS 2.1 Errata
    <http://www.w3.org/Style/css2-updates/CR-CSS21-20070719-errata.html>`__
    A few errata, mainly the definition of CHARSET_SYM tokens
`CSS3 Module: Syntax <http://www.w3.org/TR/css3-syntax/>`__
    Used in parts since cssutils 0.9.4. cssutils tries to use the features from
    CSS 2.1 and CSS 3 with preference to CSS3 but as this is not final yet some
    parts are from CSS 2.1
`MediaQueries <http://www.w3.org/TR/css3-mediaqueries/>`__
    MediaQueries are part of ``stylesheets.MediaList`` since v0.9.4, used in
    @import and @media rules.
`Namespaces <http://dev.w3.org/csswg/css3-namespace/>`__
    Added in v0.9.1, updated to definition in CSSOM in v0.9.4, updated in 0.9.5
    for dev version
`CSS3 Module: Pages Media <http://www.w3.org/TR/css3-page/>`__
    Most properties of this spec are implemented including MarginRules
`Selectors <http://www.w3.org/TR/css3-selectors/>`__
    The selector syntax defined here (and not in CSS 2.1) should be parsable
    with cssutils (*should* mind though ;) )

`DOM Level 2 Style CSS <http://www.w3.org/TR/DOM-Level-2-Style/css.html>`__
    DOM for package css. 0.9.8 removes support for CSSValue and related API,
    see PropertyValue and Value API for now
`DOM Level 2 Style Stylesheets
    <http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html>`__
    DOM for package stylesheets
`CSSOM <http://dev.w3.org/csswg/cssom/>`__
    A few details (mainly the NamespaceRule DOM) is taken from here. Plan is
    to move implementation to the stuff defined here which is newer but still
    no REC so might change anytime...


The cssutils tokenizer is a customized implementation of `CSS3 Module: Syntax
(W3C Working Draft 13 August 2003) <http://www.w3.org/TR/css3-syntax/>`__ which
itself is based on the CSS 2.1 tokenizer. It tries to be as compliant as
possible but uses some (helpful) parts of the CSS 2.1 tokenizer.

I guess cssutils is neither CSS 2.1 nor CSS 3 compliant but tries to at least
be able to parse both grammars including some more real world cases (some CSS
hacks are actually parsed and serialized). Both official grammars are not final
nor bugfree but still feasible. cssutils aim is not to be fully compliant to
any CSS specification (the specifications seem to be in a constant flow anyway)
but cssutils *should* be able to read and write as many as possible CSS
stylesheets "in the wild" while at the same time implement the official APIs
which are well documented. Some minor extensions are provided as well.

Please visit https://cssutils.readthedocs.io/ for more details.

Example::

    >>> from cssutils import CSSParser
    >>> parser = CSSParser()
    >>> sheet = parser.parseString('a { color: red}')

    # TODO: shouldn't have to decode here
    >>> print(sheet.cssText.decode())
    a {
        color: red
        }

    N   )csserrorhandlerstylesheets)	CSSParser)Profiles)CSSSerializer)r   r   r   r   )logc                   @   s8   e Zd ZdZg dZdd Zdd Zdd Zd	d
 ZdS )DOMImplementationCSSad  This interface allows the DOM user to create a CSSStyleSheet
    outside the context of a document. There is no way to associate
    the new CSSStyleSheet with a document in DOM Level 2.

    This class is its *own factory*, as it is given to
    xml.dom.registerDOMImplementation which simply calls it and receives
    an instance of this class then.
    ))r   1.0)r   2.0)r   r   )r   r   c                 C   s*   ddl }d}|j|tdd tj||dS )a(  
        Creates a new CSSStyleSheet.

        title of type DOMString
            The advisory title. See also the Style Sheet Interfaces
            section.
        media of type DOMString
            The comma-separated list of media associated with the new style
            sheet. See also the Style Sheet Interfaces section.

        returns
            CSSStyleSheet: A new CSS style sheet.

        TODO: DOMException
            SYNTAX_ERR: Raised if the specified media string value has a
            syntax error and is unparsable.
        r   Nz|Deprecated, see https://web.archive.org/web/20200701035537/https://bitbucket.org/cthedot/cssutils/issues/69#comment-30669799   )
stacklevel)titlemedia)warningswarnDeprecationWarningr   CSSStyleSheet)selfr   r   r   warning r   E/var/www/html/myenv/lib/python3.10/site-packages/cssutils/__init__.pycreateCSSStyleSheeto   s
   z(DOMImplementationCSS.createCSSStyleSheetc                 O   &   dd l m  m} | j|i |S Nr   )xml.dom.minidomdomminidomDOMImplementationcreateDocumentr   argskwargsr   r   r   r   r!         z#DOMImplementationCSS.createDocumentc                 O   r   r   )r   r   r   r    createDocumentTyper"   r   r   r   r&      r%   z'DOMImplementationCSS.createDocumentTypec                 C   s   |  t|f| jv S N)lowerstr	_features)r   featureversionr   r   r   
hasFeature      zDOMImplementationCSS.hasFeatureN)	__name__
__module____qualname____doc__r*   r   r!   r&   r-   r   r   r   r   r   ^   s    			r   cssutilsc                    s*    fdd}t t j|_  |_|_|S )Nc                     s   t t  | i |S r'   )getattrr   )r#   r$   namer   r   func   r.   z_parser_redirect.<locals>.func)r4   r   r2   r1   r/   )r6   r7   r   r5   r   _parser_redirect   s   r8   parseString	parseFileparseUrl
parseStylec                 C   s   t  j| d dS )z8Set the global serializer used by all class in cssutils.)serN)globalsupdate)
serializerr   r   r   setSerializer   s   rA   c                 c   s<    t | ddD ]	}t|E dH  qt| dr| jV  dS dS )z4
    Recursively find all CSSStyleDeclarations.
    cssRulesr   Nstyle)r4   _style_declarationshasattrrC   )baseruler   r   r   rD      s   
rD   c                 C   s,   dd | D }dd t | D }t||S )ax  Retrieve all ``url(urlstring)`` values (in e.g.
    :class:`cssutils.css.CSSImportRule` or ``cssutils.css.CSSValue``
    objects of given `sheet`.

    :param sheet:
        :class:`cssutils.css.CSSStyleSheet` object whose URLs are yielded

    This function is a generator. The generated URL values exclude ``url(`` and
    ``)`` and surrounding single or double quotes.
    c                 s   s"    | ]}|j |jkr|jV  qd S r'   )typeIMPORT_RULEhref.0rG   r   r   r   	<genexpr>   s     zgetUrls.<locals>.<genexpr>c                 s   s$    | ]}t |D ]}|jV  qqd S r'   _uri_valuesuri)rL   rC   valuer   r   r   rM      s    )rD   	itertoolschain)sheetimportsotherr   r   r   getUrls   s
   rW   c                 C   s   dd | j ddD S )Nc                 s   s*    | ]}|j D ]
}|jd kr|V  qqdS )URIN)propertyValuerH   )rL   proprQ   r   r   r   rM      s    
z_uri_values.<locals>.<genexpr>T)all)getProperties)rC   r   r   r   rO      s   
rO   Fc                    sP    fdd| D }|D ]}||j |_ qtttt| D ]}||j|_qdS )a  Replace all URLs in :class:`cssutils.css.CSSImportRule` or
    ``cssutils.css.CSSValue`` objects of given `sheet`.

    :param sheet:
        a :class:`cssutils.css.CSSStyleSheet` to be modified in place.
    :param replacer:
        a function which is called with a single argument `url` which
        is the current value of each url() excluding ``url(``, ``)`` and
        surrounding (single or double) quotes.
    :param ignoreImportRules:
        if ``True`` does not call `replacer` with URLs from @import rules.
    c                 3   s$    | ]}|j |jkr s|V  qd S r'   )rH   rI   rK   ignoreImportRulesr   r   rM      s    zreplaceUrls.<locals>.<genexpr>N)rJ   _flattenmaprO   rD   rP   )rT   replacerr^   rU   rG   rQ   r   r]   r   replaceUrls   s   
rb   c                 C   s   t | D ]}||j|_qdS )a  Replace all URLs in :class:`cssutils.css.CSSImportRule` or
    :class:`cssutils.css.CSSValue` objects of given `style`.

    :param style:
        a :class:`cssutils.css.CSSStyleDeclaration` to be modified in place.
    :param replacer:
        a function which is called with a single argument `url` which
        is the current value of each url() excluding ``url(``, ``)`` and
        surrounding (single or double) quotes.
    :param ignoreImportRules:
        not applicable, ignored.
    NrN   )rC   ra   r^   rQ   r   r   r   _   s   rc   c                   @   s,   e Zd ZdZdd Zdd Zedd ZdS )	Replacerz<
    A replacer that uses base to return adjusted URLs.
    c                 C   s   |  || _d S r'   )extract_baserF   )r   rF   r   r   r   __init__  s   zReplacer.__init__c           	      C   sb   t j|\}}}}}|s|s|dr|S tj|\}}tjtj| j	||}t j
|S )N/)urllibparseurlsplit
startswithospathsplitnormpathjoinrF   requestpathname2url)	r   rP   schemelocationrm   queryfragmentfilenamecombinedr   r   r   __call__  s   zReplacer.__call__c                 C   s*   t j| \}}}}}tj|\}}|S r'   )rh   ri   rj   rl   rm   rn   )rP   rc   raw_path	base_pathr   r   r   re   "  s   zReplacer.extract_baseN)r/   r0   r1   r2   rf   ry   staticmethodre   r   r   r   r   rd     s    
rd   c                 C   sZ   |st j| j| j| jd}| jD ]}|j|jkrq|j|jkr%t	|| q|
| q|S )a  
    Recursively combine all rules in given `sheet` into a `target` sheet.
    Attempts to wrap @import rules that use media information into
    @media rules, keeping the media information. This approach may not work in
    all instances (e.g. if an @import rule itself contains an @import rule
    with different media infos or if it contains rules that may not be
    used inside an @media block like @namespace rules). In these cases,
    the @import rule from the original sheet takes precedence and a WARNING
    is issued.

    :param sheet:
        :class:`cssutils.css.CSSStyleSheet` from which all import rules are
        resolved and added to a resulting *flat* sheet.
    :param target:
        A :class:`cssutils.css.CSSStyleSheet` object that will be the
        resulting *flat* sheet if given.
    :returns:
        :class:`cssutils.css.CSSStyleSheet` with imports resolved.
    )rJ   r   r   )r   r   rJ   r   r   rB   rH   CHARSET_RULErI   _resolve_importadd)rT   targetrG   r   r   r   resolveImports)  s   
r   c                   @   s,   e Zd Zedd Zedd Zdd ZdS )MediaCombineDisallowedc                 C   s"   t t| j|}|r| |dS )zM
        Check if rules present that may not be combined with media.
        N)listrR   filterfalse_combinable)clsrT   failedr   r   r   checkN  s   zMediaCombineDisallowed.checkc                 C   s
   | j d S r   )r#   )r   r   r   r   r   W  s   
zMediaCombineDisallowed.failedc                 C   s   | j | j| jf}| j|v S r'   )COMMENT
STYLE_RULErI   rH   )rG   
combinabler   r   r   r   [  s   
z"MediaCombineDisallowed._combinableN)r/   r0   r1   classmethodr   propertyr   r   r   r   r   r   r   M  s    

r   c              
   C   sf  t jd| j dd | jst jd| j dd ||  d S |tjd| j d zt| j	}W n# t
jjyT } zt jd| dd ||  W Y d }~d S d }~ww t jd| j dd t|t| jdd	 zt| |}W n) ty } zt jd
|jd d| j dd ||  W Y d }~d S d }~ww |p|}|D ]}|| q|r|| d S d S )NzProcessing @import %rT
neverraisez1Cannot get referenced stylesheet %r, keeping rulez/* START @import "%s" */)cssTextz0@import: Cannot resolve target, keeping rule: %sz@import: Adjusting paths for %rr]   zaCannot combine imported sheet with given media as rules other than comments or stylerules; found r   z
, keeping )r	   inforJ   	hrefFounderrorr   r   
CSSCommentr   
styleSheetxmlr   HierarchyRequestErrr   rb   rd   _check_media_proxyr   r   r   )rG   r   importedSheetemedia_proxyexc
imp_targetrr   r   r   r~   `  sV   

	
	r~   c                 C   s@   | j jdkrd S t| tjd| j j dd t| j jS )Nr[   z7@import: Wrapping some rules in @media  to keep media: Tr   )r   	mediaTextr   r   r	   r   r   CSSMediaRule)rG   r   r   r   r   r     s   
r   __main__)Fr'   )6r2   	functoolsrR   os.pathrl   urllib.parserh   urllib.requestxml.domr    r   r   r   ri   r   profilesr   	serializer   __all__ErrorHandlerr	   r=   profile_ANYNSr   r   registerDOMImplementationr8   r9   r:   r;   r<   rA   rD   rW   rO   rS   from_iterabler_   singledispatchrb   registerCSSStyleDeclarationrc   rd   r   	Exceptionr   r~   r   r/   printr   r   r   r   <module>   sP    G
C	
	

$1