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