1/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
4 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
5 * Copyright (C) 2005-2014 Apple Inc. All rights reserved.
6 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
7 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
9 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
10 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
11 * Copyright (C) 2012, 2013 Google Inc. All rights reserved.
12 * Copyright (C) 2014 Igalia S.L.
13 *
14 * This library is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU Library General Public
16 * License as published by the Free Software Foundation; either
17 * version 2 of the License, or (at your option) any later version.
18 *
19 * This library is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * Library General Public License for more details.
23 *
24 * You should have received a copy of the GNU Library General Public License
25 * along with this library; see the file COPYING.LIB. If not, write to
26 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27 * Boston, MA 02110-1301, USA.
28 */
29
30#include "config.h"
31#include "StyleResolver.h"
32
33#include "CSSCalculationValue.h"
34#include "CSSCursorImageValue.h"
35#include "CSSCustomPropertyValue.h"
36#include "CSSDefaultStyleSheets.h"
37#include "CSSFilterImageValue.h"
38#include "CSSFontSelector.h"
39#include "CSSFunctionValue.h"
40#include "CSSGradientValue.h"
41#include "CSSImageSetValue.h"
42#include "CSSImageValue.h"
43#include "CSSKeyframeRule.h"
44#include "CSSKeyframesRule.h"
45#include "CSSPaintImageValue.h"
46#include "CSSParser.h"
47#include "CSSPrimitiveValueMappings.h"
48#include "CSSPropertyNames.h"
49#include "CSSReflectValue.h"
50#include "CSSSelector.h"
51#include "CSSShadowValue.h"
52#include "CSSStyleRule.h"
53#include "CSSStyleSheet.h"
54#include "CSSValueList.h"
55#include "CSSValuePool.h"
56#include "CachedResourceLoader.h"
57#include "ElementRuleCollector.h"
58#include "FilterOperation.h"
59#include "Frame.h"
60#include "FrameSelection.h"
61#include "FrameView.h"
62#include "HTMLInputElement.h"
63#include "HTMLMarqueeElement.h"
64#include "HTMLNames.h"
65#include "HTMLSlotElement.h"
66#include "HTMLTableElement.h"
67#include "HTMLTextAreaElement.h"
68#include "InspectorInstrumentation.h"
69#include "KeyframeList.h"
70#include "Logging.h"
71#include "MathMLElement.h"
72#include "MathMLNames.h"
73#include "MediaList.h"
74#include "MediaQueryEvaluator.h"
75#include "NodeRenderStyle.h"
76#include "PageRuleCollector.h"
77#include "PaintWorkletGlobalScope.h"
78#include "Pair.h"
79#include "Quirks.h"
80#include "RenderScrollbar.h"
81#include "RenderStyleConstants.h"
82#include "RenderTheme.h"
83#include "RenderView.h"
84#include "RuleSet.h"
85#include "RuntimeEnabledFeatures.h"
86#include "SVGDocument.h"
87#include "SVGDocumentExtensions.h"
88#include "SVGFontFaceElement.h"
89#include "SVGNames.h"
90#include "SVGSVGElement.h"
91#include "SVGURIReference.h"
92#include "Settings.h"
93#include "ShadowRoot.h"
94#include "SharedStringHash.h"
95#include "StyleBuilder.h"
96#include "StyleColor.h"
97#include "StyleCachedImage.h"
98#include "StyleFontSizeFunctions.h"
99#include "StyleGeneratedImage.h"
100#include "StyleProperties.h"
101#include "StylePropertyShorthand.h"
102#include "StyleRule.h"
103#include "StyleSheetContents.h"
104#include "TransformFunctions.h"
105#include "TransformOperations.h"
106#include "UserAgentStyleSheets.h"
107#include "ViewportStyleResolver.h"
108#include "VisitedLinkState.h"
109#include "WebKitFontFamilyNames.h"
110#include <bitset>
111#include <wtf/Seconds.h>
112#include <wtf/StdLibExtras.h>
113#include <wtf/Vector.h>
114#include <wtf/text/AtomicStringHash.h>
115
116
117#if ENABLE(DASHBOARD_SUPPORT)
118#endif
119
120#if ENABLE(VIDEO_TRACK)
121#endif
122
123namespace WebCore {
124
125using namespace HTMLNames;
126
127static const CSSPropertyID firstLowPriorityProperty = static_cast<CSSPropertyID>(lastHighPriorityProperty + 1);
128
129static void extractDirectionAndWritingMode(const RenderStyle&, const StyleResolver::MatchResult&, TextDirection&, WritingMode&);
130
131inline void StyleResolver::State::cacheBorderAndBackground()
132{
133 m_hasUAAppearance = m_style->hasAppearance();
134 if (m_hasUAAppearance) {
135 m_borderData = m_style->border();
136 m_backgroundData = m_style->backgroundLayers();
137 m_backgroundColor = m_style->backgroundColor();
138 }
139}
140
141inline void StyleResolver::State::clear()
142{
143 m_element = nullptr;
144 m_parentStyle = nullptr;
145 m_ownedParentStyle = nullptr;
146 m_cssToLengthConversionData = CSSToLengthConversionData();
147}
148
149void StyleResolver::MatchResult::addMatchedProperties(const StyleProperties& properties, StyleRule* rule, unsigned linkMatchType, PropertyWhitelistType propertyWhitelistType, Style::ScopeOrdinal styleScopeOrdinal)
150{
151 m_matchedProperties.grow(m_matchedProperties.size() + 1);
152 StyleResolver::MatchedProperties& newProperties = m_matchedProperties.last();
153 newProperties.properties = const_cast<StyleProperties*>(&properties);
154 newProperties.linkMatchType = linkMatchType;
155 newProperties.whitelistType = propertyWhitelistType;
156 newProperties.styleScopeOrdinal = styleScopeOrdinal;
157 matchedRules.append(rule);
158
159 if (styleScopeOrdinal != Style::ScopeOrdinal::Element)
160 isCacheable = false;
161
162 if (isCacheable) {
163 for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
164 // Currently the property cache only copy the non-inherited values and resolve
165 // the inherited ones.
166 // Here we define some exception were we have to resolve some properties that are not inherited
167 // by default. If those exceptions become too common on the web, it should be possible
168 // to build a list of exception to resolve instead of completely disabling the cache.
169
170 StyleProperties::PropertyReference current = properties.propertyAt(i);
171 if (!current.isInherited()) {
172 // If the property value is explicitly inherited, we need to apply further non-inherited properties
173 // as they might override the value inherited here. For this reason we don't allow declarations with
174 // explicitly inherited properties to be cached.
175 const CSSValue& value = *current.value();
176 if (value.isInheritedValue()) {
177 isCacheable = false;
178 break;
179 }
180
181 // The value currentColor has implicitely the same side effect. It depends on the value of color,
182 // which is an inherited value, making the non-inherited property implicitly inherited.
183 if (is<CSSPrimitiveValue>(value) && downcast<CSSPrimitiveValue>(value).valueID() == CSSValueCurrentcolor) {
184 isCacheable = false;
185 break;
186 }
187
188 if (value.hasVariableReferences()) {
189 isCacheable = false;
190 break;
191 }
192 }
193 }
194 }
195}
196
197StyleResolver::StyleResolver(Document& document)
198 : m_ruleSets(*this)
199 , m_matchedPropertiesCacheSweepTimer(*this, &StyleResolver::sweepMatchedPropertiesCache)
200 , m_document(document)
201#if ENABLE(CSS_DEVICE_ADAPTATION)
202 , m_viewportStyleResolver(ViewportStyleResolver::create(&document))
203#endif
204 , m_styleMap(this)
205 , m_matchAuthorAndUserStyles(m_document.settings().authorAndUserStylesEnabled())
206{
207 Element* root = m_document.documentElement();
208
209 CSSDefaultStyleSheets::initDefaultStyle(root);
210
211 // construct document root element default style. this is needed
212 // to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
213 // This is here instead of constructor, because when constructor is run,
214 // document doesn't have documentElement
215 // NOTE: this assumes that element that gets passed to styleForElement -call
216 // is always from the document that owns the style selector
217 FrameView* view = m_document.view();
218 if (view)
219 m_mediaQueryEvaluator = MediaQueryEvaluator { view->mediaType() };
220 else
221 m_mediaQueryEvaluator = MediaQueryEvaluator { "all" };
222
223 if (root) {
224 m_rootDefaultStyle = styleForElement(*root, m_document.renderStyle(), nullptr, RuleMatchingBehavior::MatchOnlyUserAgentRules).renderStyle;
225 // Turn off assertion against font lookups during style resolver initialization. We may need root style font for media queries.
226 m_document.fontSelector().incrementIsComputingRootStyleFont();
227 m_rootDefaultStyle->fontCascade().update(&m_document.fontSelector());
228 m_rootDefaultStyle->fontCascade().primaryFont();
229 m_document.fontSelector().decrementIsComputingRootStyleFont();
230 }
231
232 if (m_rootDefaultStyle && view)
233 m_mediaQueryEvaluator = MediaQueryEvaluator { view->mediaType(), m_document, m_rootDefaultStyle.get() };
234
235 m_ruleSets.resetAuthorStyle();
236 m_ruleSets.resetUserAgentMediaQueryStyle();
237}
238
239void StyleResolver::addCurrentSVGFontFaceRules()
240{
241#if ENABLE(SVG_FONTS)
242 if (m_document.svgExtensions()) {
243 const HashSet<SVGFontFaceElement*>& svgFontFaceElements = m_document.svgExtensions()->svgFontFaceElements();
244 for (auto* svgFontFaceElement : svgFontFaceElements)
245 m_document.fontSelector().addFontFaceRule(svgFontFaceElement->fontFaceRule(), svgFontFaceElement->isInUserAgentShadowTree());
246 }
247#endif
248}
249
250void StyleResolver::appendAuthorStyleSheets(const Vector<RefPtr<CSSStyleSheet>>& styleSheets)
251{
252 m_ruleSets.appendAuthorStyleSheets(styleSheets, &m_mediaQueryEvaluator, m_inspectorCSSOMWrappers, this);
253
254 if (auto renderView = document().renderView())
255 renderView->style().fontCascade().update(&document().fontSelector());
256
257#if ENABLE(CSS_DEVICE_ADAPTATION)
258 viewportStyleResolver()->resolve();
259#endif
260}
261
262// This is a simplified style setting function for keyframe styles
263void StyleResolver::addKeyframeStyle(Ref<StyleRuleKeyframes>&& rule)
264{
265 AtomicString s(rule->name());
266 m_keyframesRuleMap.set(s.impl(), WTFMove(rule));
267}
268
269StyleResolver::~StyleResolver()
270{
271 RELEASE_ASSERT(!m_document.isResolvingTreeStyle());
272 RELEASE_ASSERT(!m_isDeleted);
273 m_isDeleted = true;
274
275#if ENABLE(CSS_DEVICE_ADAPTATION)
276 m_viewportStyleResolver->clearDocument();
277#endif
278}
279
280void StyleResolver::sweepMatchedPropertiesCache()
281{
282 // Look for cache entries containing a style declaration with a single ref and remove them.
283 // This may happen when an element attribute mutation causes it to generate a new inlineStyle()
284 // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one.
285 Vector<unsigned, 16> toRemove;
286 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
287 MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
288 for (; it != end; ++it) {
289 Vector<MatchedProperties>& matchedProperties = it->value.matchedProperties;
290 for (size_t i = 0; i < matchedProperties.size(); ++i) {
291 if (matchedProperties[i].properties->hasOneRef()) {
292 toRemove.append(it->key);
293 break;
294 }
295 }
296 }
297 for (size_t i = 0; i < toRemove.size(); ++i)
298 m_matchedPropertiesCache.remove(toRemove[i]);
299
300 m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
301}
302
303StyleResolver::State::State(const Element& element, const RenderStyle* parentStyle, const RenderStyle* documentElementStyle, const SelectorFilter* selectorFilter)
304 : m_element(&element)
305 , m_parentStyle(parentStyle)
306 , m_selectorFilter(selectorFilter)
307 , m_elementLinkState(element.document().visitedLinkState().determineLinkState(element))
308{
309 bool resetStyleInheritance = hasShadowRootParent(element) && downcast<ShadowRoot>(element.parentNode())->resetStyleInheritance();
310 if (resetStyleInheritance)
311 m_parentStyle = nullptr;
312
313 auto& document = element.document();
314 auto* documentElement = document.documentElement();
315 if (!documentElement || documentElement == &element)
316 m_rootElementStyle = document.renderStyle();
317 else
318 m_rootElementStyle = documentElementStyle ? documentElementStyle : documentElement->renderStyle();
319
320 updateConversionData();
321}
322
323inline void StyleResolver::State::updateConversionData()
324{
325 m_cssToLengthConversionData = CSSToLengthConversionData(m_style.get(), m_rootElementStyle, m_element ? m_element->document().renderView() : nullptr);
326}
327
328inline void StyleResolver::State::setStyle(std::unique_ptr<RenderStyle> style)
329{
330 m_style = WTFMove(style);
331 updateConversionData();
332}
333
334inline void StyleResolver::State::setParentStyle(std::unique_ptr<RenderStyle> parentStyle)
335{
336 m_ownedParentStyle = WTFMove(parentStyle);
337 m_parentStyle = m_ownedParentStyle.get();
338}
339
340static inline bool isAtShadowBoundary(const Element& element)
341{
342 auto* parentNode = element.parentNode();
343 return parentNode && parentNode->isShadowRoot();
344}
345
346void StyleResolver::setNewStateWithElement(const Element& element)
347{
348 // Apply the declaration to the style. This is a simplified version of the logic in styleForElement.
349 m_state = State(element, nullptr);
350}
351
352ElementStyle StyleResolver::styleForElement(const Element& element, const RenderStyle* parentStyle, const RenderStyle* parentBoxStyle, RuleMatchingBehavior matchingBehavior, const SelectorFilter* selectorFilter)
353{
354 RELEASE_ASSERT(!m_isDeleted);
355
356 m_state = State(element, parentStyle, m_overrideDocumentElementStyle, selectorFilter);
357 State& state = m_state;
358
359 if (state.parentStyle()) {
360 state.setStyle(RenderStyle::createPtr());
361 state.style()->inheritFrom(*state.parentStyle());
362 } else {
363 state.setStyle(defaultStyleForElement());
364 state.setParentStyle(RenderStyle::clonePtr(*state.style()));
365 }
366
367 auto& style = *state.style();
368
369 if (element.isLink()) {
370 style.setIsLink(true);
371 InsideLink linkState = state.elementLinkState();
372 if (linkState != InsideLink::NotInside) {
373 bool forceVisited = InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoClassVisited);
374 if (forceVisited)
375 linkState = InsideLink::InsideVisited;
376 }
377 style.setInsideLink(linkState);
378 }
379
380 CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(element);
381
382 ElementRuleCollector collector(element, m_ruleSets, m_state.selectorFilter());
383 collector.setMedium(&m_mediaQueryEvaluator);
384
385 if (matchingBehavior == RuleMatchingBehavior::MatchOnlyUserAgentRules)
386 collector.matchUARules();
387 else
388 collector.matchAllRules(m_matchAuthorAndUserStyles, matchingBehavior != RuleMatchingBehavior::MatchAllRulesExcludingSMIL);
389
390 if (collector.matchedPseudoElementIds())
391 style.setHasPseudoStyles(collector.matchedPseudoElementIds());
392
393 // This is required for style sharing.
394 if (collector.didMatchUncommonAttributeSelector())
395 style.setUnique();
396
397 auto elementStyleRelations = Style::commitRelationsToRenderStyle(style, element, collector.styleRelations());
398
399 applyMatchedProperties(collector.matchedResult(), element);
400
401 // Clean up our style object's display and text decorations (among other fixups).
402 adjustRenderStyle(*state.style(), *state.parentStyle(), parentBoxStyle, &element);
403
404 if (state.style()->hasViewportUnits())
405 document().setHasStyleWithViewportUnits();
406
407 state.clear(); // Clear out for the next resolve.
408
409 return { state.takeStyle(), WTFMove(elementStyleRelations) };
410}
411
412std::unique_ptr<RenderStyle> StyleResolver::styleForKeyframe(const RenderStyle* elementStyle, const StyleRuleKeyframe* keyframe, KeyframeValue& keyframeValue)
413{
414 RELEASE_ASSERT(!m_isDeleted);
415
416 MatchResult result;
417 result.addMatchedProperties(keyframe->properties());
418
419 ASSERT(!m_state.style());
420
421 State& state = m_state;
422
423 // Create the style
424 state.setStyle(RenderStyle::clonePtr(*elementStyle));
425 state.setParentStyle(RenderStyle::clonePtr(*elementStyle));
426
427 TextDirection direction;
428 WritingMode writingMode;
429 extractDirectionAndWritingMode(*state.style(), result, direction, writingMode);
430
431 // We don't need to bother with !important. Since there is only ever one
432 // decl, there's nothing to override. So just add the first properties.
433 CascadedProperties cascade(direction, writingMode);
434 cascade.addNormalMatches(result, 0, result.matchedProperties().size() - 1);
435
436 ApplyCascadedPropertyState applyState { this, &cascade, &result };
437 applyCascadedProperties(firstCSSProperty, lastHighPriorityProperty, applyState);
438
439 // If our font got dirtied, update it now.
440 updateFont();
441
442 // Now resolve remaining custom properties and the rest, in any order
443 for (auto it = cascade.customProperties().begin(); it != cascade.customProperties().end(); ++it)
444 applyCascadedCustomProperty(it->key, applyState);
445 applyCascadedProperties(firstLowPriorityProperty, lastCSSProperty, applyState);
446
447 // If our font got dirtied by one of the non-essential font props, update it a second time.
448 updateFont();
449
450 cascade.applyDeferredProperties(*this, applyState);
451
452 adjustRenderStyle(*state.style(), *state.parentStyle(), nullptr, nullptr);
453
454 // Add all the animating properties to the keyframe.
455 unsigned propertyCount = keyframe->properties().propertyCount();
456 for (unsigned i = 0; i < propertyCount; ++i) {
457 CSSPropertyID property = keyframe->properties().propertyAt(i).id();
458 // Timing-function within keyframes is special, because it is not animated; it just
459 // describes the timing function between this keyframe and the next.
460 if (property != CSSPropertyAnimationTimingFunction)
461 keyframeValue.addProperty(property);
462 }
463
464 return state.takeStyle();
465}
466
467bool StyleResolver::isAnimationNameValid(const String& name)
468{
469 return m_keyframesRuleMap.find(AtomicString(name).impl()) != m_keyframesRuleMap.end();
470}
471
472void StyleResolver::keyframeStylesForAnimation(const Element& element, const RenderStyle* elementStyle, KeyframeList& list)
473{
474 list.clear();
475
476 // Get the keyframesRule for this name.
477 if (list.animationName().isEmpty())
478 return;
479
480 m_keyframesRuleMap.checkConsistency();
481
482 KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
483 if (it == m_keyframesRuleMap.end())
484 return;
485
486 const StyleRuleKeyframes* keyframesRule = it->value.get();
487
488 auto* keyframes = &keyframesRule->keyframes();
489 Vector<Ref<StyleRuleKeyframe>> newKeyframesIfNecessary;
490
491 bool hasDuplicateKeys = false;
492 HashSet<double> keyframeKeys;
493 for (auto& keyframe : *keyframes) {
494 for (auto key : keyframe->keys()) {
495 if (!keyframeKeys.add(key)) {
496 hasDuplicateKeys = true;
497 break;
498 }
499 }
500 if (hasDuplicateKeys)
501 break;
502 }
503
504 // FIXME: If HashMaps could have Ref<> as value types, we wouldn't need
505 // to copy the HashMap into a Vector.
506 if (hasDuplicateKeys) {
507 // Merge duplicate key times.
508 HashMap<double, RefPtr<StyleRuleKeyframe>> keyframesMap;
509
510 for (auto& originalKeyframe : keyframesRule->keyframes()) {
511 for (auto key : originalKeyframe->keys()) {
512 if (auto keyframe = keyframesMap.get(key))
513 keyframe->mutableProperties().mergeAndOverrideOnConflict(originalKeyframe->properties());
514 else {
515 auto StyleRuleKeyframe = StyleRuleKeyframe::create(MutableStyleProperties::create());
516 StyleRuleKeyframe.ptr()->setKey(key);
517 StyleRuleKeyframe.ptr()->mutableProperties().mergeAndOverrideOnConflict(originalKeyframe->properties());
518 keyframesMap.set(key, StyleRuleKeyframe.ptr());
519 }
520 }
521 }
522
523 for (auto& keyframe : keyframesMap.values())
524 newKeyframesIfNecessary.append(*keyframe.get());
525
526 keyframes = &newKeyframesIfNecessary;
527 }
528
529 // Construct and populate the style for each keyframe.
530 for (auto& keyframe : *keyframes) {
531 setNewStateWithElement(element);
532
533 // Add this keyframe style to all the indicated key times
534 for (auto key : keyframe->keys()) {
535 KeyframeValue keyframeValue(0, nullptr);
536 keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe.ptr(), keyframeValue));
537 keyframeValue.setKey(key);
538 if (auto timingFunctionCSSValue = keyframe->properties().getPropertyCSSValue(CSSPropertyAnimationTimingFunction))
539 keyframeValue.setTimingFunction(TimingFunction::createFromCSSValue(*timingFunctionCSSValue.get()));
540 list.insert(WTFMove(keyframeValue));
541 }
542 }
543
544 // If the 0% keyframe is missing, create it (but only if there is at least one other keyframe).
545 int initialListSize = list.size();
546 if (initialListSize > 0 && list[0].key()) {
547 static StyleRuleKeyframe* zeroPercentKeyframe;
548 if (!zeroPercentKeyframe) {
549 zeroPercentKeyframe = &StyleRuleKeyframe::create(MutableStyleProperties::create()).leakRef();
550 zeroPercentKeyframe->setKey(0);
551 }
552 KeyframeValue keyframeValue(0, nullptr);
553 keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
554 list.insert(WTFMove(keyframeValue));
555 }
556
557 // If the 100% keyframe is missing, create it (but only if there is at least one other keyframe).
558 if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
559 static StyleRuleKeyframe* hundredPercentKeyframe;
560 if (!hundredPercentKeyframe) {
561 hundredPercentKeyframe = &StyleRuleKeyframe::create(MutableStyleProperties::create()).leakRef();
562 hundredPercentKeyframe->setKey(1);
563 }
564 KeyframeValue keyframeValue(1, nullptr);
565 keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
566 list.insert(WTFMove(keyframeValue));
567 }
568}
569
570std::unique_ptr<RenderStyle> StyleResolver::pseudoStyleForElement(const Element& element, const PseudoStyleRequest& pseudoStyleRequest, const RenderStyle& parentStyle, const SelectorFilter* selectorFilter)
571{
572 m_state = State(element, &parentStyle, m_overrideDocumentElementStyle, selectorFilter);
573
574 State& state = m_state;
575
576 if (m_state.parentStyle()) {
577 state.setStyle(RenderStyle::createPtr());
578 state.style()->inheritFrom(*m_state.parentStyle());
579 } else {
580 state.setStyle(defaultStyleForElement());
581 state.setParentStyle(RenderStyle::clonePtr(*state.style()));
582 }
583
584 // Since we don't use pseudo-elements in any of our quirk/print user agent rules, don't waste time walking
585 // those rules.
586
587 // Check UA, user and author rules.
588 ElementRuleCollector collector(element, m_ruleSets, m_state.selectorFilter());
589 collector.setPseudoStyleRequest(pseudoStyleRequest);
590 collector.setMedium(&m_mediaQueryEvaluator);
591 collector.matchUARules();
592
593 if (m_matchAuthorAndUserStyles) {
594 collector.matchUserRules(false);
595 collector.matchAuthorRules(false);
596 }
597
598 ASSERT(!collector.matchedPseudoElementIds());
599
600 if (collector.matchedResult().matchedProperties().isEmpty())
601 return nullptr;
602
603 state.style()->setStyleType(pseudoStyleRequest.pseudoId);
604
605 applyMatchedProperties(collector.matchedResult(), element);
606
607 // Clean up our style object's display and text decorations (among other fixups).
608 adjustRenderStyle(*state.style(), *m_state.parentStyle(), nullptr, nullptr);
609
610 if (state.style()->hasViewportUnits())
611 document().setHasStyleWithViewportUnits();
612
613 // Now return the style.
614 return state.takeStyle();
615}
616
617std::unique_ptr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
618{
619 RELEASE_ASSERT(!m_isDeleted);
620
621 auto* documentElement = m_document.documentElement();
622 if (!documentElement)
623 return RenderStyle::createPtr();
624
625 m_state = State(*documentElement, m_document.renderStyle());
626
627 m_state.setStyle(RenderStyle::createPtr());
628 m_state.style()->inheritFrom(*m_state.rootElementStyle());
629
630 PageRuleCollector collector(m_state, m_ruleSets);
631 collector.matchAllPageRules(pageIndex);
632
633 MatchResult& result = collector.matchedResult();
634
635 TextDirection direction;
636 WritingMode writingMode;
637 extractDirectionAndWritingMode(*m_state.style(), result, direction, writingMode);
638
639 CascadedProperties cascade(direction, writingMode);
640 cascade.addNormalMatches(result, 0, result.matchedProperties().size() - 1);
641
642 ApplyCascadedPropertyState applyState { this, &cascade, &result };
643 applyCascadedProperties(firstCSSProperty, lastHighPriorityProperty, applyState);
644
645 // If our font got dirtied, update it now.
646 updateFont();
647
648 // Now resolve remaining custom properties and the rest, in any order
649 for (auto it = cascade.customProperties().begin(); it != cascade.customProperties().end(); ++it)
650 applyCascadedCustomProperty(it->key, applyState);
651 applyCascadedProperties(firstLowPriorityProperty, lastCSSProperty, applyState);
652
653 cascade.applyDeferredProperties(*this, applyState);
654
655 // Now return the style.
656 return m_state.takeStyle();
657}
658
659std::unique_ptr<RenderStyle> StyleResolver::defaultStyleForElement()
660{
661 m_state.setStyle(RenderStyle::createPtr());
662 // Make sure our fonts are initialized if we don't inherit them from our parent style.
663 initializeFontStyle();
664 m_state.style()->fontCascade().update(&document().fontSelector());
665 return m_state.takeStyle();
666}
667
668static void addIntrinsicMargins(RenderStyle& style)
669{
670 // Intrinsic margin value.
671 const int intrinsicMargin = clampToInteger(2 * style.effectiveZoom());
672
673 // FIXME: Using width/height alone and not also dealing with min-width/max-width is flawed.
674 // FIXME: Using "hasQuirk" to decide the margin wasn't set is kind of lame.
675 if (style.width().isIntrinsicOrAuto()) {
676 if (style.marginLeft().hasQuirk())
677 style.setMarginLeft(Length(intrinsicMargin, Fixed));
678 if (style.marginRight().hasQuirk())
679 style.setMarginRight(Length(intrinsicMargin, Fixed));
680 }
681
682 if (style.height().isAuto()) {
683 if (style.marginTop().hasQuirk())
684 style.setMarginTop(Length(intrinsicMargin, Fixed));
685 if (style.marginBottom().hasQuirk())
686 style.setMarginBottom(Length(intrinsicMargin, Fixed));
687 }
688}
689
690static DisplayType equivalentBlockDisplay(const RenderStyle& style, const Document& document)
691{
692 switch (auto display = style.display()) {
693 case DisplayType::Block:
694 case DisplayType::Table:
695 case DisplayType::Box:
696 case DisplayType::Flex:
697 case DisplayType::WebKitFlex:
698 case DisplayType::Grid:
699 case DisplayType::FlowRoot:
700 return display;
701
702 case DisplayType::ListItem:
703 // It is a WinIE bug that floated list items lose their bullets, so we'll emulate the quirk, but only in quirks mode.
704 if (document.inQuirksMode() && style.isFloating())
705 return DisplayType::Block;
706 return display;
707 case DisplayType::InlineTable:
708 return DisplayType::Table;
709 case DisplayType::InlineBox:
710 return DisplayType::Box;
711 case DisplayType::InlineFlex:
712 case DisplayType::WebKitInlineFlex:
713 return DisplayType::Flex;
714 case DisplayType::InlineGrid:
715 return DisplayType::Grid;
716
717 case DisplayType::Inline:
718 case DisplayType::Compact:
719 case DisplayType::InlineBlock:
720 case DisplayType::TableRowGroup:
721 case DisplayType::TableHeaderGroup:
722 case DisplayType::TableFooterGroup:
723 case DisplayType::TableRow:
724 case DisplayType::TableColumnGroup:
725 case DisplayType::TableColumn:
726 case DisplayType::TableCell:
727 case DisplayType::TableCaption:
728 return DisplayType::Block;
729 case DisplayType::Contents:
730 ASSERT_NOT_REACHED();
731 return DisplayType::Contents;
732 case DisplayType::None:
733 ASSERT_NOT_REACHED();
734 return DisplayType::None;
735 }
736 ASSERT_NOT_REACHED();
737 return DisplayType::Block;
738}
739
740// CSS requires text-decoration to be reset at each DOM element for tables,
741// inline blocks, inline tables, shadow DOM crossings, floating elements,
742// and absolute or relatively positioned elements.
743static bool doesNotInheritTextDecoration(const RenderStyle& style, const Element* element)
744{
745 return style.display() == DisplayType::Table || style.display() == DisplayType::InlineTable
746 || style.display() == DisplayType::InlineBlock || style.display() == DisplayType::InlineBox || (element && isAtShadowBoundary(*element))
747 || style.isFloating() || style.hasOutOfFlowPosition();
748}
749
750#if ENABLE(OVERFLOW_SCROLLING_TOUCH) || ENABLE(POINTER_EVENTS)
751static bool isScrollableOverflow(Overflow overflow)
752{
753 return overflow == Overflow::Scroll || overflow == Overflow::Auto;
754}
755#endif
756
757void StyleResolver::adjustStyleForInterCharacterRuby()
758{
759 RenderStyle* style = m_state.style();
760 if (style->rubyPosition() != RubyPosition::InterCharacter || !m_state.element() || !m_state.element()->hasTagName(rtTag))
761 return;
762 style->setTextAlign(TextAlignMode::Center);
763 if (style->isHorizontalWritingMode())
764 style->setWritingMode(LeftToRightWritingMode);
765}
766
767static bool hasEffectiveDisplayNoneForDisplayContents(const Element& element)
768{
769 // https://drafts.csswg.org/css-display-3/#unbox-html
770 static NeverDestroyed<HashSet<AtomicString>> tagNames = [] {
771 static const HTMLQualifiedName* const tagList[] = {
772 &brTag.get(),
773 &wbrTag.get(),
774 &meterTag.get(),
775 &appletTag.get(),
776 &progressTag.get(),
777 &canvasTag.get(),
778 &embedTag.get(),
779 &objectTag.get(),
780 &audioTag.get(),
781 &iframeTag.get(),
782 &imgTag.get(),
783 &videoTag.get(),
784 &frameTag.get(),
785 &framesetTag.get(),
786 &inputTag.get(),
787 &textareaTag.get(),
788 &selectTag.get(),
789 };
790 HashSet<AtomicString> set;
791 for (auto& name : tagList)
792 set.add(name->localName());
793 return set;
794 }();
795
796 // https://drafts.csswg.org/css-display-3/#unbox-svg
797 // FIXME: <g>, <use> and <tspan> have special (?) behavior for display:contents in the current draft spec.
798 if (is<SVGElement>(element))
799 return true;
800#if ENABLE(MATHML)
801 // Not sure MathML code can handle it.
802 if (is<MathMLElement>(element))
803 return true;
804#endif // ENABLE(MATHML)
805 if (!is<HTMLElement>(element))
806 return false;
807 return tagNames.get().contains(element.localName());
808}
809
810static void adjustDisplayContentsStyle(RenderStyle& style, const Element* element)
811{
812 bool displayContentsEnabled = is<HTMLSlotElement>(element) || RuntimeEnabledFeatures::sharedFeatures().displayContentsEnabled();
813 if (!displayContentsEnabled) {
814 style.setDisplay(DisplayType::Inline);
815 return;
816 }
817 if (!element) {
818 if (style.styleType() != PseudoId::Before && style.styleType() != PseudoId::After)
819 style.setDisplay(DisplayType::None);
820 return;
821 }
822 if (element->document().documentElement() == element) {
823 style.setDisplay(DisplayType::Block);
824 return;
825 }
826 if (hasEffectiveDisplayNoneForDisplayContents(*element))
827 style.setDisplay(DisplayType::None);
828}
829
830void StyleResolver::adjustSVGElementStyle(const SVGElement& svgElement, RenderStyle& style)
831{
832 // Only the root <svg> element in an SVG document fragment tree honors css position
833 auto isPositioningAllowed = svgElement.hasTagName(SVGNames::svgTag) && svgElement.parentNode() && !svgElement.parentNode()->isSVGElement() && !svgElement.correspondingElement();
834 if (!isPositioningAllowed)
835 style.setPosition(RenderStyle::initialPosition());
836
837 // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
838 // not be scaled again.
839 if (svgElement.hasTagName(SVGNames::foreignObjectTag))
840 style.setEffectiveZoom(RenderStyle::initialZoom());
841
842 // SVG text layout code expects us to be a block-level style element.
843 if ((svgElement.hasTagName(SVGNames::foreignObjectTag) || svgElement.hasTagName(SVGNames::textTag)) && style.isDisplayInlineType())
844 style.setDisplay(DisplayType::Block);
845}
846
847#if ENABLE(POINTER_EVENTS)
848static OptionSet<TouchAction> computeEffectiveTouchActions(const RenderStyle& style, OptionSet<TouchAction> effectiveTouchActions)
849{
850 // https://w3c.github.io/pointerevents/#determining-supported-touch-behavior
851 // "A touch behavior is supported if it conforms to the touch-action property of each element between
852 // the hit tested element and its nearest ancestor with the default touch behavior (including both the
853 // hit tested element and the element with the default touch behavior)."
854
855 bool hasDefaultTouchBehavior = isScrollableOverflow(style.overflowX()) || isScrollableOverflow(style.overflowY());
856 if (hasDefaultTouchBehavior)
857 effectiveTouchActions = RenderStyle::initialTouchActions();
858
859 auto touchActions = style.touchActions();
860 if (touchActions == RenderStyle::initialTouchActions())
861 return effectiveTouchActions;
862
863 if (effectiveTouchActions.contains(TouchAction::None))
864 return { TouchAction::None };
865
866 if (effectiveTouchActions.contains(TouchAction::Auto) || effectiveTouchActions.contains(TouchAction::Manipulation))
867 return touchActions;
868
869 auto sharedTouchActions = effectiveTouchActions & touchActions;
870 if (sharedTouchActions.isEmpty())
871 return { TouchAction::None };
872
873 return sharedTouchActions;
874}
875#endif
876
877void StyleResolver::adjustRenderStyle(RenderStyle& style, const RenderStyle& parentStyle, const RenderStyle* parentBoxStyle, const Element* element)
878{
879 // If the composed tree parent has display:contents, the parent box style will be different from the parent style.
880 // We don't have it when resolving computed style for display:none subtree. Use parent style for adjustments in that case.
881 if (!parentBoxStyle)
882 parentBoxStyle = &parentStyle;
883
884 // Cache our original display.
885 style.setOriginalDisplay(style.display());
886
887 if (style.display() == DisplayType::Contents)
888 adjustDisplayContentsStyle(style, element);
889
890 if (style.display() != DisplayType::None && style.display() != DisplayType::Contents) {
891 if (element) {
892 // If we have a <td> that specifies a float property, in quirks mode we just drop the float
893 // property.
894 // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
895 // these tags to retain their display types.
896 if (document().inQuirksMode()) {
897 if (element->hasTagName(tdTag)) {
898 style.setDisplay(DisplayType::TableCell);
899 style.setFloating(Float::No);
900 } else if (is<HTMLTableElement>(*element))
901 style.setDisplay(style.isDisplayInlineType() ? DisplayType::InlineTable : DisplayType::Table);
902 }
903
904 if (element->hasTagName(tdTag) || element->hasTagName(thTag)) {
905 if (style.whiteSpace() == WhiteSpace::KHTMLNoWrap) {
906 // Figure out if we are really nowrapping or if we should just
907 // use normal instead. If the width of the cell is fixed, then
908 // we don't actually use WhiteSpace::NoWrap.
909 if (style.width().isFixed())
910 style.setWhiteSpace(WhiteSpace::Normal);
911 else
912 style.setWhiteSpace(WhiteSpace::NoWrap);
913 }
914 }
915
916 // Tables never support the -webkit-* values for text-align and will reset back to the default.
917 if (is<HTMLTableElement>(*element) && (style.textAlign() == TextAlignMode::WebKitLeft || style.textAlign() == TextAlignMode::WebKitCenter || style.textAlign() == TextAlignMode::WebKitRight))
918 style.setTextAlign(TextAlignMode::Start);
919
920 // Frames and framesets never honor position:relative or position:absolute. This is necessary to
921 // fix a crash where a site tries to position these objects. They also never honor display.
922 if (element->hasTagName(frameTag) || element->hasTagName(framesetTag)) {
923 style.setPosition(PositionType::Static);
924 style.setDisplay(DisplayType::Block);
925 }
926
927 // Ruby text does not support float or position. This might change with evolution of the specification.
928 if (element->hasTagName(rtTag)) {
929 style.setPosition(PositionType::Static);
930 style.setFloating(Float::No);
931 }
932
933 // User agents are expected to have a rule in their user agent stylesheet that matches th elements that have a parent
934 // node whose computed value for the 'text-align' property is its initial value, whose declaration block consists of
935 // just a single declaration that sets the 'text-align' property to the value 'center'.
936 // https://html.spec.whatwg.org/multipage/rendering.html#rendering
937 if (element->hasTagName(thTag) && !style.hasExplicitlySetTextAlign() && parentStyle.textAlign() == RenderStyle::initialTextAlign())
938 style.setTextAlign(TextAlignMode::Center);
939
940 if (element->hasTagName(legendTag))
941 style.setDisplay(DisplayType::Block);
942 }
943
944 // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
945 if (style.hasOutOfFlowPosition() || style.isFloating() || (element && element->document().documentElement() == element))
946 style.setDisplay(equivalentBlockDisplay(style, document()));
947
948 // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
949 // clear how that should work.
950 if (style.display() == DisplayType::Inline && style.styleType() == PseudoId::None && style.writingMode() != parentStyle.writingMode())
951 style.setDisplay(DisplayType::InlineBlock);
952
953 // After performing the display mutation, check table rows. We do not honor position:relative or position:sticky on
954 // table rows or cells. This has been established for position:relative in CSS2.1 (and caused a crash in containingBlock()
955 // on some sites).
956 if ((style.display() == DisplayType::TableHeaderGroup || style.display() == DisplayType::TableRowGroup
957 || style.display() == DisplayType::TableFooterGroup || style.display() == DisplayType::TableRow)
958 && style.position() == PositionType::Relative)
959 style.setPosition(PositionType::Static);
960
961 // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
962 // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
963 if (style.display() == DisplayType::TableColumn || style.display() == DisplayType::TableColumnGroup || style.display() == DisplayType::TableFooterGroup
964 || style.display() == DisplayType::TableHeaderGroup || style.display() == DisplayType::TableRow || style.display() == DisplayType::TableRowGroup
965 || style.display() == DisplayType::TableCell)
966 style.setWritingMode(parentStyle.writingMode());
967
968 // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
969 // of block-flow to anything other than TopToBottomWritingMode.
970 // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
971 if (style.writingMode() != TopToBottomWritingMode && (style.display() == DisplayType::Box || style.display() == DisplayType::InlineBox))
972 style.setWritingMode(TopToBottomWritingMode);
973
974 // https://www.w3.org/TR/css-display/#transformations
975 // "A parent with a grid or flex display value blockifies the box’s display type."
976 if (parentBoxStyle->isDisplayFlexibleOrGridBox()) {
977 style.setFloating(Float::No);
978 style.setDisplay(equivalentBlockDisplay(style, document()));
979 }
980 }
981
982 // Make sure our z-index value is only applied if the object is positioned.
983 if (style.position() == PositionType::Static && !parentBoxStyle->isDisplayFlexibleOrGridBox())
984 style.setHasAutoZIndex();
985
986 // Auto z-index becomes 0 for the root element and transparent objects. This prevents
987 // cases where objects that should be blended as a single unit end up with a non-transparent
988 // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
989 if (style.hasAutoZIndex()) {
990 if ((element && element->document().documentElement() == element)
991 || style.opacity() < 1.0f
992 || style.hasTransformRelatedProperty()
993 || style.hasMask()
994 || style.clipPath()
995 || style.boxReflect()
996 || style.hasFilter()
997#if ENABLE(FILTERS_LEVEL_2)
998 || style.hasBackdropFilter()
999#endif
1000 || style.hasBlendMode()
1001 || style.hasIsolation()
1002 || style.position() == PositionType::Sticky
1003 || style.position() == PositionType::Fixed
1004 || style.willChangeCreatesStackingContext())
1005 style.setZIndex(0);
1006 }
1007
1008 if (element) {
1009 // Textarea considers overflow visible as auto.
1010 if (is<HTMLTextAreaElement>(*element)) {
1011 style.setOverflowX(style.overflowX() == Overflow::Visible ? Overflow::Auto : style.overflowX());
1012 style.setOverflowY(style.overflowY() == Overflow::Visible ? Overflow::Auto : style.overflowY());
1013 }
1014
1015 // Disallow -webkit-user-modify on :pseudo and ::pseudo elements.
1016 if (!element->shadowPseudoId().isNull())
1017 style.setUserModify(UserModify::ReadOnly);
1018
1019 if (is<HTMLMarqueeElement>(*element)) {
1020 // For now, <marquee> requires an overflow clip to work properly.
1021 style.setOverflowX(Overflow::Hidden);
1022 style.setOverflowY(Overflow::Hidden);
1023
1024 bool isVertical = style.marqueeDirection() == MarqueeDirection::Up || style.marqueeDirection() == MarqueeDirection::Down;
1025 // Make horizontal marquees not wrap.
1026 if (!isVertical) {
1027 style.setWhiteSpace(WhiteSpace::NoWrap);
1028 style.setTextAlign(TextAlignMode::Start);
1029 }
1030 // Apparently this is the expected legacy behavior.
1031 if (isVertical && style.height().isAuto())
1032 style.setHeight(Length(200, Fixed));
1033 }
1034 }
1035
1036 if (doesNotInheritTextDecoration(style, element))
1037 style.setTextDecorationsInEffect(style.textDecoration());
1038 else
1039 style.addToTextDecorationsInEffect(style.textDecoration());
1040
1041 // If either overflow value is not visible, change to auto.
1042 if (style.overflowX() == Overflow::Visible && style.overflowY() != Overflow::Visible) {
1043 // FIXME: Once we implement pagination controls, overflow-x should default to hidden
1044 // if overflow-y is set to -webkit-paged-x or -webkit-page-y. For now, we'll let it
1045 // default to auto so we can at least scroll through the pages.
1046 style.setOverflowX(Overflow::Auto);
1047 } else if (style.overflowY() == Overflow::Visible && style.overflowX() != Overflow::Visible)
1048 style.setOverflowY(Overflow::Auto);
1049
1050 // Call setStylesForPaginationMode() if a pagination mode is set for any non-root elements. If these
1051 // styles are specified on a root element, then they will be incorporated in
1052 // Style::createForDocument().
1053 if ((style.overflowY() == Overflow::PagedX || style.overflowY() == Overflow::PagedY) && !(element && (element->hasTagName(htmlTag) || element->hasTagName(bodyTag))))
1054 style.setColumnStylesFromPaginationMode(WebCore::paginationModeForRenderStyle(style));
1055
1056 // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
1057 // FIXME: Eventually table sections will support auto and scroll.
1058 if (style.display() == DisplayType::Table || style.display() == DisplayType::InlineTable
1059 || style.display() == DisplayType::TableRowGroup || style.display() == DisplayType::TableRow) {
1060 if (style.overflowX() != Overflow::Visible && style.overflowX() != Overflow::Hidden)
1061 style.setOverflowX(Overflow::Visible);
1062 if (style.overflowY() != Overflow::Visible && style.overflowY() != Overflow::Hidden)
1063 style.setOverflowY(Overflow::Visible);
1064 }
1065
1066 // Menulists should have visible overflow
1067 if (style.appearance() == MenulistPart) {
1068 style.setOverflowX(Overflow::Visible);
1069 style.setOverflowY(Overflow::Visible);
1070 }
1071
1072#if ENABLE(OVERFLOW_SCROLLING_TOUCH)
1073 // Touch overflow scrolling creates a stacking context.
1074 if (style.hasAutoZIndex() && style.useTouchOverflowScrolling() && (isScrollableOverflow(style.overflowX()) || isScrollableOverflow(style.overflowY())))
1075 style.setZIndex(0);
1076#endif
1077
1078 // Cull out any useless layers and also repeat patterns into additional layers.
1079 style.adjustBackgroundLayers();
1080 style.adjustMaskLayers();
1081
1082 // Do the same for animations and transitions.
1083 style.adjustAnimations();
1084 style.adjustTransitions();
1085
1086 // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1087 // alter fonts and heights/widths.
1088 if (is<HTMLFormControlElement>(element) && style.computedFontPixelSize() >= 11) {
1089 // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
1090 // so we have to treat all image buttons as though they were explicitly sized.
1091 if (!is<HTMLInputElement>(*element) || !downcast<HTMLInputElement>(*element).isImageButton())
1092 addIntrinsicMargins(style);
1093 }
1094
1095 // Let the theme also have a crack at adjusting the style.
1096 if (style.hasAppearance())
1097 RenderTheme::singleton().adjustStyle(*this, style, element, m_state.hasUAAppearance(), m_state.borderData(), m_state.backgroundData(), m_state.backgroundColor());
1098
1099 // If we have first-letter pseudo style, do not share this style.
1100 if (style.hasPseudoStyle(PseudoId::FirstLetter))
1101 style.setUnique();
1102
1103 // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
1104 if (style.preserves3D() && (style.overflowX() != Overflow::Visible
1105 || style.overflowY() != Overflow::Visible
1106 || style.hasClip()
1107 || style.clipPath()
1108 || style.hasFilter()
1109#if ENABLE(FILTERS_LEVEL_2)
1110 || style.hasBackdropFilter()
1111#endif
1112 || style.hasBlendMode()))
1113 style.setTransformStyle3D(TransformStyle3D::Flat);
1114
1115 if (is<SVGElement>(element))
1116 adjustSVGElementStyle(downcast<SVGElement>(*element), style);
1117
1118 // If the inherited value of justify-items includes the 'legacy' keyword (plus 'left', 'right' or
1119 // 'center'), 'legacy' computes to the the inherited value. Otherwise, 'auto' computes to 'normal'.
1120 if (parentBoxStyle->justifyItems().positionType() == ItemPositionType::Legacy && style.justifyItems().position() == ItemPosition::Legacy)
1121 style.setJustifyItems(parentBoxStyle->justifyItems());
1122
1123#if ENABLE(POINTER_EVENTS)
1124 style.setEffectiveTouchActions(computeEffectiveTouchActions(style, parentStyle.effectiveTouchActions()));
1125#endif
1126
1127 if (element)
1128 adjustRenderStyleForSiteSpecificQuirks(style, *element);
1129}
1130
1131void StyleResolver::adjustRenderStyleForSiteSpecificQuirks(RenderStyle& style, const Element& element)
1132{
1133 if (document().quirks().needsGMailOverflowScrollQuirk()) {
1134 // This turns sidebar scrollable without mouse move event.
1135 static NeverDestroyed<AtomicString> roleValue("navigation", AtomicString::ConstructFromLiteral);
1136 if (style.overflowY() == Overflow::Hidden && element.attributeWithoutSynchronization(roleAttr) == roleValue)
1137 style.setOverflowY(Overflow::Auto);
1138 }
1139 if (document().quirks().needsYouTubeOverflowScrollQuirk()) {
1140 // This turns sidebar scrollable without hover.
1141 static NeverDestroyed<AtomicString> idValue("guide-inner-content", AtomicString::ConstructFromLiteral);
1142 if (style.overflowY() == Overflow::Hidden && element.idForStyleResolution() == idValue)
1143 style.setOverflowY(Overflow::Auto);
1144 }
1145}
1146
1147static void checkForOrientationChange(RenderStyle* style)
1148{
1149 FontOrientation fontOrientation;
1150 NonCJKGlyphOrientation glyphOrientation;
1151 std::tie(fontOrientation, glyphOrientation) = style->fontAndGlyphOrientation();
1152
1153 const auto& fontDescription = style->fontDescription();
1154 if (fontDescription.orientation() == fontOrientation && fontDescription.nonCJKGlyphOrientation() == glyphOrientation)
1155 return;
1156
1157 auto newFontDescription = fontDescription;
1158 newFontDescription.setNonCJKGlyphOrientation(glyphOrientation);
1159 newFontDescription.setOrientation(fontOrientation);
1160 style->setFontDescription(WTFMove(newFontDescription));
1161}
1162
1163void StyleResolver::updateFont()
1164{
1165 if (!m_state.fontDirty())
1166 return;
1167
1168 RenderStyle* style = m_state.style();
1169#if ENABLE(TEXT_AUTOSIZING)
1170 checkForTextSizeAdjust(style);
1171#endif
1172 checkForGenericFamilyChange(style, m_state.parentStyle());
1173 checkForZoomChange(style, m_state.parentStyle());
1174 checkForOrientationChange(style);
1175 style->fontCascade().update(&document().fontSelector());
1176 if (m_state.fontSizeHasViewportUnits())
1177 style->setHasViewportUnits(true);
1178 m_state.setFontDirty(false);
1179}
1180
1181Vector<RefPtr<StyleRule>> StyleResolver::styleRulesForElement(const Element* element, unsigned rulesToInclude)
1182{
1183 return pseudoStyleRulesForElement(element, PseudoId::None, rulesToInclude);
1184}
1185
1186Vector<RefPtr<StyleRule>> StyleResolver::pseudoStyleRulesForElement(const Element* element, PseudoId pseudoId, unsigned rulesToInclude)
1187{
1188 if (!element)
1189 return { };
1190
1191 m_state = State(*element, nullptr);
1192
1193 ElementRuleCollector collector(*element, m_ruleSets, m_state.selectorFilter());
1194 collector.setMode(SelectorChecker::Mode::CollectingRules);
1195 collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
1196 collector.setMedium(&m_mediaQueryEvaluator);
1197
1198 if (rulesToInclude & UAAndUserCSSRules) {
1199 // First we match rules from the user agent sheet.
1200 collector.matchUARules();
1201
1202 // Now we check user sheet rules.
1203 if (m_matchAuthorAndUserStyles)
1204 collector.matchUserRules(rulesToInclude & EmptyCSSRules);
1205 }
1206
1207 if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules))
1208 collector.matchAuthorRules(rulesToInclude & EmptyCSSRules);
1209
1210 return collector.matchedRuleList();
1211}
1212
1213static bool shouldApplyPropertyInParseOrder(CSSPropertyID propertyID)
1214{
1215 switch (propertyID) {
1216 case CSSPropertyWebkitBackgroundClip:
1217 case CSSPropertyBackgroundClip:
1218 case CSSPropertyWebkitBackgroundOrigin:
1219 case CSSPropertyBackgroundOrigin:
1220 case CSSPropertyWebkitBackgroundSize:
1221 case CSSPropertyBackgroundSize:
1222 case CSSPropertyWebkitBorderImage:
1223 case CSSPropertyBorderImage:
1224 case CSSPropertyBorderImageSlice:
1225 case CSSPropertyBorderImageSource:
1226 case CSSPropertyBorderImageOutset:
1227 case CSSPropertyBorderImageRepeat:
1228 case CSSPropertyBorderImageWidth:
1229 case CSSPropertyWebkitBoxShadow:
1230 case CSSPropertyBoxShadow:
1231 case CSSPropertyWebkitTextDecoration:
1232 case CSSPropertyTextDecorationLine:
1233 case CSSPropertyTextDecorationStyle:
1234 case CSSPropertyTextDecorationColor:
1235 case CSSPropertyTextDecorationSkip:
1236 case CSSPropertyTextUnderlinePosition:
1237 case CSSPropertyTextUnderlineOffset:
1238 case CSSPropertyTextDecorationThickness:
1239 case CSSPropertyTextDecoration:
1240 return true;
1241 default:
1242 return false;
1243 }
1244}
1245
1246static bool elementTypeHasAppearanceFromUAStyle(const Element& element)
1247{
1248 // NOTE: This is just a hard-coded list of elements that have some -webkit-appearance value in html.css
1249 const auto& localName = element.localName();
1250 return localName == HTMLNames::inputTag
1251 || localName == HTMLNames::textareaTag
1252 || localName == HTMLNames::buttonTag
1253 || localName == HTMLNames::progressTag
1254 || localName == HTMLNames::selectTag
1255 || localName == HTMLNames::meterTag;
1256}
1257
1258unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
1259{
1260 return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
1261}
1262
1263bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
1264{
1265 return a.firstUARule == b.firstUARule
1266 && a.lastUARule == b.lastUARule
1267 && a.firstAuthorRule == b.firstAuthorRule
1268 && a.lastAuthorRule == b.lastAuthorRule
1269 && a.firstUserRule == b.firstUserRule
1270 && a.lastUserRule == b.lastUserRule;
1271}
1272
1273bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
1274{
1275 return !(a == b);
1276}
1277
1278bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
1279{
1280 return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
1281}
1282
1283bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
1284{
1285 return !(a == b);
1286}
1287
1288const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
1289{
1290 ASSERT(hash);
1291
1292 MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
1293 if (it == m_matchedPropertiesCache.end())
1294 return nullptr;
1295 MatchedPropertiesCacheItem& cacheItem = it->value;
1296
1297 size_t size = matchResult.matchedProperties().size();
1298 if (size != cacheItem.matchedProperties.size())
1299 return nullptr;
1300 for (size_t i = 0; i < size; ++i) {
1301 if (matchResult.matchedProperties()[i] != cacheItem.matchedProperties[i])
1302 return nullptr;
1303 }
1304 if (cacheItem.ranges != matchResult.ranges)
1305 return nullptr;
1306 return &cacheItem;
1307}
1308
1309void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
1310{
1311 static const unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
1312 if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps
1313 && !m_matchedPropertiesCacheSweepTimer.isActive()) {
1314 static const Seconds matchedDeclarationCacheSweepTime { 1_min };
1315 m_matchedPropertiesCacheSweepTimer.startOneShot(matchedDeclarationCacheSweepTime);
1316 }
1317
1318 ASSERT(hash);
1319 // Note that we don't cache the original RenderStyle instance. It may be further modified.
1320 // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
1321 MatchedPropertiesCacheItem cacheItem(matchResult, style, parentStyle);
1322 m_matchedPropertiesCache.add(hash, WTFMove(cacheItem));
1323}
1324
1325void StyleResolver::invalidateMatchedPropertiesCache()
1326{
1327 m_matchedPropertiesCache.clear();
1328}
1329
1330void StyleResolver::clearCachedPropertiesAffectedByViewportUnits()
1331{
1332 Vector<unsigned, 16> toRemove;
1333 for (auto& cacheKeyValue : m_matchedPropertiesCache) {
1334 if (cacheKeyValue.value.renderStyle->hasViewportUnits())
1335 toRemove.append(cacheKeyValue.key);
1336 }
1337 for (auto key : toRemove)
1338 m_matchedPropertiesCache.remove(key);
1339}
1340
1341static bool isCacheableInMatchedPropertiesCache(const Element& element, const RenderStyle* style, const RenderStyle* parentStyle)
1342{
1343 // FIXME: Writing mode and direction properties modify state when applying to document element by calling
1344 // Document::setWritingMode/DirectionSetOnDocumentElement. We can't skip the applying by caching.
1345 if (&element == element.document().documentElement())
1346 return false;
1347 // content:attr() value depends on the element it is being applied to.
1348 if (style->hasAttrContent() || (style->styleType() != PseudoId::None && parentStyle->hasAttrContent()))
1349 return false;
1350 if (style->hasAppearance())
1351 return false;
1352 if (style->zoom() != RenderStyle::initialZoom())
1353 return false;
1354 if (style->writingMode() != RenderStyle::initialWritingMode() || style->direction() != RenderStyle::initialDirection())
1355 return false;
1356 // The cache assumes static knowledge about which properties are inherited.
1357 if (style->hasExplicitlyInheritedProperties())
1358 return false;
1359 return true;
1360}
1361
1362void extractDirectionAndWritingMode(const RenderStyle& style, const StyleResolver::MatchResult& matchResult, TextDirection& direction, WritingMode& writingMode)
1363{
1364 direction = style.direction();
1365 writingMode = style.writingMode();
1366
1367 bool hadImportantWritingMode = false;
1368 bool hadImportantDirection = false;
1369
1370 for (const auto& matchedProperties : matchResult.matchedProperties()) {
1371 for (unsigned i = 0, count = matchedProperties.properties->propertyCount(); i < count; ++i) {
1372 auto property = matchedProperties.properties->propertyAt(i);
1373 if (!property.value()->isPrimitiveValue())
1374 continue;
1375 switch (property.id()) {
1376 case CSSPropertyWritingMode:
1377 if (!hadImportantWritingMode || property.isImportant()) {
1378 writingMode = downcast<CSSPrimitiveValue>(*property.value());
1379 hadImportantWritingMode = property.isImportant();
1380 }
1381 break;
1382 case CSSPropertyDirection:
1383 if (!hadImportantDirection || property.isImportant()) {
1384 direction = downcast<CSSPrimitiveValue>(*property.value());
1385 hadImportantDirection = property.isImportant();
1386 }
1387 break;
1388 default:
1389 break;
1390 }
1391 }
1392 }
1393}
1394
1395void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element& element, ShouldUseMatchedPropertiesCache shouldUseMatchedPropertiesCache)
1396{
1397 State& state = m_state;
1398 unsigned cacheHash = shouldUseMatchedPropertiesCache && matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties().data(), matchResult.matchedProperties().size()) : 0;
1399 bool applyInheritedOnly = false;
1400 const MatchedPropertiesCacheItem* cacheItem = nullptr;
1401 if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))
1402 && isCacheableInMatchedPropertiesCache(element, state.style(), state.parentStyle())) {
1403 // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
1404 // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
1405 // element context. This is fast and saves memory by reusing the style data structures.
1406 state.style()->copyNonInheritedFrom(*cacheItem->renderStyle);
1407 if (state.parentStyle()->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
1408 InsideLink linkStatus = state.style()->insideLink();
1409 // If the cache item parent style has identical inherited properties to the current parent style then the
1410 // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
1411 state.style()->inheritFrom(*cacheItem->renderStyle);
1412
1413 // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
1414 state.style()->setInsideLink(linkStatus);
1415 return;
1416 }
1417 applyInheritedOnly = true;
1418 }
1419
1420 // Directional properties (*-before/after) are aliases that depend on the TextDirection and WritingMode.
1421 // These must be resolved before we can begin the property cascade.
1422 TextDirection direction;
1423 WritingMode writingMode;
1424 extractDirectionAndWritingMode(*state.style(), matchResult, direction, writingMode);
1425
1426 if (elementTypeHasAppearanceFromUAStyle(*state.element())) {
1427 // FIXME: This is such a hack.
1428 // Find out if there's a -webkit-appearance property in effect from the UA sheet.
1429 // If so, we cache the border and background styles so that RenderTheme::adjustStyle()
1430 // can look at them later to figure out if this is a styled form control or not.
1431 CascadedProperties cascade(direction, writingMode);
1432 cascade.addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1433 cascade.addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1434
1435 ApplyCascadedPropertyState applyState { this, &cascade, &matchResult };
1436
1437 applyCascadedProperties(CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition, applyState);
1438 adjustStyleForInterCharacterRuby();
1439
1440#if ENABLE(DARK_MODE_CSS)
1441 // Supported color schemes can affect resolved colors, so we need to apply that property before any color properties.
1442 applyCascadedProperties(CSSPropertyColorScheme, CSSPropertyColorScheme, applyState);
1443#endif
1444
1445 applyCascadedProperties(firstCSSProperty, lastHighPriorityProperty, applyState);
1446
1447 // If our font got dirtied, update it now.
1448 updateFont();
1449
1450 // Now resolve remaining custom properties and the rest, in any order
1451 for (auto it = cascade.customProperties().begin(); it != cascade.customProperties().end(); ++it)
1452 applyCascadedCustomProperty(it->key, applyState);
1453 applyCascadedProperties(firstLowPriorityProperty, lastCSSProperty, applyState);
1454
1455 state.cacheBorderAndBackground();
1456 }
1457
1458 CascadedProperties cascade(direction, writingMode);
1459 cascade.addNormalMatches(matchResult, 0, matchResult.matchedProperties().size() - 1, applyInheritedOnly);
1460 cascade.addImportantMatches(matchResult, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
1461 cascade.addImportantMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
1462 cascade.addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1463
1464 ApplyCascadedPropertyState applyState { this, &cascade, &matchResult };
1465
1466 applyCascadedProperties(CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition, applyState);
1467 adjustStyleForInterCharacterRuby();
1468
1469#if ENABLE(DARK_MODE_CSS)
1470 // Supported color schemes can affect resolved colors, so we need to apply that property before any color properties.
1471 applyCascadedProperties(CSSPropertyColorScheme, CSSPropertyColorScheme, applyState);
1472#endif
1473
1474 applyCascadedProperties(firstCSSProperty, lastHighPriorityProperty, applyState);
1475
1476 // If the effective zoom value changes, we can't use the matched properties cache. Start over.
1477 if (cacheItem && cacheItem->renderStyle->effectiveZoom() != state.style()->effectiveZoom())
1478 return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
1479
1480 // If our font got dirtied, update it now.
1481 updateFont();
1482
1483 // If the font changed, we can't use the matched properties cache. Start over.
1484 if (cacheItem && cacheItem->renderStyle->fontDescription() != state.style()->fontDescription())
1485 return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
1486
1487 // Now resolve remaining custom properties and the rest, in any order
1488 for (auto it = cascade.customProperties().begin(); it != cascade.customProperties().end(); ++it)
1489 applyCascadedCustomProperty(it->key, applyState);
1490 applyCascadedProperties(firstLowPriorityProperty, lastCSSProperty, applyState);
1491
1492 // Finally, some properties must be applied in the order they were parsed.
1493 // There are some CSS properties that affect the same RenderStyle values,
1494 // so to preserve behavior, we queue them up during cascade and flush here.
1495 cascade.applyDeferredProperties(*this, applyState);
1496
1497 ASSERT(!state.fontDirty());
1498
1499 if (cacheItem || !cacheHash)
1500 return;
1501 if (!isCacheableInMatchedPropertiesCache(*state.element(), state.style(), state.parentStyle()))
1502 return;
1503 addToMatchedPropertiesCache(state.style(), state.parentStyle(), cacheHash, matchResult);
1504}
1505
1506void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, std::unique_ptr<RenderStyle> style)
1507{
1508 m_state = State();
1509 m_state.setParentStyle(RenderStyle::clonePtr(*style));
1510 m_state.setStyle(WTFMove(style));
1511 applyPropertyToCurrentStyle(id, value);
1512}
1513
1514void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
1515{
1516 ApplyCascadedPropertyState applyState { this, nullptr, nullptr };
1517 if (value)
1518 applyProperty(id, value, applyState);
1519}
1520
1521inline bool isValidVisitedLinkProperty(CSSPropertyID id)
1522{
1523 switch (id) {
1524 case CSSPropertyBackgroundColor:
1525 case CSSPropertyBorderLeftColor:
1526 case CSSPropertyBorderRightColor:
1527 case CSSPropertyBorderTopColor:
1528 case CSSPropertyBorderBottomColor:
1529 case CSSPropertyCaretColor:
1530 case CSSPropertyColor:
1531 case CSSPropertyOutlineColor:
1532 case CSSPropertyColumnRuleColor:
1533 case CSSPropertyTextDecorationColor:
1534 case CSSPropertyWebkitTextEmphasisColor:
1535 case CSSPropertyWebkitTextFillColor:
1536 case CSSPropertyWebkitTextStrokeColor:
1537 case CSSPropertyFill:
1538 case CSSPropertyStroke:
1539 case CSSPropertyStrokeColor:
1540 return true;
1541 default:
1542 break;
1543 }
1544
1545 return false;
1546}
1547
1548// https://www.w3.org/TR/css-pseudo-4/#marker-pseudo (Editor's Draft, 25 July 2017)
1549static inline bool isValidMarkerStyleProperty(CSSPropertyID id)
1550{
1551 switch (id) {
1552 case CSSPropertyColor:
1553 case CSSPropertyFontFamily:
1554 case CSSPropertyFontFeatureSettings:
1555 case CSSPropertyFontSize:
1556 case CSSPropertyFontStretch:
1557 case CSSPropertyFontStyle:
1558 case CSSPropertyFontSynthesis:
1559 case CSSPropertyFontVariantAlternates:
1560 case CSSPropertyFontVariantCaps:
1561 case CSSPropertyFontVariantEastAsian:
1562 case CSSPropertyFontVariantLigatures:
1563 case CSSPropertyFontVariantNumeric:
1564 case CSSPropertyFontVariantPosition:
1565 case CSSPropertyFontWeight:
1566#if ENABLE(VARIATION_FONTS)
1567 case CSSPropertyFontOpticalSizing:
1568 case CSSPropertyFontVariationSettings:
1569#endif
1570 return true;
1571 default:
1572 break;
1573 }
1574 return false;
1575}
1576
1577#if ENABLE(VIDEO_TRACK)
1578static inline bool isValidCueStyleProperty(CSSPropertyID id)
1579{
1580 switch (id) {
1581 case CSSPropertyBackground:
1582 case CSSPropertyBackgroundAttachment:
1583 case CSSPropertyBackgroundClip:
1584 case CSSPropertyBackgroundColor:
1585 case CSSPropertyBackgroundImage:
1586 case CSSPropertyBackgroundOrigin:
1587 case CSSPropertyBackgroundPosition:
1588 case CSSPropertyBackgroundPositionX:
1589 case CSSPropertyBackgroundPositionY:
1590 case CSSPropertyBackgroundRepeat:
1591 case CSSPropertyBackgroundSize:
1592 case CSSPropertyColor:
1593 case CSSPropertyFont:
1594 case CSSPropertyFontFamily:
1595 case CSSPropertyFontSize:
1596 case CSSPropertyFontStyle:
1597 case CSSPropertyFontVariantCaps:
1598 case CSSPropertyFontWeight:
1599 case CSSPropertyLineHeight:
1600 case CSSPropertyOpacity:
1601 case CSSPropertyOutline:
1602 case CSSPropertyOutlineColor:
1603 case CSSPropertyOutlineOffset:
1604 case CSSPropertyOutlineStyle:
1605 case CSSPropertyOutlineWidth:
1606 case CSSPropertyVisibility:
1607 case CSSPropertyWhiteSpace:
1608 case CSSPropertyTextDecoration:
1609 case CSSPropertyTextShadow:
1610 case CSSPropertyBorderStyle:
1611 case CSSPropertyPaintOrder:
1612 case CSSPropertyStrokeLinejoin:
1613 case CSSPropertyStrokeLinecap:
1614 case CSSPropertyStrokeColor:
1615 case CSSPropertyStrokeWidth:
1616 return true;
1617 default:
1618 break;
1619 }
1620 return false;
1621}
1622#endif
1623// SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
1624// of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
1625// multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
1626// Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
1627// need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
1628// width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
1629// if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
1630// properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
1631bool StyleResolver::useSVGZoomRules() const
1632{
1633 return m_state.element() && m_state.element()->isSVGElement();
1634}
1635
1636// Scale with/height properties on inline SVG root.
1637bool StyleResolver::useSVGZoomRulesForLength() const
1638{
1639 return is<SVGElement>(m_state.element()) && !(is<SVGSVGElement>(*m_state.element()) && m_state.element()->parentNode());
1640}
1641
1642StyleResolver::CascadedProperties* StyleResolver::cascadedPropertiesForRollback(const MatchResult& matchResult)
1643{
1644 ASSERT(cascadeLevel() != CascadeLevel::UserAgentLevel);
1645
1646 TextDirection direction;
1647 WritingMode writingMode;
1648 extractDirectionAndWritingMode(*state().style(), matchResult, direction, writingMode);
1649
1650 if (cascadeLevel() == CascadeLevel::AuthorLevel) {
1651 CascadedProperties* authorRollback = state().authorRollback();
1652 if (authorRollback)
1653 return authorRollback;
1654
1655 auto newAuthorRollback(std::make_unique<CascadedProperties>(direction, writingMode));
1656
1657 // This special rollback cascade contains UA rules and user rules but no author rules.
1658 newAuthorRollback->addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1659 newAuthorRollback->addNormalMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, false);
1660 newAuthorRollback->addImportantMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, false);
1661 newAuthorRollback->addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1662
1663 state().setAuthorRollback(newAuthorRollback);
1664 return state().authorRollback();
1665 }
1666
1667 if (cascadeLevel() == CascadeLevel::UserLevel) {
1668 CascadedProperties* userRollback = state().userRollback();
1669 if (userRollback)
1670 return userRollback;
1671
1672 auto newUserRollback(std::make_unique<CascadedProperties>(direction, writingMode));
1673
1674 // This special rollback cascade contains only UA rules.
1675 newUserRollback->addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1676 newUserRollback->addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1677
1678 state().setUserRollback(newUserRollback);
1679 return state().userRollback();
1680 }
1681
1682 return nullptr;
1683}
1684
1685void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value, ApplyCascadedPropertyState& applyState, SelectorChecker::LinkMatchMask linkMatchMask)
1686{
1687 auto* matchResult = applyState.matchResult;
1688 ASSERT_WITH_MESSAGE(!isShorthandCSSProperty(id), "Shorthand property id = %d wasn't expanded at parsing time", id);
1689
1690 State& state = m_state;
1691
1692 RefPtr<CSSValue> valueToApply = value;
1693 if (value->hasVariableReferences()) {
1694 valueToApply = resolvedVariableValue(id, *value, applyState);
1695 // If appliedProperties already has this id, then we detected a cycle, and this value should be unset.
1696 if (!valueToApply || applyState.appliedProperties.get(id)) {
1697 if (CSSProperty::isInheritedProperty(id))
1698 valueToApply = CSSValuePool::singleton().createInheritedValue();
1699 else
1700 valueToApply = CSSValuePool::singleton().createExplicitInitialValue();
1701 }
1702 }
1703
1704 if (CSSProperty::isDirectionAwareProperty(id)) {
1705 CSSPropertyID newId = CSSProperty::resolveDirectionAwareProperty(id, state.style()->direction(), state.style()->writingMode());
1706 ASSERT(newId != id);
1707 return applyProperty(newId, valueToApply.get(), applyState, linkMatchMask);
1708 }
1709
1710 CSSValue* valueToCheckForInheritInitial = valueToApply.get();
1711 CSSCustomPropertyValue* customPropertyValue = nullptr;
1712 CSSValueID customPropertyValueID = CSSValueInvalid;
1713
1714 CSSRegisteredCustomProperty* customPropertyRegistered = nullptr;
1715
1716 if (id == CSSPropertyCustom) {
1717 customPropertyValue = &downcast<CSSCustomPropertyValue>(*valueToApply);
1718 ASSERT(customPropertyValue->isResolved());
1719 if (WTF::holds_alternative<CSSValueID>(customPropertyValue->value()))
1720 customPropertyValueID = WTF::get<CSSValueID>(customPropertyValue->value());
1721 auto& name = customPropertyValue->name();
1722 customPropertyRegistered = document().getCSSRegisteredCustomPropertySet().get(name);
1723 }
1724
1725 bool isInherit = state.parentStyle() ? valueToCheckForInheritInitial->isInheritedValue() || customPropertyValueID == CSSValueInherit : false;
1726 bool isInitial = valueToCheckForInheritInitial->isInitialValue() || customPropertyValueID == CSSValueInitial || (!state.parentStyle() && (valueToCheckForInheritInitial->isInheritedValue() || customPropertyValueID == CSSValueInherit));
1727
1728 bool isUnset = valueToCheckForInheritInitial->isUnsetValue() || customPropertyValueID == CSSValueUnset;
1729 bool isRevert = valueToCheckForInheritInitial->isRevertValue() || customPropertyValueID == CSSValueRevert;
1730
1731 if (isRevert) {
1732 if (cascadeLevel() == CascadeLevel::UserAgentLevel || !matchResult)
1733 isUnset = true;
1734 else {
1735 // Fetch the correct rollback object from the state, building it if necessary.
1736 // This requires having the original MatchResult available.
1737 auto* rollback = cascadedPropertiesForRollback(*matchResult);
1738 ASSERT(rollback);
1739
1740 // With the cascade built, we need to obtain the property and apply it. If the property is
1741 // not present, then we behave like "unset." Otherwise we apply the property instead of
1742 // our own.
1743 if (customPropertyValue) {
1744 if (customPropertyRegistered && customPropertyRegistered->inherits && rollback->hasCustomProperty(customPropertyValue->name())) {
1745 auto property = rollback->customProperty(customPropertyValue->name());
1746 if (property.cssValue[linkMatchMask])
1747 applyProperty(property.id, property.cssValue[linkMatchMask], applyState, linkMatchMask);
1748 return;
1749 }
1750 } else if (rollback->hasProperty(id)) {
1751 auto& property = rollback->property(id);
1752 if (property.cssValue[linkMatchMask])
1753 applyProperty(property.id, property.cssValue[linkMatchMask], applyState, linkMatchMask);
1754 return;
1755 }
1756
1757 isUnset = true;
1758 }
1759 }
1760
1761 if (isUnset) {
1762 if (CSSProperty::isInheritedProperty(id))
1763 isInherit = true;
1764 else
1765 isInitial = true;
1766 }
1767
1768 ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
1769
1770 if (!state.applyPropertyToRegularStyle() && (!state.applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
1771 // Limit the properties that can be applied to only the ones honored by :visited.
1772 return;
1773 }
1774
1775 if (isInherit && !CSSProperty::isInheritedProperty(id))
1776 state.style()->setHasExplicitlyInheritedProperties();
1777
1778#if ENABLE(CSS_PAINTING_API)
1779 if (is<CSSPaintImageValue>(*valueToApply)) {
1780 auto& name = downcast<CSSPaintImageValue>(*valueToApply).name();
1781 if (auto* paintWorklet = document().paintWorkletGlobalScopeForName(name)) {
1782 auto locker = holdLock(paintWorklet->paintDefinitionLock());
1783 if (auto* registration = paintWorklet->paintDefinitionMap().get(name)) {
1784 for (auto& property : registration->inputProperties)
1785 state.style()->addCustomPaintWatchProperty(property);
1786 }
1787 }
1788 }
1789#endif
1790
1791 // Use the generated StyleBuilder.
1792 StyleBuilder::applyProperty(id, *this, *valueToApply, isInitial, isInherit, customPropertyRegistered);
1793}
1794
1795RefPtr<CSSValue> StyleResolver::resolvedVariableValue(CSSPropertyID propID, const CSSValue& value, ApplyCascadedPropertyState& state) const
1796{
1797 CSSParser parser(document());
1798 return parser.parseValueWithVariableReferences(propID, value, state);
1799}
1800
1801RefPtr<StyleImage> StyleResolver::styleImage(CSSValue& value)
1802{
1803 if (is<CSSImageGeneratorValue>(value)) {
1804 if (is<CSSGradientValue>(value))
1805 return StyleGeneratedImage::create(downcast<CSSGradientValue>(value).gradientWithStylesResolved(*this));
1806
1807 if (is<CSSFilterImageValue>(value)) {
1808 // FilterImage needs to calculate FilterOperations.
1809 downcast<CSSFilterImageValue>(value).createFilterOperations(this);
1810 }
1811 return StyleGeneratedImage::create(downcast<CSSImageGeneratorValue>(value));
1812 }
1813
1814 if (is<CSSImageValue>(value) || is<CSSImageSetValue>(value) || is<CSSCursorImageValue>(value))
1815 return StyleCachedImage::create(value);
1816
1817 return nullptr;
1818}
1819
1820#if ENABLE(TEXT_AUTOSIZING)
1821void StyleResolver::checkForTextSizeAdjust(RenderStyle* style)
1822{
1823 if (style->textSizeAdjust().isAuto())
1824 return;
1825
1826 auto newFontDescription = style->fontDescription();
1827 if (!style->textSizeAdjust().isNone())
1828 newFontDescription.setComputedSize(newFontDescription.specifiedSize() * style->textSizeAdjust().multiplier());
1829 else
1830 newFontDescription.setComputedSize(newFontDescription.specifiedSize());
1831 style->setFontDescription(WTFMove(newFontDescription));
1832}
1833#endif
1834
1835void StyleResolver::checkForZoomChange(RenderStyle* style, const RenderStyle* parentStyle)
1836{
1837 if (!parentStyle)
1838 return;
1839
1840 if (style->effectiveZoom() == parentStyle->effectiveZoom() && style->textZoom() == parentStyle->textZoom())
1841 return;
1842
1843 const auto& childFont = style->fontDescription();
1844 auto newFontDescription = childFont;
1845 setFontSize(newFontDescription, childFont.specifiedSize());
1846 style->setFontDescription(WTFMove(newFontDescription));
1847}
1848
1849void StyleResolver::checkForGenericFamilyChange(RenderStyle* style, const RenderStyle* parentStyle)
1850{
1851 const auto& childFont = style->fontDescription();
1852
1853 if (childFont.isAbsoluteSize() || !parentStyle)
1854 return;
1855
1856 const auto& parentFont = parentStyle->fontDescription();
1857 if (childFont.useFixedDefaultSize() == parentFont.useFixedDefaultSize())
1858 return;
1859 // We know the parent is monospace or the child is monospace, and that font
1860 // size was unspecified. We want to scale our font size as appropriate.
1861 // If the font uses a keyword size, then we refetch from the table rather than
1862 // multiplying by our scale factor.
1863 float size;
1864 if (CSSValueID sizeIdentifier = childFont.keywordSizeAsIdentifier())
1865 size = Style::fontSizeForKeyword(sizeIdentifier, childFont.useFixedDefaultSize(), document());
1866 else {
1867 float fixedScaleFactor = (settings().defaultFixedFontSize() && settings().defaultFontSize())
1868 ? static_cast<float>(settings().defaultFixedFontSize()) / settings().defaultFontSize()
1869 : 1;
1870 size = parentFont.useFixedDefaultSize() ?
1871 childFont.specifiedSize() / fixedScaleFactor :
1872 childFont.specifiedSize() * fixedScaleFactor;
1873 }
1874
1875 auto newFontDescription = childFont;
1876 setFontSize(newFontDescription, size);
1877 style->setFontDescription(WTFMove(newFontDescription));
1878}
1879
1880void StyleResolver::initializeFontStyle()
1881{
1882 FontCascadeDescription fontDescription;
1883 fontDescription.setRenderingMode(settings().fontRenderingMode());
1884 fontDescription.setOneFamily(standardFamily);
1885 fontDescription.setKeywordSizeFromIdentifier(CSSValueMedium);
1886 setFontSize(fontDescription, Style::fontSizeForKeyword(CSSValueMedium, false, document()));
1887 fontDescription.setShouldAllowUserInstalledFonts(settings().shouldAllowUserInstalledFonts() ? AllowUserInstalledFonts::Yes : AllowUserInstalledFonts::No);
1888 setFontDescription(WTFMove(fontDescription));
1889}
1890
1891void StyleResolver::setFontSize(FontCascadeDescription& fontDescription, float size)
1892{
1893 fontDescription.setSpecifiedSize(size);
1894 fontDescription.setComputedSize(Style::computedFontSizeFromSpecifiedSize(size, fontDescription.isAbsoluteSize(), useSVGZoomRules(), m_state.style(), document()));
1895}
1896
1897bool StyleResolver::colorFromPrimitiveValueIsDerivedFromElement(const CSSPrimitiveValue& value)
1898{
1899 switch (value.valueID()) {
1900 case CSSValueWebkitText:
1901 case CSSValueWebkitLink:
1902 case CSSValueWebkitActivelink:
1903 case CSSValueCurrentcolor:
1904 return true;
1905 default:
1906 return false;
1907 }
1908}
1909
1910Color StyleResolver::colorFromPrimitiveValue(const CSSPrimitiveValue& value, bool forVisitedLink) const
1911{
1912 if (value.isRGBColor())
1913 return value.color();
1914
1915 auto identifier = value.valueID();
1916 switch (identifier) {
1917 case CSSValueWebkitText:
1918 return document().textColor();
1919 case CSSValueWebkitLink:
1920 return (m_state.element()->isLink() && forVisitedLink) ? document().visitedLinkColor() : document().linkColor();
1921 case CSSValueWebkitActivelink:
1922 return document().activeLinkColor();
1923 case CSSValueWebkitFocusRingColor:
1924 return RenderTheme::singleton().focusRingColor(document().styleColorOptions(m_state.style()));
1925 case CSSValueCurrentcolor:
1926 // Color is an inherited property so depending on it effectively makes the property inherited.
1927 // FIXME: Setting the flag as a side effect of calling this function is a bit oblique. Can we do better?
1928 m_state.style()->setHasExplicitlyInheritedProperties();
1929 return m_state.style()->color();
1930 default:
1931 return StyleColor::colorFromKeyword(identifier, document().styleColorOptions(m_state.style()));
1932 }
1933}
1934
1935void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExpression& expression, bool result)
1936{
1937 m_viewportDependentMediaQueryResults.append(MediaQueryResult { expression, result });
1938}
1939
1940bool StyleResolver::hasMediaQueriesAffectedByViewportChange() const
1941{
1942 LOG(MediaQueries, "StyleResolver::hasMediaQueriesAffectedByViewportChange evaluating queries");
1943 for (auto& result : m_viewportDependentMediaQueryResults) {
1944 if (m_mediaQueryEvaluator.evaluate(result.expression) != result.result)
1945 return true;
1946 }
1947 return false;
1948}
1949
1950void StyleResolver::addAccessibilitySettingsDependentMediaQueryResult(const MediaQueryExpression& expression, bool result)
1951{
1952 m_accessibilitySettingsDependentMediaQueryResults.append(MediaQueryResult { expression, result });
1953}
1954
1955bool StyleResolver::hasMediaQueriesAffectedByAccessibilitySettingsChange() const
1956{
1957 LOG(MediaQueries, "StyleResolver::hasMediaQueriesAffectedByAccessibilitySettingsChange evaluating queries");
1958 for (auto& result : m_accessibilitySettingsDependentMediaQueryResults) {
1959 if (m_mediaQueryEvaluator.evaluate(result.expression) != result.result)
1960 return true;
1961 }
1962 return false;
1963}
1964
1965void StyleResolver::addAppearanceDependentMediaQueryResult(const MediaQueryExpression& expression, bool result)
1966{
1967 m_appearanceDependentMediaQueryResults.append(MediaQueryResult { expression, result });
1968}
1969
1970bool StyleResolver::hasMediaQueriesAffectedByAppearanceChange() const
1971{
1972 LOG(MediaQueries, "StyleResolver::hasMediaQueriesAffectedByAppearanceChange evaluating queries");
1973 for (auto& result : m_appearanceDependentMediaQueryResults) {
1974 if (m_mediaQueryEvaluator.evaluate(result.expression) != result.result)
1975 return true;
1976 }
1977 return false;
1978}
1979
1980static FilterOperation::OperationType filterOperationForType(CSSValueID type)
1981{
1982 switch (type) {
1983 case CSSValueUrl:
1984 return FilterOperation::REFERENCE;
1985 case CSSValueGrayscale:
1986 return FilterOperation::GRAYSCALE;
1987 case CSSValueSepia:
1988 return FilterOperation::SEPIA;
1989 case CSSValueSaturate:
1990 return FilterOperation::SATURATE;
1991 case CSSValueHueRotate:
1992 return FilterOperation::HUE_ROTATE;
1993 case CSSValueInvert:
1994 return FilterOperation::INVERT;
1995 case CSSValueAppleInvertLightness:
1996 return FilterOperation::APPLE_INVERT_LIGHTNESS;
1997 case CSSValueOpacity:
1998 return FilterOperation::OPACITY;
1999 case CSSValueBrightness:
2000 return FilterOperation::BRIGHTNESS;
2001 case CSSValueContrast:
2002 return FilterOperation::CONTRAST;
2003 case CSSValueBlur:
2004 return FilterOperation::BLUR;
2005 case CSSValueDropShadow:
2006 return FilterOperation::DROP_SHADOW;
2007 default:
2008 break;
2009 }
2010 ASSERT_NOT_REACHED();
2011 return FilterOperation::NONE;
2012}
2013
2014bool StyleResolver::createFilterOperations(const CSSValue& inValue, FilterOperations& outOperations)
2015{
2016 State& state = m_state;
2017 ASSERT(outOperations.isEmpty());
2018
2019 if (is<CSSPrimitiveValue>(inValue)) {
2020 auto& primitiveValue = downcast<CSSPrimitiveValue>(inValue);
2021 if (primitiveValue.valueID() == CSSValueNone)
2022 return true;
2023 }
2024
2025 if (!is<CSSValueList>(inValue))
2026 return false;
2027
2028 FilterOperations operations;
2029 for (auto& currentValue : downcast<CSSValueList>(inValue)) {
2030
2031 if (is<CSSPrimitiveValue>(currentValue)) {
2032 auto& primitiveValue = downcast<CSSPrimitiveValue>(currentValue.get());
2033 if (!primitiveValue.isURI())
2034 continue;
2035
2036 String cssUrl = primitiveValue.stringValue();
2037 URL url = document().completeURL(cssUrl);
2038
2039 auto operation = ReferenceFilterOperation::create(cssUrl, url.fragmentIdentifier());
2040 operations.operations().append(WTFMove(operation));
2041 continue;
2042 }
2043
2044 if (!is<CSSFunctionValue>(currentValue))
2045 continue;
2046
2047 auto& filterValue = downcast<CSSFunctionValue>(currentValue.get());
2048 FilterOperation::OperationType operationType = filterOperationForType(filterValue.name());
2049
2050 // Check that all parameters are primitive values, with the
2051 // exception of drop shadow which has a CSSShadowValue parameter.
2052 const CSSPrimitiveValue* firstValue = nullptr;
2053 if (operationType != FilterOperation::DROP_SHADOW) {
2054 bool haveNonPrimitiveValue = false;
2055 for (unsigned j = 0; j < filterValue.length(); ++j) {
2056 if (!is<CSSPrimitiveValue>(*filterValue.itemWithoutBoundsCheck(j))) {
2057 haveNonPrimitiveValue = true;
2058 break;
2059 }
2060 }
2061 if (haveNonPrimitiveValue)
2062 continue;
2063 if (filterValue.length())
2064 firstValue = downcast<CSSPrimitiveValue>(filterValue.itemWithoutBoundsCheck(0));
2065 }
2066
2067 switch (operationType) {
2068 case FilterOperation::GRAYSCALE:
2069 case FilterOperation::SEPIA:
2070 case FilterOperation::SATURATE: {
2071 double amount = 1;
2072 if (filterValue.length() == 1) {
2073 amount = firstValue->doubleValue();
2074 if (firstValue->isPercentage())
2075 amount /= 100;
2076 }
2077
2078 operations.operations().append(BasicColorMatrixFilterOperation::create(amount, operationType));
2079 break;
2080 }
2081 case FilterOperation::HUE_ROTATE: {
2082 double angle = 0;
2083 if (filterValue.length() == 1)
2084 angle = firstValue->computeDegrees();
2085
2086 operations.operations().append(BasicColorMatrixFilterOperation::create(angle, operationType));
2087 break;
2088 }
2089 case FilterOperation::INVERT:
2090 case FilterOperation::BRIGHTNESS:
2091 case FilterOperation::CONTRAST:
2092 case FilterOperation::OPACITY: {
2093 double amount = 1;
2094 if (filterValue.length() == 1) {
2095 amount = firstValue->doubleValue();
2096 if (firstValue->isPercentage())
2097 amount /= 100;
2098 }
2099
2100 operations.operations().append(BasicComponentTransferFilterOperation::create(amount, operationType));
2101 break;
2102 }
2103 case FilterOperation::APPLE_INVERT_LIGHTNESS: {
2104 operations.operations().append(InvertLightnessFilterOperation::create());
2105 break;
2106 }
2107 case FilterOperation::BLUR: {
2108 Length stdDeviation = Length(0, Fixed);
2109 if (filterValue.length() >= 1)
2110 stdDeviation = convertToFloatLength(firstValue, state.cssToLengthConversionData());
2111 if (stdDeviation.isUndefined())
2112 return false;
2113
2114 operations.operations().append(BlurFilterOperation::create(stdDeviation));
2115 break;
2116 }
2117 case FilterOperation::DROP_SHADOW: {
2118 if (filterValue.length() != 1)
2119 return false;
2120
2121 const auto* cssValue = filterValue.itemWithoutBoundsCheck(0);
2122 if (!is<CSSShadowValue>(cssValue))
2123 continue;
2124
2125 const auto& item = downcast<CSSShadowValue>(*cssValue);
2126 int x = item.x->computeLength<int>(state.cssToLengthConversionData());
2127 int y = item.y->computeLength<int>(state.cssToLengthConversionData());
2128 IntPoint location(x, y);
2129 int blur = item.blur ? item.blur->computeLength<int>(state.cssToLengthConversionData()) : 0;
2130 Color color;
2131 if (item.color)
2132 color = colorFromPrimitiveValue(*item.color);
2133
2134 operations.operations().append(DropShadowFilterOperation::create(location, blur, color.isValid() ? color : Color::transparent));
2135 break;
2136 }
2137 default:
2138 ASSERT_NOT_REACHED();
2139 break;
2140 }
2141 }
2142
2143 outOperations = operations;
2144 return true;
2145}
2146
2147inline StyleResolver::MatchedProperties::MatchedProperties() = default;
2148
2149StyleResolver::MatchedProperties::~MatchedProperties() = default;
2150
2151StyleResolver::CascadedProperties::CascadedProperties(TextDirection direction, WritingMode writingMode)
2152 : m_direction(direction)
2153 , m_writingMode(writingMode)
2154{
2155}
2156
2157inline bool StyleResolver::CascadedProperties::hasProperty(CSSPropertyID id) const
2158{
2159 ASSERT(id < m_propertyIsPresent.size());
2160 return m_propertyIsPresent[id];
2161}
2162
2163inline StyleResolver::CascadedProperties::Property& StyleResolver::CascadedProperties::property(CSSPropertyID id)
2164{
2165 return m_properties[id];
2166}
2167
2168inline bool StyleResolver::CascadedProperties::hasCustomProperty(const String& name) const
2169{
2170 return m_customProperties.contains(name);
2171}
2172
2173inline StyleResolver::CascadedProperties::Property StyleResolver::CascadedProperties::customProperty(const String& name) const
2174{
2175 return m_customProperties.get(name);
2176}
2177
2178void StyleResolver::CascadedProperties::setPropertyInternal(Property& property, CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel, Style::ScopeOrdinal styleScopeOrdinal)
2179{
2180 ASSERT(linkMatchType <= SelectorChecker::MatchAll);
2181 property.id = id;
2182 property.level = cascadeLevel;
2183 property.styleScopeOrdinal = styleScopeOrdinal;
2184 if (linkMatchType == SelectorChecker::MatchAll) {
2185 property.cssValue[0] = &cssValue;
2186 property.cssValue[SelectorChecker::MatchLink] = &cssValue;
2187 property.cssValue[SelectorChecker::MatchVisited] = &cssValue;
2188 } else
2189 property.cssValue[linkMatchType] = &cssValue;
2190}
2191
2192void StyleResolver::CascadedProperties::set(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel, Style::ScopeOrdinal styleScopeOrdinal)
2193{
2194 if (CSSProperty::isDirectionAwareProperty(id))
2195 id = CSSProperty::resolveDirectionAwareProperty(id, m_direction, m_writingMode);
2196
2197 ASSERT(!shouldApplyPropertyInParseOrder(id));
2198
2199 auto& property = m_properties[id];
2200 ASSERT(id < m_propertyIsPresent.size());
2201 if (id == CSSPropertyCustom) {
2202 m_propertyIsPresent.set(id);
2203 const auto& customValue = downcast<CSSCustomPropertyValue>(cssValue);
2204 bool hasValue = customProperties().contains(customValue.name());
2205 if (!hasValue) {
2206 Property property;
2207 property.id = id;
2208 memset(property.cssValue, 0, sizeof(property.cssValue));
2209 setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel, styleScopeOrdinal);
2210 customProperties().set(customValue.name(), property);
2211 } else {
2212 Property property = customProperties().get(customValue.name());
2213 setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel, styleScopeOrdinal);
2214 customProperties().set(customValue.name(), property);
2215 }
2216 return;
2217 }
2218
2219 if (!m_propertyIsPresent[id])
2220 memset(property.cssValue, 0, sizeof(property.cssValue));
2221 m_propertyIsPresent.set(id);
2222 setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel, styleScopeOrdinal);
2223}
2224
2225void StyleResolver::CascadedProperties::setDeferred(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel, Style::ScopeOrdinal styleScopeOrdinal)
2226{
2227 ASSERT(!CSSProperty::isDirectionAwareProperty(id));
2228 ASSERT(shouldApplyPropertyInParseOrder(id));
2229
2230 Property property;
2231 memset(property.cssValue, 0, sizeof(property.cssValue));
2232 setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel, styleScopeOrdinal);
2233 m_deferredProperties.append(property);
2234}
2235
2236static CascadeLevel cascadeLevelForIndex(const StyleResolver::MatchResult& matchResult, int index)
2237{
2238 if (index >= matchResult.ranges.firstUARule && index <= matchResult.ranges.lastUARule)
2239 return CascadeLevel::UserAgentLevel;
2240 if (index >= matchResult.ranges.firstUserRule && index <= matchResult.ranges.lastUserRule)
2241 return CascadeLevel::UserLevel;
2242 return CascadeLevel::AuthorLevel;
2243}
2244
2245void StyleResolver::CascadedProperties::addMatch(const MatchResult& matchResult, unsigned index, bool isImportant, bool inheritedOnly)
2246{
2247 auto& matchedProperties = matchResult.matchedProperties()[index];
2248 auto& styleProperties = *matchedProperties.properties;
2249
2250 auto propertyWhitelistType = static_cast<PropertyWhitelistType>(matchedProperties.whitelistType);
2251 auto cascadeLevel = cascadeLevelForIndex(matchResult, index);
2252
2253 for (unsigned i = 0, count = styleProperties.propertyCount(); i < count; ++i) {
2254 auto current = styleProperties.propertyAt(i);
2255 if (isImportant != current.isImportant())
2256 continue;
2257 if (inheritedOnly && !current.isInherited()) {
2258 // We apply the inherited properties only when using the property cache.
2259 // A match with a value that is explicitely inherited should never have been cached.
2260 ASSERT(!current.value()->isInheritedValue());
2261 continue;
2262 }
2263 CSSPropertyID propertyID = current.id();
2264
2265#if ENABLE(VIDEO_TRACK)
2266 if (propertyWhitelistType == PropertyWhitelistCue && !isValidCueStyleProperty(propertyID))
2267 continue;
2268#endif
2269 if (propertyWhitelistType == PropertyWhitelistMarker && !isValidMarkerStyleProperty(propertyID))
2270 continue;
2271
2272 if (shouldApplyPropertyInParseOrder(propertyID))
2273 setDeferred(propertyID, *current.value(), matchedProperties.linkMatchType, cascadeLevel, matchedProperties.styleScopeOrdinal);
2274 else
2275 set(propertyID, *current.value(), matchedProperties.linkMatchType, cascadeLevel, matchedProperties.styleScopeOrdinal);
2276 }
2277}
2278
2279void StyleResolver::CascadedProperties::addNormalMatches(const MatchResult& matchResult, int startIndex, int endIndex, bool inheritedOnly)
2280{
2281 if (startIndex == -1)
2282 return;
2283
2284 for (int i = startIndex; i <= endIndex; ++i)
2285 addMatch(matchResult, i, false, inheritedOnly);
2286}
2287
2288static bool hasImportantProperties(const StyleProperties& properties)
2289{
2290 for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
2291 if (properties.propertyAt(i).isImportant())
2292 return true;
2293 }
2294 return false;
2295}
2296
2297void StyleResolver::CascadedProperties::addImportantMatches(const MatchResult& matchResult, int startIndex, int endIndex, bool inheritedOnly)
2298{
2299 if (startIndex == -1)
2300 return;
2301
2302 struct IndexAndOrdinal {
2303 int index;
2304 Style::ScopeOrdinal ordinal;
2305 };
2306 Vector<IndexAndOrdinal> shadowTreeMatches;
2307
2308 for (int i = startIndex; i <= endIndex; ++i) {
2309 const MatchedProperties& matchedProperties = matchResult.matchedProperties()[i];
2310
2311 if (!hasImportantProperties(*matchedProperties.properties))
2312 continue;
2313
2314 if (matchedProperties.styleScopeOrdinal != Style::ScopeOrdinal::Element) {
2315 shadowTreeMatches.append({ i, matchedProperties.styleScopeOrdinal });
2316 continue;
2317 }
2318
2319 addMatch(matchResult, i, true, inheritedOnly);
2320 }
2321
2322 if (shadowTreeMatches.isEmpty())
2323 return;
2324
2325 // For !important properties a later shadow tree wins.
2326 // Match results are sorted in reverse tree context order so this is not needed for normal properties.
2327 std::stable_sort(shadowTreeMatches.begin(), shadowTreeMatches.end(), [] (const IndexAndOrdinal& a, const IndexAndOrdinal& b) {
2328 return a.ordinal < b.ordinal;
2329 });
2330
2331 for (auto& match : shadowTreeMatches)
2332 addMatch(matchResult, match.index, true, inheritedOnly);
2333}
2334
2335void StyleResolver::CascadedProperties::applyDeferredProperties(StyleResolver& resolver, ApplyCascadedPropertyState& applyState)
2336{
2337 for (auto& property : m_deferredProperties)
2338 property.apply(resolver, applyState);
2339}
2340
2341void StyleResolver::CascadedProperties::Property::apply(StyleResolver& resolver, ApplyCascadedPropertyState& applyState)
2342{
2343 State& state = resolver.state();
2344 state.setCascadeLevel(level);
2345 state.setStyleScopeOrdinal(styleScopeOrdinal);
2346
2347 if (cssValue[SelectorChecker::MatchDefault]) {
2348 state.setApplyPropertyToRegularStyle(true);
2349 state.setApplyPropertyToVisitedLinkStyle(false);
2350 resolver.applyProperty(id, cssValue[SelectorChecker::MatchDefault], applyState, SelectorChecker::MatchDefault);
2351 }
2352
2353 if (state.style()->insideLink() == InsideLink::NotInside)
2354 return;
2355
2356 if (cssValue[SelectorChecker::MatchLink]) {
2357 state.setApplyPropertyToRegularStyle(true);
2358 state.setApplyPropertyToVisitedLinkStyle(false);
2359 resolver.applyProperty(id, cssValue[SelectorChecker::MatchLink], applyState, SelectorChecker::MatchLink);
2360 }
2361
2362 if (cssValue[SelectorChecker::MatchVisited]) {
2363 state.setApplyPropertyToRegularStyle(false);
2364 state.setApplyPropertyToVisitedLinkStyle(true);
2365 resolver.applyProperty(id, cssValue[SelectorChecker::MatchVisited], applyState, SelectorChecker::MatchVisited);
2366 }
2367
2368 state.setApplyPropertyToRegularStyle(true);
2369 state.setApplyPropertyToVisitedLinkStyle(false);
2370}
2371
2372void StyleResolver::applyCascadedCustomProperty(const String& name, ApplyCascadedPropertyState& state)
2373{
2374 if (state.appliedCustomProperties.contains(name) || !state.cascade->customProperties().contains(name))
2375 return;
2376
2377 auto property = state.cascade->customProperties().get(name);
2378 bool inCycle = state.inProgressPropertiesCustom.contains(name);
2379
2380 for (auto index : { SelectorChecker::MatchDefault, SelectorChecker::MatchLink, SelectorChecker::MatchVisited }) {
2381 if (!property.cssValue[index])
2382 continue;
2383 if (index != SelectorChecker::MatchDefault && this->state().style()->insideLink() == InsideLink::NotInside)
2384 continue;
2385
2386 Ref<CSSCustomPropertyValue> valueToApply = CSSCustomPropertyValue::create(downcast<CSSCustomPropertyValue>(*property.cssValue[index]));
2387
2388 if (inCycle) {
2389 state.appliedCustomProperties.add(name); // Make sure we do not try to apply this property again while resolving it.
2390 valueToApply = CSSCustomPropertyValue::createWithID(name, CSSValueInvalid);
2391 }
2392
2393 state.inProgressPropertiesCustom.add(name);
2394
2395 if (WTF::holds_alternative<Ref<CSSVariableReferenceValue>>(valueToApply->value())) {
2396 RefPtr<CSSValue> parsedValue = resolvedVariableValue(CSSPropertyCustom, valueToApply.get(), state);
2397
2398 if (state.appliedCustomProperties.contains(name))
2399 return; // There was a cycle and the value was reset, so bail.
2400
2401 if (!parsedValue)
2402 parsedValue = CSSCustomPropertyValue::createWithID(name, CSSValueUnset);
2403
2404 valueToApply = downcast<CSSCustomPropertyValue>(*parsedValue);
2405 }
2406
2407 if (state.inProgressPropertiesCustom.contains(name)) {
2408 if (index == SelectorChecker::MatchDefault) {
2409 this->state().setApplyPropertyToRegularStyle(true);
2410 this->state().setApplyPropertyToVisitedLinkStyle(false);
2411 }
2412
2413 if (index == SelectorChecker::MatchLink) {
2414 this->state().setApplyPropertyToRegularStyle(true);
2415 this->state().setApplyPropertyToVisitedLinkStyle(false);
2416 }
2417
2418 if (index == SelectorChecker::MatchVisited) {
2419 this->state().setApplyPropertyToRegularStyle(false);
2420 this->state().setApplyPropertyToVisitedLinkStyle(true);
2421 }
2422 applyProperty(CSSPropertyCustom, valueToApply.ptr(), state, index);
2423 }
2424 }
2425
2426 state.inProgressPropertiesCustom.remove(name);
2427 state.appliedCustomProperties.add(name);
2428
2429 for (auto index : { SelectorChecker::MatchDefault, SelectorChecker::MatchLink, SelectorChecker::MatchVisited }) {
2430 if (!property.cssValue[index])
2431 continue;
2432 if (index != SelectorChecker::MatchDefault && this->state().style()->insideLink() == InsideLink::NotInside)
2433 continue;
2434
2435 Ref<CSSCustomPropertyValue> valueToApply = CSSCustomPropertyValue::create(downcast<CSSCustomPropertyValue>(*property.cssValue[index]));
2436
2437 if (inCycle && WTF::holds_alternative<Ref<CSSVariableReferenceValue>>(valueToApply->value())) {
2438 // Resolve this value so that we reset its dependencies.
2439 resolvedVariableValue(CSSPropertyCustom, valueToApply.get(), state);
2440 }
2441 }
2442}
2443
2444void StyleResolver::applyCascadedProperties(int firstProperty, int lastProperty, ApplyCascadedPropertyState& state)
2445{
2446 if (LIKELY(state.cascade->customProperties().isEmpty()))
2447 return applyCascadedPropertiesImpl<CustomPropertyCycleTracking::Disabled>(firstProperty, lastProperty, state);
2448 return applyCascadedPropertiesImpl<CustomPropertyCycleTracking::Enabled>(firstProperty, lastProperty, state);
2449}
2450
2451template<StyleResolver::CustomPropertyCycleTracking TrackCycles>
2452inline void StyleResolver::applyCascadedPropertiesImpl(int firstProperty, int lastProperty, ApplyCascadedPropertyState& state)
2453{
2454 for (int id = firstProperty; id <= lastProperty; ++id) {
2455 CSSPropertyID propertyID = static_cast<CSSPropertyID>(id);
2456 if (!state.cascade->hasProperty(propertyID))
2457 continue;
2458 ASSERT(propertyID != CSSPropertyCustom);
2459 auto& property = state.cascade->property(propertyID);
2460 ASSERT(!shouldApplyPropertyInParseOrder(propertyID));
2461
2462 if (TrackCycles == CustomPropertyCycleTracking::Disabled) {
2463 // If we don't have any custom properties, then there can't be any cycles.
2464 property.apply(*this, state);
2465 } else {
2466 if (UNLIKELY(state.inProgressProperties.get(propertyID))) {
2467 // We are in a cycle (eg. setting font size using registered custom property value containing em).
2468 // So this value should be unset.
2469 state.appliedProperties.set(propertyID);
2470 // This property is in a cycle, and only the root of the call stack will have firstProperty != lastProperty.
2471 ASSERT(firstProperty == lastProperty);
2472 continue;
2473 }
2474
2475 state.inProgressProperties.set(propertyID);
2476 property.apply(*this, state);
2477 state.appliedProperties.set(propertyID);
2478 state.inProgressProperties.set(propertyID, false);
2479 }
2480 }
2481}
2482
2483} // namespace WebCore
2484