View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.css;
16  
17  import static java.nio.charset.StandardCharsets.UTF_8;
18  import static org.htmlunit.BrowserVersionFeatures.HTMLLINK_CHECK_TYPE_FOR_STYLESHEET;
19  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.InputStreamReader;
24  import java.io.Reader;
25  import java.io.Serializable;
26  import java.io.StringReader;
27  import java.net.URL;
28  import java.nio.charset.Charset;
29  import java.util.ArrayList;
30  import java.util.Arrays;
31  import java.util.Collections;
32  import java.util.HashMap;
33  import java.util.HashSet;
34  import java.util.Iterator;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Set;
38  import java.util.regex.Pattern;
39  
40  import org.apache.commons.io.IOUtils;
41  import org.apache.commons.logging.Log;
42  import org.apache.commons.logging.LogFactory;
43  import org.htmlunit.BrowserVersion;
44  import org.htmlunit.Cache;
45  import org.htmlunit.FailingHttpStatusCodeException;
46  import org.htmlunit.Page;
47  import org.htmlunit.SgmlPage;
48  import org.htmlunit.WebClient;
49  import org.htmlunit.WebClient.PooledCSS3Parser;
50  import org.htmlunit.WebRequest;
51  import org.htmlunit.WebResponse;
52  import org.htmlunit.WebWindow;
53  import org.htmlunit.cssparser.dom.AbstractCSSRuleImpl;
54  import org.htmlunit.cssparser.dom.CSSImportRuleImpl;
55  import org.htmlunit.cssparser.dom.CSSMediaRuleImpl;
56  import org.htmlunit.cssparser.dom.CSSRuleListImpl;
57  import org.htmlunit.cssparser.dom.CSSStyleDeclarationImpl;
58  import org.htmlunit.cssparser.dom.CSSStyleRuleImpl;
59  import org.htmlunit.cssparser.dom.CSSStyleSheetImpl;
60  import org.htmlunit.cssparser.dom.CSSValueImpl;
61  import org.htmlunit.cssparser.dom.CSSValueImpl.CSSPrimitiveValueType;
62  import org.htmlunit.cssparser.dom.MediaListImpl;
63  import org.htmlunit.cssparser.dom.Property;
64  import org.htmlunit.cssparser.parser.CSSErrorHandler;
65  import org.htmlunit.cssparser.parser.CSSException;
66  import org.htmlunit.cssparser.parser.CSSOMParser;
67  import org.htmlunit.cssparser.parser.InputSource;
68  import org.htmlunit.cssparser.parser.LexicalUnit;
69  import org.htmlunit.cssparser.parser.condition.AttributeCondition;
70  import org.htmlunit.cssparser.parser.condition.Condition;
71  import org.htmlunit.cssparser.parser.condition.Condition.ConditionType;
72  import org.htmlunit.cssparser.parser.condition.HasPseudoClassCondition;
73  import org.htmlunit.cssparser.parser.condition.IsPseudoClassCondition;
74  import org.htmlunit.cssparser.parser.condition.NotPseudoClassCondition;
75  import org.htmlunit.cssparser.parser.condition.NthPseudoClassCondition;
76  import org.htmlunit.cssparser.parser.condition.NthPseudoClassCondition.NthType;
77  import org.htmlunit.cssparser.parser.condition.WherePseudoClassCondition;
78  import org.htmlunit.cssparser.parser.media.MediaQuery;
79  import org.htmlunit.cssparser.parser.selector.ChildSelector;
80  import org.htmlunit.cssparser.parser.selector.DescendantSelector;
81  import org.htmlunit.cssparser.parser.selector.DirectAdjacentSelector;
82  import org.htmlunit.cssparser.parser.selector.ElementSelector;
83  import org.htmlunit.cssparser.parser.selector.GeneralAdjacentSelector;
84  import org.htmlunit.cssparser.parser.selector.PseudoElementSelector;
85  import org.htmlunit.cssparser.parser.selector.RelativeSelector;
86  import org.htmlunit.cssparser.parser.selector.Selector;
87  import org.htmlunit.cssparser.parser.selector.Selector.SelectorType;
88  import org.htmlunit.cssparser.parser.selector.SelectorList;
89  import org.htmlunit.cssparser.parser.selector.SimpleSelector;
90  import org.htmlunit.html.DisabledElement;
91  import org.htmlunit.html.DomElement;
92  import org.htmlunit.html.DomNode;
93  import org.htmlunit.html.DomText;
94  import org.htmlunit.html.HtmlCheckBoxInput;
95  import org.htmlunit.html.HtmlElement;
96  import org.htmlunit.html.HtmlForm;
97  import org.htmlunit.html.HtmlInput;
98  import org.htmlunit.html.HtmlLink;
99  import org.htmlunit.html.HtmlOption;
100 import org.htmlunit.html.HtmlPage;
101 import org.htmlunit.html.HtmlRadioButtonInput;
102 import org.htmlunit.html.HtmlStyle;
103 import org.htmlunit.html.HtmlTextArea;
104 import org.htmlunit.html.ValidatableHtmlElement;
105 import org.htmlunit.html.csp.ContentSecurityPolicy;
106 import org.htmlunit.javascript.host.css.MediaList;
107 import org.htmlunit.util.MimeType;
108 import org.htmlunit.util.StringUtils;
109 import org.htmlunit.util.UrlUtils;
110 
111 /**
112  * A css StyleSheet.
113  *
114  * @author Marc Guillemot
115  * @author Daniel Gredler
116  * @author Ahmed Ashour
117  * @author Ronald Brill
118  * @author Guy Burton
119  * @author Frank Danek
120  * @author Carsten Steul
121  * @author Sven Strickroth
122  * @author Ashutosh Panda
123  */
124 public class CssStyleSheet implements Serializable {
125 
126     /** "none". */
127     public static final String NONE = "none";
128     /** "auto". */
129     public static final String AUTO = "auto";
130     /** "static". */
131     public static final String STATIC = "static";
132     /** "inherit". */
133     public static final String INHERIT = "inherit";
134     /** "initial". */
135     public static final String INITIAL = "initial";
136     /** "relative". */
137     public static final String RELATIVE = "relative";
138     /** "fixed". */
139     public static final String FIXED = "fixed";
140     /** "absolute". */
141     public static final String ABSOLUTE = "absolute";
142     /** "repeat". */
143     public static final String REPEAT = "repeat";
144     /** "block". */
145     public static final String BLOCK = "block";
146     /** "inline". */
147     public static final String INLINE = "inline";
148     /** "scroll". */
149     public static final String SCROLL = "scroll";
150 
151     private static final Log LOG = LogFactory.getLog(CssStyleSheet.class);
152 
153     private static final Pattern UNESCAPE_SELECTOR = Pattern.compile("\\\\([\\[\\].:])");
154 
155     /** The parsed stylesheet which this host object wraps. */
156     private final CSSStyleSheetImpl wrapped_;
157 
158     /** The HTML element which owns this stylesheet. */
159     private final HtmlElement owner_;
160 
161     /** The CSS import rules and their corresponding stylesheets. */
162     private final Map<CSSImportRuleImpl, CssStyleSheet> imports_ = new HashMap<>();
163 
164     /** True if this (imported) style sheet was not loaded because of the Content-Security-Policy. */
165     private boolean blockedByContentSecurityPolicy_;
166 
167     /** cache parsed media strings. */
168     private static final Map<String, MediaListImpl> MEDIA = Collections.synchronizedMap(new HashMap<>(100));
169 
170     /** This stylesheet's URI (used to resolved contained @import rules). */
171     private final String uri_;
172 
173     private boolean enabled_ = true;
174 
175     /**
176      * Set of CSS2 pseudo class names.
177      */
178     public static final Set<String> CSS2_PSEUDO_CLASSES;
179 
180     private static final Set<String> CSS3_PSEUDO_CLASSES;
181 
182     /**
183      * Set of CSS4 pseudo class names.
184      */
185     public static final Set<String> CSS4_PSEUDO_CLASSES;
186 
187     static {
188         CSS2_PSEUDO_CLASSES = Set.of("link", "visited", "hover", "active", "focus", "lang", "first-child");
189 
190         final Set<String> css3 = new HashSet<>(Arrays.asList(
191                 "checked", "disabled", "enabled", "indeterminate", "root", "target", "not()",
192                 "nth-child()", "nth-last-child()", "nth-of-type()", "nth-last-of-type()",
193                 "last-child", "first-of-type", "last-of-type", "only-child", "only-of-type", "empty",
194                 "optional", "required", "valid", "invalid"));
195         css3.addAll(CSS2_PSEUDO_CLASSES);
196         CSS3_PSEUDO_CLASSES = Collections.unmodifiableSet(css3);
197 
198         final Set<String> css4 = new HashSet<>(Arrays.asList(
199                 // only what is supported at the moment
200                 "focus-within", "focus-visible", "scope"));
201         css4.addAll(CSS3_PSEUDO_CLASSES);
202         CSS4_PSEUDO_CLASSES = Collections.unmodifiableSet(css4);
203     }
204 
205     /**
206      * Creates a new stylesheet representing the CSS stylesheet for the specified input source.
207      * @param element the owning node
208      * @param source the input source which contains the CSS stylesheet which this stylesheet host object represents
209      * @param uri this stylesheet's URI (used to resolved contained @import rules)
210      */
211     public CssStyleSheet(final HtmlElement element, final InputSource source, final String uri) {
212         if (source == null) {
213             wrapped_ = new CSSStyleSheetImpl();
214         }
215         else {
216             source.setURI(uri);
217             wrapped_ = parseCSS(source, element.getPage().getWebClient());
218         }
219         uri_ = uri;
220         owner_ = element;
221     }
222 
223     /**
224      * Creates a new stylesheet representing the CSS stylesheet for the specified input source.
225      * @param element the owning node
226      * @param styleSheet the source which contains the CSS stylesheet which this stylesheet host object represents
227      * @param uri this stylesheet's URI (used to resolved contained @import rules)
228      */
229     public CssStyleSheet(final HtmlElement element, final String styleSheet, final String uri) {
230         CSSStyleSheetImpl css = null;
231         try (InputSource source = new InputSource(new StringReader(styleSheet))) {
232             source.setURI(uri);
233             css = parseCSS(source, element.getPage().getWebClient());
234         }
235         catch (final IOException e) {
236             LOG.error(e.getMessage(), e);
237         }
238 
239         wrapped_ = css;
240         uri_ = uri;
241         owner_ = element;
242     }
243 
244     /**
245      * Creates a new stylesheet representing the specified CSS stylesheet.
246      * @param element the owning node
247      * @param wrapped the CSS stylesheet which this stylesheet host object represents
248      * @param uri this stylesheet's URI (used to resolved contained @import rules)
249      */
250     public CssStyleSheet(final HtmlElement element, final CSSStyleSheetImpl wrapped, final String uri) {
251         wrapped_ = wrapped;
252         uri_ = uri;
253         owner_ = element;
254     }
255 
256     /**
257      * Returns the wrapped stylesheet.
258      * @return the wrapped stylesheet
259      */
260     public CSSStyleSheetImpl getWrappedSheet() {
261         return wrapped_;
262     }
263 
264     /**
265      * Returns this stylesheet's URI (used to resolved contained @import rules).
266      * For inline styles this is the page uri.
267      * @return this stylesheet's URI (used to resolved contained @import rules)
268      */
269     public String getUri() {
270         return uri_;
271     }
272 
273     /**
274      * Returns {@code true} if this stylesheet is enabled.
275      * @return {@code true} if this stylesheet is enabled
276      */
277     public boolean isEnabled() {
278         return enabled_;
279     }
280 
281     /**
282      * Sets whether this sheet is enabled or not.
283      * @param enabled enabled or not
284      */
285     public void setEnabled(final boolean enabled) {
286         enabled_ = enabled;
287     }
288 
289     /**
290      * Loads the stylesheet at the specified link or href.
291      * @param element the parent DOM element
292      * @param link the stylesheet's link (maybe {@code null} if a <code>url</code> is specified)
293      * @param url the stylesheet's url (maybe {@code null} if a <code>link</code> is specified)
294      * @return the loaded stylesheet
295      */
296     public static CssStyleSheet loadStylesheet(final HtmlElement element, final HtmlLink link, final String url) {
297         final HtmlPage page = (HtmlPage) element.getPage();
298         String uri = page.getUrl().toExternalForm();
299         try {
300             // Retrieve the associated content and respect client settings regarding failing HTTP status codes.
301             final WebRequest request;
302             final WebResponse response;
303             final WebClient client = page.getWebClient();
304             if (link == null) {
305                 // Use href.
306                 final BrowserVersion browser = client.getBrowserVersion();
307                 request = new WebRequest(new URL(url), browser.getCssAcceptHeader(), browser.getAcceptEncodingHeader());
308 
309                 // like the browsers, a page not loaded from a file is not allowed to load a local file
310                 if (!page.isLocalResourceAccessAllowed(request.getUrl())) {
311                     client.getIncorrectnessListener().notify("Not allowed to load local resource: " + url, page);
312                     return new CssStyleSheet(element, "", url);
313                 }
314 
315                 request.setRefererHeader(page.getUrl());
316                 request.setReferrerPolicy(page.getReferrerPolicy());
317                 // https://www.w3.org/TR/css-syntax-3/#input-byte-stream
318                 request.setDefaultResponseContentCharset(UTF_8);
319 
320                 if (page.getContentSecurityPolicy() != null) {
321                     // like the browsers, redirects are checked (and upgraded) also
322                     final URL importUrl = request.getUrl();
323                     ContentSecurityPolicy.upgradeInsecureRedirects(page, request);
324                     request.setRedirectFilter(
325                         redirectUrl -> ContentSecurityPolicy.allowsExternalStyle(page, null, redirectUrl, importUrl));
326                 }
327 
328                 // our cache is a bit strange;
329                 // loadWebResponse check the cache for the web response
330                 // AND also fixes the request url for the following cache lookups
331                 response = client.loadWebResponse(request);
332                 if (response == null) {
333                     // redirect blocked by the Content-Security-Policy
334                     final CssStyleSheet blocked = new CssStyleSheet(element, "", url);
335                     blocked.blockedByContentSecurityPolicy_ = true;
336                     return blocked;
337                 }
338             }
339             else {
340                 // Use link.
341                 request = link.getWebRequest();
342 
343                 final String type = link.getTypeAttribute();
344                 if (client.getBrowserVersion().hasFeature(HTMLLINK_CHECK_TYPE_FOR_STYLESHEET)) {
345                     if (StringUtils.isNotBlank(type) && !MimeType.TEXT_CSS.equals(type)) {
346                         return new CssStyleSheet(element, "", uri);
347                     }
348                 }
349 
350                 if (request.getCharset() != null) {
351                     request.setDefaultResponseContentCharset(request.getCharset());
352                 }
353                 else {
354                     // https://www.w3.org/TR/css-syntax-3/#input-byte-stream
355                     request.setDefaultResponseContentCharset(UTF_8);
356                 }
357 
358                 // our cache is a bit strange;
359                 // loadWebResponse check the cache for the web response
360                 // AND also fixes the request url for the following cache lookups
361                 response = link.getWebResponse(true, request, true, type);
362                 if (response == null) {
363                     return new CssStyleSheet(element, "", uri);
364                 }
365             }
366 
367             // now we can look into the cache with the fixed request for
368             // a cached style sheet
369             final Cache cache = client.getCache();
370             final Object fromCache = cache.getCachedObject(request);
371             if (fromCache instanceof CSSStyleSheetImpl impl) {
372                 uri = request.getUrl().toExternalForm();
373                 return new CssStyleSheet(element, impl, uri);
374             }
375 
376             uri = response.getWebRequest().getUrl().toExternalForm();
377             client.printContentIfNecessary(response);
378             client.throwFailingHttpStatusCodeExceptionIfNecessary(response);
379             // CSS content must have downloaded OK; go ahead and build the corresponding stylesheet.
380 
381             final CssStyleSheet sheet;
382             final String contentType = response.getContentType();
383             if (StringUtils.isEmptyOrNull(contentType) || MimeType.TEXT_CSS.equals(contentType)) {
384                 try (InputStream in = response.getContentAsStreamWithBomIfApplicable()) {
385                     if (in == null) {
386                         if (LOG.isWarnEnabled()) {
387                             LOG.warn("Loading stylesheet for url '" + uri + "' returns empty responseData");
388                         }
389                         return new CssStyleSheet(element, "", uri);
390                     }
391 
392                     final Charset cssEncoding2 = response.getContentCharset();
393                     try (InputSource source = new InputSource(new InputStreamReader(in, cssEncoding2))) {
394                         source.setURI(uri);
395                         sheet = new CssStyleSheet(element, source, uri);
396                     }
397                 }
398             }
399             else {
400                 sheet = new CssStyleSheet(element, "", uri);
401             }
402 
403             // cache the style sheet
404             if (!cache.cacheIfPossible(request, response, sheet.getWrappedSheet())) {
405                 response.cleanUp();
406             }
407 
408             return sheet;
409         }
410         catch (final FailingHttpStatusCodeException e) {
411             // Got a 404 response or something like that; behave nicely.
412             if (LOG.isErrorEnabled()) {
413                 LOG.error("Exception loading " + uri, e);
414             }
415             return new CssStyleSheet(element, "", uri);
416         }
417         catch (final IOException e) {
418             // Got a basic IO error; behave nicely.
419             if (LOG.isErrorEnabled()) {
420                 LOG.error("IOException loading " + uri, e);
421             }
422             return new CssStyleSheet(element, "", uri);
423         }
424     }
425 
426     /**
427      * Returns {@code true} if the specified selector selects the specified element.
428      *
429      * @param browserVersion the browser version
430      * @param selector the selector to test
431      * @param element the element to test
432      * @param pseudoElement the pseudo element to match, (can be {@code null})
433      * @param scope the context scope node used for evaluating relative selectors like :scope
434      * @param fromQuerySelectorAll whether this is called from {@link DomNode#querySelectorAll(String, DomNode)}
435      * @param throwOnSyntax throw exception if the selector syntax is incorrect
436      * @return {@code true} if it does apply, {@code false} if it doesn't apply
437      */
438     public static boolean selects(final BrowserVersion browserVersion,
439             final DomElement element,
440             final Selector selector,
441             final String pseudoElement,
442             final DomNode scope,
443             final boolean fromQuerySelectorAll,
444             final boolean throwOnSyntax) {
445         switch (selector.getSelectorType()) {
446             case ELEMENT_NODE_SELECTOR:
447                 final ElementSelector es = (ElementSelector) selector;
448 
449                 final String name;
450                 final String elementName;
451                 if (element.getPage().hasCaseSensitiveTagNames()) {
452                     name = es.getLocalName();
453                     elementName = element.getLocalName();
454                 }
455                 else {
456                     name = es.getLocalNameLowerCase();
457                     elementName = element.getLowercaseName();
458                 }
459 
460                 if (name == null || name.equals(elementName)) {
461                     final List<Condition> conditions = es.getConditions();
462                     if (conditions != null) {
463                         for (final Condition condition : conditions) {
464                             if (!selects(browserVersion, element, condition,
465                                     scope, fromQuerySelectorAll, throwOnSyntax)) {
466                                 return false;
467                             }
468                         }
469                     }
470                     return true;
471                 }
472 
473                 return false;
474 
475             case CHILD_SELECTOR:
476                 final DomNode parentNode = element.getParentNode();
477                 if (parentNode == element.getPage()) {
478                     return false;
479                 }
480                 if (!(parentNode instanceof DomElement)) {
481                     return false; // for instance parent is a DocumentFragment
482                 }
483                 final ChildSelector cs = (ChildSelector) selector;
484                 return selects(browserVersion, element, cs.getSimpleSelector(), pseudoElement,
485                             scope, fromQuerySelectorAll, throwOnSyntax)
486                     && selects(browserVersion, (DomElement) parentNode, cs.getAncestorSelector(),
487                             pseudoElement, scope, fromQuerySelectorAll, throwOnSyntax);
488 
489             case DESCENDANT_SELECTOR:
490                 final DescendantSelector ds = (DescendantSelector) selector;
491                 final SimpleSelector simpleSelector = ds.getSimpleSelector();
492                 if (selects(browserVersion, element, simpleSelector, pseudoElement,
493                             scope, fromQuerySelectorAll, throwOnSyntax)) {
494                     DomNode ancestor = element;
495                     if (simpleSelector.getSelectorType() != SelectorType.PSEUDO_ELEMENT_SELECTOR) {
496                         ancestor = ancestor.getParentNode();
497                     }
498                     final Selector dsAncestorSelector = ds.getAncestorSelector();
499                     while (ancestor instanceof DomElement) {
500                         if (selects(browserVersion, (DomElement) ancestor, dsAncestorSelector, pseudoElement,
501                                 scope, fromQuerySelectorAll, throwOnSyntax)) {
502                             return true;
503                         }
504                         ancestor = ancestor.getParentNode();
505                     }
506                 }
507                 return false;
508 
509             case DIRECT_ADJACENT_SELECTOR:
510                 final DirectAdjacentSelector das = (DirectAdjacentSelector) selector;
511                 if (selects(browserVersion, element, das.getSimpleSelector(), pseudoElement,
512                             scope, fromQuerySelectorAll, throwOnSyntax)) {
513                     DomNode prev = element.getPreviousSibling();
514                     while (prev != null && !(prev instanceof DomElement)) {
515                         prev = prev.getPreviousSibling();
516                     }
517                     return prev != null
518                             && selects(browserVersion, (DomElement) prev, das.getSelector(),
519                                     pseudoElement, scope, fromQuerySelectorAll, throwOnSyntax);
520                 }
521                 return false;
522 
523             case GENERAL_ADJACENT_SELECTOR:
524                 final GeneralAdjacentSelector gas = (GeneralAdjacentSelector) selector;
525                 if (selects(browserVersion, element, gas.getSimpleSelector(), pseudoElement,
526                             scope, fromQuerySelectorAll, throwOnSyntax)) {
527                     for (DomNode prev1 = element.getPreviousSibling(); prev1 != null;
528                                                         prev1 = prev1.getPreviousSibling()) {
529                         if (prev1 instanceof DomElement domElement
530                             && selects(browserVersion, domElement, gas.getSelector(),
531                                     pseudoElement, scope, fromQuerySelectorAll, throwOnSyntax)) {
532                             return true;
533                         }
534                     }
535                 }
536                 return false;
537             case PSEUDO_ELEMENT_SELECTOR:
538                 if (pseudoElement != null && pseudoElement.length() != 0 && pseudoElement.charAt(0) == ':') {
539                     final String pseudoName = ((PseudoElementSelector) selector).getLocalName();
540                     return pseudoName.equals(pseudoElement.substring(1));
541                 }
542                 return false;
543 
544             case RELATIVE_SELECTOR:
545                 final RelativeSelector rs = (RelativeSelector) selector;
546 
547                 switch (rs.getCombinator()) {
548                     case DESCENDANT_COMBINATOR:
549                         for (final DomElement descendant : element.getDomElementDescendants()) {
550                             if (selects(browserVersion, descendant, rs.getSelector(), pseudoElement,
551                                             scope, fromQuerySelectorAll, throwOnSyntax)) {
552                                 return true;
553                             }
554                         }
555                         return false;
556 
557                     case CHILD_COMBINATOR:
558                         for (final DomElement child : element.getChildElements()) {
559                             if (selects(browserVersion, child, rs.getSelector(), pseudoElement,
560                                             scope, fromQuerySelectorAll, throwOnSyntax)) {
561                                 return true;
562                             }
563                         }
564                         return false;
565 
566                     case NEXT_SIBLING_COMBINATOR:
567                         final DomElement nextSibling = element.getNextElementSibling();
568                         return nextSibling != null && selects(browserVersion, nextSibling,
569                                                                 rs.getSelector(), pseudoElement,
570                                                                 scope, fromQuerySelectorAll, throwOnSyntax);
571 
572                     case SUBSEQUENT_SIBLING_COMBINATOR:
573                         for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
574                             if (n instanceof DomElement domElement
575                                     && selects(browserVersion, domElement, rs.getSelector(), pseudoElement,
576                                                 scope, fromQuerySelectorAll, throwOnSyntax)) {
577                                 return true;
578                             }
579                         }
580                         return false;
581 
582                     default:
583                         if (LOG.isErrorEnabled()) {
584                             LOG.error("Unknown CSS combinator '" + rs.getCombinator() + "'.");
585                         }
586                         return false;
587                 }
588 
589             default:
590                 if (LOG.isErrorEnabled()) {
591                     LOG.error("Unknown CSS selector type '" + selector.getSelectorType() + "'.");
592                 }
593                 return false;
594         }
595     }
596 
597     /**
598      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
599      * Returns {@code true} if the specified condition selects the specified element.
600      *
601      * @param browserVersion the browser version
602      * @param condition the condition to test
603      * @param element the element to test
604      * @param scope the context scope node used for evaluating relative selectors like :scope
605      * @param fromQuerySelectorAll whether this is called from {@link DomNode#querySelectorAll(String)}
606      * @param throwOnSyntax throw exception if the selector syntax is incorrect
607      * @return {@code true} if it does apply, {@code false} if it doesn't apply
608      */
609     static boolean selects(final BrowserVersion browserVersion,
610             final DomElement element,
611             final Condition condition,
612             final DomNode scope,
613             final boolean fromQuerySelectorAll, final boolean throwOnSyntax) {
614 
615         switch (condition.getConditionType()) {
616             case ID_CONDITION:
617                 return condition.getValue().equals(element.getId());
618 
619             case CLASS_CONDITION:
620                 String v3 = condition.getValue();
621                 if (v3.indexOf('\\') > -1) {
622                     v3 = UNESCAPE_SELECTOR.matcher(v3).replaceAll("$1");
623                 }
624                 final String a3 = element.getAttributeDirect("class");
625                 return matchesWhitespaceSeparated(v3, a3);
626 
627             case ATTRIBUTE_CONDITION:
628                 final AttributeCondition attributeCondition = (AttributeCondition) condition;
629                 String value = attributeCondition.getValue();
630                 if (value != null) {
631                     if (value.indexOf('\\') > -1) {
632                         value = UNESCAPE_SELECTOR.matcher(value).replaceAll("$1");
633                     }
634                     final String name = attributeCondition.getLocalName();
635                     final String attrValue = element.getAttribute(name);
636                     if (attributeCondition.isCaseInSensitive() || DomElement.TYPE_ATTRIBUTE.equals(name)) {
637                         return ATTRIBUTE_NOT_DEFINED != attrValue && attrValue.equalsIgnoreCase(value);
638                     }
639                     return ATTRIBUTE_NOT_DEFINED != attrValue && attrValue.equals(value);
640                 }
641                 return element.hasAttribute(condition.getLocalName());
642 
643             case PREFIX_ATTRIBUTE_CONDITION:
644                 final AttributeCondition prefixAttributeCondition = (AttributeCondition) condition;
645                 final String prefixValue = prefixAttributeCondition.getValue();
646                 if (prefixAttributeCondition.isCaseInSensitive()) {
647                     return !StringUtils.isEmptyString(prefixValue)
648                             && StringUtils.startsWithIgnoreCase(
649                                     element.getAttribute(prefixAttributeCondition.getLocalName()), prefixValue);
650                 }
651                 return !StringUtils.isEmptyString(prefixValue)
652                         && element.getAttribute(prefixAttributeCondition.getLocalName()).startsWith(prefixValue);
653 
654             case SUFFIX_ATTRIBUTE_CONDITION:
655                 final AttributeCondition suffixAttributeCondition = (AttributeCondition) condition;
656                 final String suffixValue = suffixAttributeCondition.getValue();
657                 if (suffixAttributeCondition.isCaseInSensitive()) {
658                     return !StringUtils.isEmptyString(suffixValue)
659                             && StringUtils.endsWithIgnoreCase(
660                                     element.getAttribute(suffixAttributeCondition.getLocalName()), suffixValue);
661                 }
662                 return !StringUtils.isEmptyString(suffixValue)
663                         && element.getAttribute(suffixAttributeCondition.getLocalName()).endsWith(suffixValue);
664 
665             case SUBSTRING_ATTRIBUTE_CONDITION:
666                 final AttributeCondition substringAttributeCondition = (AttributeCondition) condition;
667                 final String substringValue = substringAttributeCondition.getValue();
668                 if (substringAttributeCondition.isCaseInSensitive()) {
669                     return !StringUtils.isEmptyString(substringValue)
670                             && StringUtils.containsIgnoreCase(
671                                     element.getAttribute(substringAttributeCondition.getLocalName()), substringValue);
672                 }
673                 return !StringUtils.isEmptyString(substringValue)
674                         && element.getAttribute(substringAttributeCondition.getLocalName()).contains(substringValue);
675 
676             case BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
677                 final AttributeCondition beginHyphenAttributeCondition = (AttributeCondition) condition;
678                 final String v = beginHyphenAttributeCondition.getValue();
679                 final String a = element.getAttribute(beginHyphenAttributeCondition.getLocalName());
680                 if (beginHyphenAttributeCondition.isCaseInSensitive()) {
681                     return matchesHyphenSeparated(
682                             StringUtils.toRootLowerCase(v),
683                             StringUtils.toRootLowerCase(a));
684                 }
685                 return matchesHyphenSeparated(v, a);
686 
687             case ONE_OF_ATTRIBUTE_CONDITION:
688                 final AttributeCondition oneOfAttributeCondition = (AttributeCondition) condition;
689                 final String v2 = oneOfAttributeCondition.getValue();
690                 final String a2 = element.getAttribute(oneOfAttributeCondition.getLocalName());
691                 if (oneOfAttributeCondition.isCaseInSensitive()) {
692                     return matchesWhitespaceSeparated(
693                             StringUtils.toRootLowerCase(v2),
694                             StringUtils.toRootLowerCase(a2));
695                 }
696                 return matchesWhitespaceSeparated(v2, a2);
697 
698             case LANG_CONDITION:
699                 final String lcLang = condition.getValue();
700                 final int lcLangLength = lcLang.length();
701                 for (DomNode node = element; node instanceof HtmlElement; node = node.getParentNode()) {
702                     final String nodeLang = ((HtmlElement) node).getAttributeDirect("lang");
703                     if (ATTRIBUTE_NOT_DEFINED != nodeLang) {
704                         // "en", "en-GB" should be matched by "en" but not "english"
705                         return nodeLang.startsWith(lcLang)
706                             && (nodeLang.length() == lcLangLength || '-' == nodeLang.charAt(lcLangLength));
707                     }
708                 }
709                 return false;
710 
711             case NOT_PSEUDO_CLASS_CONDITION:
712                 return !selectsAny(browserVersion, element, ((NotPseudoClassCondition) condition).getSelectors(),
713                                     scope, fromQuerySelectorAll, throwOnSyntax);
714 
715             case IS_PSEUDO_CLASS_CONDITION:
716                 return selectsAny(browserVersion, element, ((IsPseudoClassCondition) condition).getSelectors(),
717                                     scope, fromQuerySelectorAll, throwOnSyntax);
718 
719             case WHERE_PSEUDO_CLASS_CONDITION:
720                 // same as is
721                 return selectsAny(browserVersion, element, ((WherePseudoClassCondition) condition).getSelectors(),
722                                     scope, fromQuerySelectorAll, throwOnSyntax);
723 
724             case HAS_PSEUDO_CLASS_CONDITION:
725                 return selectsAny(browserVersion, element, ((HasPseudoClassCondition) condition).getSelectors(),
726                                     scope, fromQuerySelectorAll, throwOnSyntax);
727 
728             case NTH_PSEUDO_CLASS_CONDITION:
729                 return selectsNth(browserVersion, element, (NthPseudoClassCondition) condition,
730                                     scope, fromQuerySelectorAll, throwOnSyntax);
731 
732             case PSEUDO_CLASS_CONDITION:
733                 return selectsPseudoClass(browserVersion, element, condition, scope);
734 
735             default:
736                 if (LOG.isErrorEnabled()) {
737                     LOG.error("Unknown CSS condition type '" + condition.getConditionType() + "'.");
738                 }
739                 return false;
740         }
741     }
742 
743     /**
744      * Checks one of the nth-xxx() pseudo-classes; the position of the element is determined
745      * by counting the siblings (of the same type and/or matching the optional 'of S' selectors).
746      *
747      * @param browserVersion the browser version
748      * @param element the element to test
749      * @param condition the nth condition
750      * @param scope the context scope node used for evaluating relative selectors like :scope
751      * @param fromQuerySelectorAll whether this is called from {@link DomNode#querySelectorAll(String)}
752      * @param throwOnSyntax throw exception if the selector syntax is incorrect
753      * @return {@code true} if the condition applies
754      */
755     private static boolean selectsNth(final BrowserVersion browserVersion,
756             final DomElement element,
757             final NthPseudoClassCondition condition,
758             final DomNode scope,
759             final boolean fromQuerySelectorAll, final boolean throwOnSyntax) {
760         final SelectorList ofSelectors = condition.getSelectors();
761         if (ofSelectors != null
762                 && !selectsAny(browserVersion, element, ofSelectors, scope, fromQuerySelectorAll, throwOnSyntax)) {
763             return false;
764         }
765 
766         final NthType type = condition.getType();
767         final String nodeName = element.getNodeName();
768         int position = 0;
769         for (DomNode n = element; n != null; n = type.isFromEnd() ? n.getNextSibling() : n.getPreviousSibling()) {
770             if (n instanceof DomElement sibling
771                     && (!type.isOfType() || nodeName.equals(sibling.getNodeName()))
772                     && (ofSelectors == null || selectsAny(browserVersion, sibling, ofSelectors,
773                                                     scope, fromQuerySelectorAll, throwOnSyntax))) {
774                 position++;
775             }
776         }
777         return condition.matches(position);
778     }
779 
780     /**
781      * Returns true if the element is matched by at least one of the selectors.
782      *
783      * @param browserVersion the browser version
784      * @param element the element to test
785      * @param selectors the selectors
786      * @param scope the context scope node used for evaluating relative selectors like :scope
787      * @param fromQuerySelectorAll whether this is called from {@link DomNode#querySelectorAll(String)}
788      * @param throwOnSyntax throw exception if the selector syntax is incorrect
789      * @return {@code true} if at least one selector applies
790      */
791     private static boolean selectsAny(final BrowserVersion browserVersion,
792             final DomElement element,
793             final SelectorList selectors,
794             final DomNode scope,
795             final boolean fromQuerySelectorAll, final boolean throwOnSyntax) {
796         for (final Selector selector : selectors) {
797             if (selects(browserVersion, element, selector, null, scope, fromQuerySelectorAll, throwOnSyntax)) {
798                 return true;
799             }
800         }
801         return false;
802     }
803 
804     private static boolean matchesHyphenSeparated(final String condition, final String attribute) {
805         final int conditionLength = condition.length();
806         if (conditionLength < 1) {
807             if (attribute != ATTRIBUTE_NOT_DEFINED) {
808                 final int attribLength = attribute.length();
809                 return attribLength == 0 || '-' == attribute.charAt(0);
810             }
811             return false;
812         }
813 
814         final int attribLength = attribute.length();
815         if (attribLength < conditionLength) {
816             return false;
817         }
818         if (attribLength > conditionLength) {
819             return '-' == attribute.charAt(conditionLength)
820                     && attribute.startsWith(condition);
821         }
822         return attribute.equals(condition);
823     }
824 
825     private static boolean matchesWhitespaceSeparated(final String condition, final String attribute) {
826         final int conditionLength = condition.length();
827         if (conditionLength < 1) {
828             return false;
829         }
830 
831         final int attribLength = attribute.length();
832         if (attribLength < conditionLength) {
833             return false;
834         }
835 
836         int pos = attribute.indexOf(condition);
837         while (pos != -1) {
838             if (pos > 0 && !Character.isWhitespace(attribute.charAt(pos - 1))) {
839                 pos = attribute.indexOf(condition, pos + 1);
840             }
841             else {
842                 final int lastPos = pos + condition.length();
843                 if (lastPos >= attribLength || Character.isWhitespace(attribute.charAt(lastPos))) {
844                     return true;
845                 }
846                 pos = attribute.indexOf(condition, pos + 1);
847             }
848         }
849 
850         return false;
851     }
852 
853     @SuppressWarnings("PMD.UselessParentheses")
854     private static boolean selectsPseudoClass(
855             final BrowserVersion browserVersion,
856             final DomElement element,
857             final Condition condition,
858             final DomNode scope) {
859         final String value = StringUtils.toRootLowerCase(condition.getValue());
860         switch (value) {
861             case "root":
862                 return element == element.getPage().getDocumentElement();
863 
864             case "enabled":
865                 return element instanceof DisabledElement de && !de.isDisabled();
866 
867             case "disabled":
868                 return element instanceof DisabledElement de && de.isDisabled();
869 
870             case "focus":
871                 final HtmlPage htmlPage = element.getHtmlPageOrNull();
872                 if (htmlPage != null) {
873                     final DomElement focus = htmlPage.getFocusedElement();
874                     return element == focus;
875                 }
876                 return false;
877 
878             case "focus-within":
879                 final HtmlPage htmlPage2 = element.getHtmlPageOrNull();
880                 if (htmlPage2 != null) {
881                     final DomElement focus = htmlPage2.getFocusedElement();
882                     return element == focus || element.isAncestorOf(focus);
883                 }
884                 return false;
885 
886             case "focus-visible":
887                 final HtmlPage htmlPage3 = element.getHtmlPageOrNull();
888                 if (htmlPage3 != null) {
889                     final DomElement focus = htmlPage3.getFocusedElement();
890                     return element == focus
891                             && ((element instanceof HtmlInput hi && !hi.isReadOnly())
892                                 || (element instanceof HtmlTextArea hta && !hta.isReadOnly()));
893                 }
894                 return false;
895 
896             case "scope":
897                 return element == (scope == null ? element.getPage().getDocumentElement() : scope);
898 
899             case "checked":
900                 return (element instanceof HtmlCheckBoxInput hcbi && hcbi.isChecked())
901                         || (element instanceof HtmlRadioButtonInput hrbi && hrbi.isChecked())
902                                 || (element instanceof HtmlOption ho && ho.isSelected());
903 
904             case "required":
905                 return element instanceof HtmlElement he && he.isRequired();
906 
907             case "optional":
908                 return element instanceof HtmlElement he && he.isOptional();
909 
910             case "first-child":
911                 for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
912                     if (n instanceof DomElement) {
913                         return false;
914                     }
915                 }
916                 return true;
917 
918             case "last-child":
919                 for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
920                     if (n instanceof DomElement) {
921                         return false;
922                     }
923                 }
924                 return true;
925 
926             case "first-of-type":
927                 final String firstType = element.getNodeName();
928                 for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
929                     if (n instanceof DomElement && n.getNodeName().equals(firstType)) {
930                         return false;
931                     }
932                 }
933                 return true;
934 
935             case "last-of-type":
936                 final String lastType = element.getNodeName();
937                 for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
938                     if (n instanceof DomElement && n.getNodeName().equals(lastType)) {
939                         return false;
940                     }
941                 }
942                 return true;
943 
944             case "only-child":
945                 for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
946                     if (n instanceof DomElement) {
947                         return false;
948                     }
949                 }
950                 for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
951                     if (n instanceof DomElement) {
952                         return false;
953                     }
954                 }
955                 return true;
956 
957             case "only-of-type":
958                 final String type = element.getNodeName();
959                 for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
960                     if (n instanceof DomElement && n.getNodeName().equals(type)) {
961                         return false;
962                     }
963                 }
964                 for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
965                     if (n instanceof DomElement && n.getNodeName().equals(type)) {
966                         return false;
967                     }
968                 }
969                 return true;
970 
971             case "valid":
972                 if (element instanceof ValidatableHtmlElement validatable) {
973                     return validatable.willValidate()
974                                 && ((HtmlElement) validatable).isValid();
975                 }
976                 else if (element instanceof HtmlForm form) {
977                     return form.isValid();
978                 }
979                 return false;
980 
981             case "invalid":
982                 if (element instanceof ValidatableHtmlElement validatable) {
983                     return validatable.willValidate()
984                                 && !((HtmlElement) validatable).isValid();
985                 }
986                 else if (element instanceof HtmlForm form) {
987                     return !form.isValid();
988                 }
989                 return false;
990 
991             case "empty":
992                 return isEmpty(element);
993 
994             case "target":
995                 final String ref = element.getPage().getUrl().getRef();
996                 return StringUtils.isNotBlank(ref) && ref.equals(element.getId());
997 
998             case "hover":
999                 return element.isMouseOver();
1000 
1001             case "placeholder-shown":
1002                 return element instanceof HtmlInput hi
1003                         && StringUtils.isEmptyOrNull(hi.getValue())
1004                         && !StringUtils.isEmptyOrNull(hi.getPlaceholder());
1005 
1006             default:
1007                 return false;
1008         }
1009     }
1010 
1011     private static boolean isEmpty(final DomElement element) {
1012         for (DomNode n = element.getFirstChild(); n != null; n = n.getNextSibling()) {
1013             if (n instanceof DomElement || n instanceof DomText) {
1014                 return false;
1015             }
1016         }
1017         return true;
1018     }
1019 
1020     /**
1021      * Parses the CSS at the specified input source. If anything at all goes wrong, this method
1022      * returns an empty stylesheet.
1023      *
1024      * @param source the source from which to retrieve the CSS to be parsed
1025      * @param client the client
1026      * @return the stylesheet parsed from the specified input source
1027      */
1028     private static CSSStyleSheetImpl parseCSS(final InputSource source, final WebClient client) {
1029         CSSStyleSheetImpl ss;
1030 
1031         // use a pooled parser, if any available to avoid expensive recreation
1032         try (PooledCSS3Parser pooledParser = client.getCSS3Parser()) {
1033             final CSSErrorHandler errorHandler = client.getCssErrorHandler();
1034             final CSSOMParser parser = new CSSOMParser(pooledParser);
1035             parser.setErrorHandler(errorHandler);
1036             ss = parser.parseStyleSheet(source, null);
1037         }
1038         catch (final Throwable ex) {
1039             if (LOG.isErrorEnabled()) {
1040                 LOG.error("Error parsing CSS from '" + toString(source) + "': " + ex.getMessage(), ex);
1041             }
1042             ss = new CSSStyleSheetImpl();
1043         }
1044         return ss;
1045     }
1046 
1047     /**
1048      * Parses the given media string. If anything at all goes wrong, this
1049      * method returns an empty MediaList list.
1050      *
1051      * @param mediaString the source from which to retrieve the media to be parsed
1052      * @param webClient the {@link WebClient} to be used
1053      * @return the media parsed from the specified input source
1054      */
1055     public static MediaListImpl parseMedia(final String mediaString, final WebClient webClient) {
1056         return MEDIA.computeIfAbsent(mediaString, s -> {
1057             // get us a pooled parser for efficiency because a new parser is expensive
1058             try (PooledCSS3Parser pooledParser = webClient.getCSS3Parser()) {
1059                 final CSSOMParser parser = new CSSOMParser(pooledParser);
1060                 parser.setErrorHandler(webClient.getCssErrorHandler());
1061 
1062                 return new MediaListImpl(parser.parseMedia(mediaString));
1063             }
1064             catch (final Exception e) {
1065                 if (LOG.isErrorEnabled()) {
1066                     LOG.error("Error parsing CSS media from '" + mediaString + "': " + e.getMessage(), e);
1067                 }
1068             }
1069 
1070             return new MediaListImpl(null);
1071         });
1072     }
1073 
1074     /**
1075      * Returns the contents of the specified input source, ignoring any {@link IOException}s.
1076      * @param source the input source from which to read
1077      * @return the contents of the specified input source, or an empty string if an {@link IOException} occurs
1078      */
1079     private static String toString(final InputSource source) {
1080         try {
1081             final Reader reader = source.getReader();
1082             if (null != reader) {
1083                 // try to reset to produce some output
1084                 if (reader instanceof StringReader sr) {
1085                     sr.reset();
1086                 }
1087                 return IOUtils.toString(reader);
1088             }
1089             return "";
1090         }
1091         catch (final IOException e) {
1092             LOG.error(e.getMessage(), e);
1093             return "";
1094         }
1095     }
1096 
1097     /**
1098      * Validates the list of selectors.
1099      * @param selectorList the selectors
1100      * @param domNode the dom node the query should work on
1101      *
1102      * @throws CSSException if a selector is invalid
1103      */
1104     public static void validateSelectors(final SelectorList selectorList, final DomNode domNode) throws CSSException {
1105         for (final Selector selector : selectorList) {
1106             if (!isValidSelector(selector, domNode)) {
1107                 throw new CSSException("Invalid selector: " + selector, null);
1108             }
1109         }
1110     }
1111 
1112     private static boolean isValidSelector(final Selector selector, final DomNode domNode) {
1113         switch (selector.getSelectorType()) {
1114             case ELEMENT_NODE_SELECTOR:
1115                 final List<Condition> conditions = ((ElementSelector) selector).getConditions();
1116                 if (conditions != null) {
1117                     for (final Condition condition : conditions) {
1118                         if (!isValidCondition(condition, domNode)) {
1119                             return false;
1120                         }
1121                     }
1122                 }
1123                 return true;
1124             case DESCENDANT_SELECTOR:
1125                 final DescendantSelector ds = (DescendantSelector) selector;
1126                 return isValidSelector(ds.getAncestorSelector(), domNode)
1127                         && isValidSelector(ds.getSimpleSelector(), domNode);
1128             case CHILD_SELECTOR:
1129                 final ChildSelector cs = (ChildSelector) selector;
1130                 return isValidSelector(cs.getAncestorSelector(), domNode)
1131                         && isValidSelector(cs.getSimpleSelector(), domNode);
1132             case DIRECT_ADJACENT_SELECTOR:
1133                 final DirectAdjacentSelector das = (DirectAdjacentSelector) selector;
1134                 return isValidSelector(das.getSelector(), domNode)
1135                         && isValidSelector(das.getSimpleSelector(), domNode);
1136             case GENERAL_ADJACENT_SELECTOR:
1137                 final GeneralAdjacentSelector gas = (GeneralAdjacentSelector) selector;
1138                 return isValidSelector(gas.getSelector(), domNode)
1139                         && isValidSelector(gas.getSimpleSelector(), domNode);
1140             case PSEUDO_ELEMENT_SELECTOR:
1141                 // as of now (4.17) the htmlunit-cssparser accepts only supported selectors
1142                 // if ("first-line".equals(s)
1143                 //         || "first-letter".equals(s)
1144                 //         || "before".equals(s)
1145                 //         || "after".equals(s))
1146                 //     {
1147                 //         return new PseudoElementSelector(s, locator, doubleColon);
1148                 //     }
1149                 return true;
1150             case RELATIVE_SELECTOR:
1151                 final RelativeSelector rs = (RelativeSelector) selector;
1152                 return isValidSelector(rs.getSelector(), domNode);
1153             default:
1154                 if (LOG.isWarnEnabled()) {
1155                     LOG.warn("Unhandled CSS selector type '"
1156                                 + selector.getSelectorType() + "'. Accepting it silently.");
1157                 }
1158                 return true; // at least in a first time to break less stuff
1159         }
1160     }
1161 
1162     private static boolean isValidSelectors(final SelectorList selectors, final DomNode domNode) {
1163         for (final Selector selector : selectors) {
1164             if (!isValidSelector(selector, domNode)) {
1165                 return false;
1166             }
1167         }
1168         return true;
1169     }
1170 
1171     private static boolean isValidCondition(final Condition condition, final DomNode domNode) {
1172         switch (condition.getConditionType()) {
1173             case ATTRIBUTE_CONDITION:
1174             case ID_CONDITION:
1175             case LANG_CONDITION:
1176             case ONE_OF_ATTRIBUTE_CONDITION:
1177             case BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
1178             case CLASS_CONDITION:
1179             case PREFIX_ATTRIBUTE_CONDITION:
1180             case SUBSTRING_ATTRIBUTE_CONDITION:
1181             case SUFFIX_ATTRIBUTE_CONDITION:
1182                 return true;
1183             case NOT_PSEUDO_CLASS_CONDITION:
1184                 return isValidSelectors(((NotPseudoClassCondition) condition).getSelectors(), domNode);
1185             case IS_PSEUDO_CLASS_CONDITION:
1186                 return isValidSelectors(((IsPseudoClassCondition) condition).getSelectors(), domNode);
1187             case WHERE_PSEUDO_CLASS_CONDITION:
1188                 return isValidSelectors(((WherePseudoClassCondition) condition).getSelectors(), domNode);
1189             case HAS_PSEUDO_CLASS_CONDITION:
1190                 return isValidSelectors(((HasPseudoClassCondition) condition).getSelectors(), domNode);
1191             case NTH_PSEUDO_CLASS_CONDITION:
1192                 // the An+B argument is already checked by the parser; only the optional 'of S' list is left
1193                 final SelectorList nthSelectors = ((NthPseudoClassCondition) condition).getSelectors();
1194                 return nthSelectors == null || isValidSelectors(nthSelectors, domNode);
1195             case PSEUDO_CLASS_CONDITION:
1196                 String value = condition.getValue();
1197                 if (value.endsWith(")")) {
1198                     if (value.endsWith("()")) {
1199                         return false;
1200                     }
1201                     value = value.substring(0, value.indexOf('(') + 1) + ')';
1202                 }
1203 
1204                 value = StringUtils.toRootLowerCase(value);
1205                 if ("placeholder-shown".equals(value)) {
1206                     return true;
1207                 }
1208 
1209                 return CSS4_PSEUDO_CLASSES.contains(value);
1210             default:
1211                 if (LOG.isWarnEnabled()) {
1212                     LOG.warn("Unhandled CSS condition type '"
1213                                 + condition.getConditionType() + "'. Accepting it silently.");
1214                 }
1215                 return true;
1216         }
1217     }
1218 
1219     /**
1220      * Returns the {@link CssStyleSheet} imported by this rule.
1221      *
1222      * @param importRule the {@link CSSImportRuleImpl} that imports the {@link CssStyleSheet}
1223      * @return the {@link CssStyleSheet} imported by this rule
1224      */
1225     public CssStyleSheet getImportedStyleSheet(final CSSImportRuleImpl importRule) {
1226         CssStyleSheet sheet = imports_.get(importRule);
1227         if (sheet == null) {
1228             String url = UrlUtils.resolveUrl(getUri(), importRule.getHref());
1229             if (owner_ == null || !(owner_.getPage() instanceof HtmlPage page)) {
1230                 // nothing to load from; e.g. a constructed stylesheet
1231                 sheet = new CssStyleSheet(owner_, new CSSStyleSheetImpl(), url);
1232             }
1233             else {
1234                 // upgrade-insecure-requests of the Content-Security-Policy
1235                 final URL resolvedUrl = UrlUtils.toUrlSafe(url);
1236                 final URL upgradedUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, resolvedUrl);
1237                 if (upgradedUrl != resolvedUrl) {
1238                     url = upgradedUrl.toExternalForm();
1239                 }
1240 
1241                 if (ContentSecurityPolicy.allowsExternalStyle(page, null, upgradedUrl)) {
1242                     sheet = loadStylesheet(owner_, null, url);
1243                 }
1244                 else {
1245                     sheet = new CssStyleSheet(owner_, new CSSStyleSheetImpl(), url);
1246                     sheet.blockedByContentSecurityPolicy_ = true;
1247                 }
1248             }
1249             imports_.put(importRule, sheet);
1250         }
1251         return sheet;
1252     }
1253 
1254     /**
1255      * Loads all imported style sheets (including nested imports) like the browsers do before
1256      * the load event of the link element is fired.
1257      *
1258      * @return {@code false} if at least one import was blocked by the Content-Security-Policy
1259      */
1260     public boolean loadImports() {
1261         return loadImports(new HashSet<>());
1262     }
1263 
1264     private boolean loadImports(final Set<String> alreadyProcessing) {
1265         boolean allowed = true;
1266         for (final AbstractCSSRuleImpl rule : wrapped_.getCssRules().getRules()) {
1267             if (rule instanceof CSSImportRuleImpl importRule) {
1268                 final CssStyleSheet sheet = getImportedStyleSheet(importRule);
1269                 if (sheet.blockedByContentSecurityPolicy_) {
1270                     allowed = false;
1271                 }
1272                 else if (alreadyProcessing.add(sheet.getUri()) && !sheet.loadImports(alreadyProcessing)) {
1273                     allowed = false;
1274                 }
1275             }
1276         }
1277         return allowed;
1278     }
1279 
1280     /**
1281      * Returns {@code true} if this stylesheet is active, based on the media types it is associated with (if any).
1282      * @return {@code true} if this stylesheet is active, based on the media types it is associated with (if any)
1283      */
1284     public boolean isActive() {
1285         final String media;
1286         if (owner_ instanceof HtmlStyle style) {
1287             media = style.getMediaAttribute();
1288         }
1289         else if (owner_ instanceof HtmlLink link) {
1290             media = link.getMediaAttribute();
1291         }
1292         else {
1293             return true;
1294         }
1295 
1296         if (StringUtils.isBlank(media)) {
1297             return true;
1298         }
1299 
1300         final WebWindow webWindow = owner_.getPage().getEnclosingWindow();
1301         final MediaListImpl mediaList = parseMedia(media, webWindow.getWebClient());
1302         return isActive(mediaList, webWindow);
1303     }
1304 
1305     /**
1306      * Returns whether the specified {@link MediaList} is active or not.
1307      * @param mediaList the media list
1308      * @param webWindow the {@link WebWindow} for some basic data
1309      * @return whether the specified {@link MediaList} is active or not
1310      */
1311     public static boolean isActive(final MediaListImpl mediaList, final WebWindow webWindow) {
1312         if (mediaList.getLength() == 0) {
1313             return true;
1314         }
1315 
1316         final int length = mediaList.getLength();
1317         for (int i = 0; i < length; i++) {
1318             final MediaQuery mediaQuery = mediaList.mediaQuery(i);
1319             boolean isActive = isActive(mediaQuery, webWindow);
1320             if (mediaQuery.isNot()) {
1321                 isActive = !isActive;
1322             }
1323             if (isActive) {
1324                 return true;
1325             }
1326         }
1327         return false;
1328     }
1329 
1330     private static boolean isActive(final MediaQuery mediaQuery, final WebWindow webWindow) {
1331         final String mediaType = mediaQuery.getMedia();
1332         if ("screen".equalsIgnoreCase(mediaType) || "all".equalsIgnoreCase(mediaType)) {
1333             for (final Property property : mediaQuery.getProperties()) {
1334                 final double val;
1335                 switch (property.getName()) {
1336                     case "max-width":
1337                         val = pixelValue(property.getValue(), webWindow);
1338                         if (val == -1 || val < webWindow.getInnerWidth()) {
1339                             return false;
1340                         }
1341                         break;
1342 
1343                     case "min-width":
1344                         val = pixelValue(property.getValue(), webWindow);
1345                         if (val == -1 || val > webWindow.getInnerWidth()) {
1346                             return false;
1347                         }
1348                         break;
1349 
1350                     case "max-device-width":
1351                         val = pixelValue(property.getValue(), webWindow);
1352                         if (val == -1 || val < webWindow.getScreen().getWidth()) {
1353                             return false;
1354                         }
1355                         break;
1356 
1357                     case "min-device-width":
1358                         val = pixelValue(property.getValue(), webWindow);
1359                         if (val == -1 || val > webWindow.getScreen().getWidth()) {
1360                             return false;
1361                         }
1362                         break;
1363 
1364                     case "max-height":
1365                         val = pixelValue(property.getValue(), webWindow);
1366                         if (val == -1 || val < webWindow.getInnerHeight()) {
1367                             return false;
1368                         }
1369                         break;
1370 
1371                     case "min-height":
1372                         val = pixelValue(property.getValue(), webWindow);
1373                         if (val == -1 || val > webWindow.getInnerHeight()) {
1374                             return false;
1375                         }
1376                         break;
1377 
1378                     case "max-device-height":
1379                         val = pixelValue(property.getValue(), webWindow);
1380                         if (val == -1 || val < webWindow.getScreen().getHeight()) {
1381                             return false;
1382                         }
1383                         break;
1384 
1385                     case "min-device-height":
1386                         val = pixelValue(property.getValue(), webWindow);
1387                         if (val == -1 || val > webWindow.getScreen().getHeight()) {
1388                             return false;
1389                         }
1390                         break;
1391 
1392                     case "resolution":
1393                         final CSSValueImpl propValue = property.getValue();
1394                         val = resolutionValue(propValue);
1395                         if (propValue == null) {
1396                             return true;
1397                         }
1398                         if (val == -1 || Math.round(val) != webWindow.getScreen().getDeviceXDPI()) {
1399                             return false;
1400                         }
1401                         break;
1402 
1403                     case "max-resolution":
1404                         val = resolutionValue(property.getValue());
1405                         if (val == -1 || val < webWindow.getScreen().getDeviceXDPI()) {
1406                             return false;
1407                         }
1408                         break;
1409 
1410                     case "min-resolution":
1411                         val = resolutionValue(property.getValue());
1412                         if (val == -1 || val > webWindow.getScreen().getDeviceXDPI()) {
1413                             return false;
1414                         }
1415                         break;
1416 
1417                     case "orientation":
1418                         final CSSValueImpl cssValue = property.getValue();
1419                         if (cssValue == null) {
1420                             LOG.warn("CSSValue is null not supported for feature 'orientation'");
1421                             return true;
1422                         }
1423 
1424                         final String orient = cssValue.getCssText();
1425                         if ("portrait".equals(orient)) {
1426                             if (webWindow.getInnerWidth() > webWindow.getInnerHeight()) {
1427                                 return false;
1428                             }
1429                         }
1430                         else if ("landscape".equals(orient)) {
1431                             if (webWindow.getInnerWidth() < webWindow.getInnerHeight()) {
1432                                 return false;
1433                             }
1434                         }
1435                         else {
1436                             if (LOG.isWarnEnabled()) {
1437                                 LOG.warn("CSSValue '" + property.getValue().getCssText()
1438                                             + "' not supported for feature 'orientation'.");
1439                             }
1440                             return false;
1441                         }
1442                         break;
1443 
1444                     default:
1445                 }
1446             }
1447             return true;
1448         }
1449         else if ("print".equalsIgnoreCase(mediaType)) {
1450             final Page page = webWindow.getEnclosedPage();
1451             if (page instanceof SgmlPage sgmlPage) {
1452                 return sgmlPage.isPrinting();
1453             }
1454         }
1455         return false;
1456     }
1457 
1458     @SuppressWarnings("PMD.UselessParentheses")
1459     private static double pixelValue(final CSSValueImpl cssValue, final WebWindow webWindow) {
1460         if (cssValue == null) {
1461             LOG.warn("CSSValue is null but has to be a 'px', 'em', '%', 'ex', 'ch', "
1462                     + "'vw', 'vh', 'vmin', 'vmax', 'dvw', 'dvh', 'dvmin', 'dvmax', "
1463                     + "'lvw', 'lvh', 'lvmin', 'lvmax', 'svw', 'svh', 'svmin', 'svmax', "
1464                     + "'rem', 'mm', 'cm', 'Q', or 'pt' value.");
1465             return -1;
1466         }
1467 
1468         final LexicalUnit.LexicalUnitType luType = cssValue.getLexicalUnitType();
1469         if (luType != null) {
1470             final int dpi;
1471 
1472             switch (luType) {
1473                 case PIXEL:
1474                     return cssValue.getDoubleValue();
1475                 case EM:
1476                     // hard coded default for the moment 16px = 1 em
1477                     return 16f * cssValue.getDoubleValue();
1478                 case PERCENTAGE:
1479                     // hard coded default for the moment 16px = 100%
1480                     return 0.16f * cssValue.getDoubleValue();
1481                 case EX:
1482                     // hard coded default for the moment 16px = 100%
1483                     return 0.16f * cssValue.getDoubleValue();
1484                 case CH:
1485                     // hard coded default for the moment 16px = 100%
1486                     return 0.16f * cssValue.getDoubleValue();
1487                 case VW:
1488                     // hard coded default for the moment 16px = 100%
1489                     return 0.16f * cssValue.getDoubleValue();
1490                 case VH:
1491                     // hard coded default for the moment 16px = 100%
1492                     return 0.16f * cssValue.getDoubleValue();
1493                 case VMIN:
1494                     // hard coded default for the moment 16px = 100%
1495                     return 0.16f * cssValue.getDoubleValue();
1496                 case VMAX:
1497                     // hard coded default for the moment 16px = 100%
1498                     return 0.16f * cssValue.getDoubleValue();
1499                 case DVW:
1500                     // hard coded default for the moment 16px = 100%
1501                     return 0.16f * cssValue.getDoubleValue();
1502                 case DVH:
1503                     // hard coded default for the moment 16px = 100%
1504                     return 0.16f * cssValue.getDoubleValue();
1505                 case DVMIN:
1506                     // hard coded default for the moment 16px = 100%
1507                     return 0.16f * cssValue.getDoubleValue();
1508                 case DVMAX:
1509                     // hard coded default for the moment 16px = 100%
1510                     return 0.16f * cssValue.getDoubleValue();
1511                 case LVW:
1512                     // hard coded default for the moment 16px = 100%
1513                     return 0.16f * cssValue.getDoubleValue();
1514                 case LVH:
1515                     // hard coded default for the moment 16px = 100%
1516                     return 0.16f * cssValue.getDoubleValue();
1517                 case LVMIN:
1518                     // hard coded default for the moment 16px = 100%
1519                     return 0.16f * cssValue.getDoubleValue();
1520                 case LVMAX:
1521                     // hard coded default for the moment 16px = 100%
1522                     return 0.16f * cssValue.getDoubleValue();
1523                 case SVW:
1524                     // hard coded default for the moment 16px = 100%
1525                     return 0.16f * cssValue.getDoubleValue();
1526                 case SVH:
1527                     // hard coded default for the moment 16px = 100%
1528                     return 0.16f * cssValue.getDoubleValue();
1529                 case SVMIN:
1530                     // hard coded default for the moment 16px = 100%
1531                     return 0.16f * cssValue.getDoubleValue();
1532                 case SVMAX:
1533                     // hard coded default for the moment 16px = 100%
1534                     return 0.16f * cssValue.getDoubleValue();
1535                 case REM:
1536                     // hard coded default for the moment 16px = 100%
1537                     return 0.16f * cssValue.getDoubleValue();
1538                 case MILLIMETER:
1539                     dpi = webWindow.getScreen().getDeviceXDPI();
1540                     return (dpi / 25.4f) * cssValue.getDoubleValue();
1541                 case QUARTER:
1542                     // One quarter of a millimeter. 1Q = 1/40th of 1cm.
1543                     dpi = webWindow.getScreen().getDeviceXDPI();
1544                     return ((dpi / 25.4f) * cssValue.getDoubleValue()) / 4d;
1545                 case CENTIMETER:
1546                     dpi = webWindow.getScreen().getDeviceXDPI();
1547                     return (dpi / 2.54f) * cssValue.getDoubleValue();
1548                 case POINT:
1549                     dpi = webWindow.getScreen().getDeviceXDPI();
1550                     return (dpi / 72f) * cssValue.getDoubleValue();
1551                 default:
1552                     break;
1553             }
1554         }
1555         if (LOG.isWarnEnabled()) {
1556             LOG.warn("CSSValue '" + cssValue.getCssText()
1557                         + "' has to be a 'px', 'em', '%', 'ex', 'ch', "
1558                         + "'vw', 'vh', 'vmin', 'vmax', 'dvw', 'dvh', 'dvmin', 'dvmax', "
1559                         + "'lvw', 'lvh', 'lvmin', 'lvmax', 'svw', 'svh', 'svmin', 'svmax', "
1560                         + "'rem', 'mm', 'cm', 'Q', or 'pt' value.");
1561         }
1562         return -1;
1563     }
1564 
1565     private static double resolutionValue(final CSSValueImpl cssValue) {
1566         if (cssValue == null) {
1567             LOG.warn("CSSValue is null but has to be a 'dpi', 'dpcm', or 'dppx' value.");
1568             return -1;
1569         }
1570 
1571         if (cssValue.getPrimitiveType() == CSSPrimitiveValueType.CSS_DIMENSION) {
1572             final String text = cssValue.getCssText();
1573             if (text.endsWith("dpi")) {
1574                 return cssValue.getDoubleValue();
1575             }
1576             if (text.endsWith("dpcm")) {
1577                 return 2.54f * cssValue.getDoubleValue();
1578             }
1579             if (text.endsWith("dppx")) {
1580                 return 96 * cssValue.getDoubleValue();
1581             }
1582             // 'x' is an alias for 'dppx'
1583             if (text.endsWith("x")) {
1584                 return 96 * cssValue.getDoubleValue();
1585             }
1586         }
1587 
1588         if (LOG.isWarnEnabled()) {
1589             LOG.warn("CSSValue '" + cssValue.getCssText() + "' has to be a 'dpi', 'dpcm', 'dppx' or 'x' value.");
1590         }
1591         return -1;
1592     }
1593 
1594     /**
1595      * Modifies the specified style object by adding any style rules which apply to the specified
1596      * element.
1597      *
1598      * @param style the style to modify
1599      * @param element the element to which style rules must apply in order for them to be added to
1600      *        the specified style
1601      * @param pseudoElement a string specifying the pseudo-element to match (maybe {@code null})
1602      * @param scope the context scope node used for evaluating relative selectors like :scope
1603      */
1604     public void modifyIfNecessary(final ComputedCssStyleDeclaration style,
1605             final DomElement element,
1606             final String pseudoElement,
1607             final DomNode scope) {
1608 
1609         final BrowserVersion browser = element.getPage().getWebClient().getBrowserVersion();
1610         final List<CSSStyleSheetImpl.SelectorEntry> matchingRules =
1611                 selects(getRuleIndex(), browser, element, pseudoElement, scope, false);
1612         for (final CSSStyleSheetImpl.SelectorEntry entry : matchingRules) {
1613             final CSSStyleDeclarationImpl dec = entry.getRule().getStyle();
1614             style.applyStyleFromSelector(dec, entry.getSelector());
1615         }
1616     }
1617 
1618     private CSSStyleSheetImpl.CSSStyleSheetRuleIndex getRuleIndex() {
1619         final CSSStyleSheetImpl styleSheet = getWrappedSheet();
1620         CSSStyleSheetImpl.CSSStyleSheetRuleIndex index = styleSheet.getRuleIndex();
1621 
1622         if (index == null) {
1623             index = new CSSStyleSheetImpl.CSSStyleSheetRuleIndex();
1624             final CSSRuleListImpl ruleList = styleSheet.getCssRules();
1625             index(index, ruleList, new HashSet<>());
1626 
1627             styleSheet.setRuleIndex(index);
1628         }
1629         return index;
1630     }
1631 
1632     private void index(final CSSStyleSheetImpl.CSSStyleSheetRuleIndex index, final CSSRuleListImpl ruleList,
1633             final Set<String> alreadyProcessing) {
1634 
1635         for (final AbstractCSSRuleImpl rule : ruleList.getRules()) {
1636             if (rule instanceof CSSStyleRuleImpl styleRule) {
1637                 final SelectorList selectors = styleRule.getSelectors();
1638                 for (final Selector selector : selectors) {
1639                     final SimpleSelector simpleSel = selector.getSimpleSelector();
1640                     if (SelectorType.ELEMENT_NODE_SELECTOR == simpleSel.getSelectorType()) {
1641                         final ElementSelector es = (ElementSelector) simpleSel;
1642                         boolean wasClass = false;
1643                         final List<Condition> conds = es.getConditions();
1644                         if (conds != null && conds.size() == 1) {
1645                             final Condition c = conds.get(0);
1646                             if (ConditionType.CLASS_CONDITION == c.getConditionType()) {
1647                                 index.addClassSelector(es, c.getValue(), selector, styleRule);
1648                                 wasClass = true;
1649                             }
1650                         }
1651                         if (!wasClass) {
1652                             index.addElementSelector(es, selector, styleRule);
1653                         }
1654                     }
1655                     else {
1656                         index.addOtherSelector(selector, styleRule);
1657                     }
1658                 }
1659             }
1660             else if (rule instanceof CSSImportRuleImpl importRule) {
1661 
1662                 final CssStyleSheet sheet = getImportedStyleSheet(importRule);
1663 
1664                 if (!alreadyProcessing.contains(sheet.getUri())) {
1665                     final CSSRuleListImpl sheetRuleList = sheet.getWrappedSheet().getCssRules();
1666                     alreadyProcessing.add(sheet.getUri());
1667 
1668                     final MediaListImpl mediaList = importRule.getMedia();
1669                     if (mediaList.getLength() == 0 && index.getMediaList().getLength() == 0) {
1670                         index(index, sheetRuleList, alreadyProcessing);
1671                     }
1672                     else {
1673                         index(index.addMedia(mediaList), sheetRuleList, alreadyProcessing);
1674                     }
1675                 }
1676             }
1677             else if (rule instanceof CSSMediaRuleImpl mediaRule) {
1678                 final MediaListImpl mediaList = mediaRule.getMediaList();
1679                 if (mediaList.getLength() == 0 && index.getMediaList().getLength() == 0) {
1680                     index(index, mediaRule.getCssRules(), alreadyProcessing);
1681                 }
1682                 else {
1683                     index(index.addMedia(mediaList), mediaRule.getCssRules(), alreadyProcessing);
1684                 }
1685             }
1686         }
1687     }
1688 
1689     private List<CSSStyleSheetImpl.SelectorEntry> selects(
1690                             final CSSStyleSheetImpl.CSSStyleSheetRuleIndex index,
1691                             final BrowserVersion browserVersion,
1692                             final DomElement element,
1693                             final String pseudoElement,
1694                             final DomNode scope,
1695                             final boolean fromQuerySelectorAll) {
1696 
1697         final List<CSSStyleSheetImpl.SelectorEntry> matchingRules = new ArrayList<>();
1698 
1699         if (isActive(index.getMediaList(), element.getPage().getEnclosingWindow())) {
1700             final String elementName = element.getLowercaseName();
1701             final String[] classes = StringUtils.splitAtJavaWhitespace(
1702                                                             element.getAttributeDirect("class"));
1703             final Iterator<CSSStyleSheetImpl.SelectorEntry> iter =
1704                     index.getSelectorEntriesIteratorFor(elementName, classes);
1705 
1706             CSSStyleSheetImpl.SelectorEntry entry = iter.next();
1707             while (null != entry) {
1708                 if (selects(browserVersion, element, entry.getSelector(),
1709                             pseudoElement, scope, fromQuerySelectorAll, false)) {
1710                     matchingRules.add(entry);
1711                 }
1712                 entry = iter.next();
1713             }
1714 
1715             for (final CSSStyleSheetImpl.CSSStyleSheetRuleIndex child : index.getChildren()) {
1716                 matchingRules.addAll(selects(child, browserVersion,
1717                                                     element, pseudoElement, scope, fromQuerySelectorAll));
1718             }
1719         }
1720 
1721         return matchingRules;
1722     }
1723 }