Writing-mode-dependent properties don't apply if their value is a variable
[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 #if ENABLE(SHADOW_DOM) || ENABLE(DETAILS_ELEMENT)
826             elementSupportsDisplayContents = is<HTMLSlotElement>(element);
827 #endif
828             if (!elementSupportsDisplayContents)
829                 style.setDisplay(INLINE);
830         }
831         if (element) {
832             // If we have a <td> that specifies a float property, in quirks mode we just drop the float
833             // property.
834             // Sites also commonly use display:inline/block on <td>s and <table>s. In quirks mode we force
835             // these tags to retain their display types.
836             if (document().inQuirksMode()) {
837                 if (element->hasTagName(tdTag)) {
838                     style.setDisplay(TABLE_CELL);
839                     style.setFloating(NoFloat);
840                 } else if (is<HTMLTableElement>(*element))
841                     style.setDisplay(style.isDisplayInlineType() ? INLINE_TABLE : TABLE);
842             }
843
844             if (element->hasTagName(tdTag) || element->hasTagName(thTag)) {
845                 if (style.whiteSpace() == KHTML_NOWRAP) {
846                     // Figure out if we are really nowrapping or if we should just
847                     // use normal instead. If the width of the cell is fixed, then
848                     // we don't actually use NOWRAP.
849                     if (style.width().isFixed())
850                         style.setWhiteSpace(NORMAL);
851                     else
852                         style.setWhiteSpace(NOWRAP);
853                 }
854             }
855
856             // Tables never support the -webkit-* values for text-align and will reset back to the default.
857             if (is<HTMLTableElement>(*element) && (style.textAlign() == WEBKIT_LEFT || style.textAlign() == WEBKIT_CENTER || style.textAlign() == WEBKIT_RIGHT))
858                 style.setTextAlign(TASTART);
859
860             // Frames and framesets never honor position:relative or position:absolute. This is necessary to
861             // fix a crash where a site tries to position these objects. They also never honor display.
862             if (element->hasTagName(frameTag) || element->hasTagName(framesetTag)) {
863                 style.setPosition(StaticPosition);
864                 style.setDisplay(BLOCK);
865             }
866
867             // Ruby text does not support float or position. This might change with evolution of the specification.
868             if (element->hasTagName(rtTag)) {
869                 style.setPosition(StaticPosition);
870                 style.setFloating(NoFloat);
871             }
872
873             // FIXME: We shouldn't be overriding start/-webkit-auto like this. Do it in html.css instead.
874             // Table headers with a text-align of -webkit-auto will change the text-align to center.
875             if (element->hasTagName(thTag) && style.textAlign() == TASTART)
876                 style.setTextAlign(CENTER);
877
878             if (element->hasTagName(legendTag))
879                 style.setDisplay(BLOCK);
880         }
881
882         // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
883         if (style.hasOutOfFlowPosition() || style.isFloating() || (element && element->document().documentElement() == element))
884             style.setDisplay(equivalentBlockDisplay(style.display(), style.isFloating(), !document().inQuirksMode()));
885
886         // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
887         // clear how that should work.
888         if (style.display() == INLINE && style.styleType() == NOPSEUDO && style.writingMode() != parentStyle.writingMode())
889             style.setDisplay(INLINE_BLOCK);
890
891         // After performing the display mutation, check table rows. We do not honor position:relative or position:sticky on
892         // table rows or cells. This has been established for position:relative in CSS2.1 (and caused a crash in containingBlock()
893         // on some sites).
894         if ((style.display() == TABLE_HEADER_GROUP || style.display() == TABLE_ROW_GROUP
895             || style.display() == TABLE_FOOTER_GROUP || style.display() == TABLE_ROW)
896             && style.position() == RelativePosition)
897             style.setPosition(StaticPosition);
898
899         // writing-mode does not apply to table row groups, table column groups, table rows, and table columns.
900         // FIXME: Table cells should be allowed to be perpendicular or flipped with respect to the table, though.
901         if (style.display() == TABLE_COLUMN || style.display() == TABLE_COLUMN_GROUP || style.display() == TABLE_FOOTER_GROUP
902             || style.display() == TABLE_HEADER_GROUP || style.display() == TABLE_ROW || style.display() == TABLE_ROW_GROUP
903             || style.display() == TABLE_CELL)
904             style.setWritingMode(parentStyle.writingMode());
905
906         // FIXME: Since we don't support block-flow on flexible boxes yet, disallow setting
907         // of block-flow to anything other than TopToBottomWritingMode.
908         // https://bugs.webkit.org/show_bug.cgi?id=46418 - Flexible box support.
909         if (style.writingMode() != TopToBottomWritingMode && (style.display() == BOX || style.display() == INLINE_BOX))
910             style.setWritingMode(TopToBottomWritingMode);
911
912         if (parentStyle.isDisplayFlexibleOrGridBox()) {
913             style.setFloating(NoFloat);
914             style.setDisplay(equivalentBlockDisplay(style.display(), style.isFloating(), !document().inQuirksMode()));
915         }
916     }
917
918     // Make sure our z-index value is only applied if the object is positioned.
919     if (style.position() == StaticPosition && !parentStyle.isDisplayFlexibleOrGridBox())
920         style.setHasAutoZIndex();
921
922     // Auto z-index becomes 0 for the root element and transparent objects. This prevents
923     // cases where objects that should be blended as a single unit end up with a non-transparent
924     // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
925     if (style.hasAutoZIndex()) {
926         if ((element && element->document().documentElement() == element)
927             || style.opacity() < 1.0f
928             || style.hasTransformRelatedProperty()
929             || style.hasMask()
930             || style.clipPath()
931             || style.boxReflect()
932             || style.hasFilter()
933 #if ENABLE(FILTERS_LEVEL_2)
934             || style.hasBackdropFilter()
935 #endif
936             || style.hasBlendMode()
937             || style.hasIsolation()
938             || style.position() == StickyPosition
939             || (style.position() == FixedPosition && documentSettings() && documentSettings()->fixedPositionCreatesStackingContext())
940             || style.hasFlowFrom()
941             || style.willChangeCreatesStackingContext())
942             style.setZIndex(0);
943     }
944
945     if (element) {
946         // Textarea considers overflow visible as auto.
947         if (is<HTMLTextAreaElement>(*element)) {
948             style.setOverflowX(style.overflowX() == OVISIBLE ? OAUTO : style.overflowX());
949             style.setOverflowY(style.overflowY() == OVISIBLE ? OAUTO : style.overflowY());
950         }
951
952         // Disallow -webkit-user-modify on :pseudo and ::pseudo elements.
953         if (!element->shadowPseudoId().isNull())
954             style.setUserModify(READ_ONLY);
955
956         // For now, <marquee> requires an overflow clip to work properly.
957         if (is<HTMLMarqueeElement>(*element)) {
958             style.setOverflowX(OHIDDEN);
959             style.setOverflowY(OHIDDEN);
960         }
961     }
962
963     if (doesNotInheritTextDecoration(style, element))
964         style.setTextDecorationsInEffect(style.textDecoration());
965     else
966         style.addToTextDecorationsInEffect(style.textDecoration());
967
968     // If either overflow value is not visible, change to auto.
969     if (style.overflowX() == OVISIBLE && style.overflowY() != OVISIBLE) {
970         // FIXME: Once we implement pagination controls, overflow-x should default to hidden
971         // if overflow-y is set to -webkit-paged-x or -webkit-page-y. For now, we'll let it
972         // default to auto so we can at least scroll through the pages.
973         style.setOverflowX(OAUTO);
974     } else if (style.overflowY() == OVISIBLE && style.overflowX() != OVISIBLE)
975         style.setOverflowY(OAUTO);
976
977     // Call setStylesForPaginationMode() if a pagination mode is set for any non-root elements. If these
978     // styles are specified on a root element, then they will be incorporated in
979     // Style::createForDocument().
980     if ((style.overflowY() == OPAGEDX || style.overflowY() == OPAGEDY) && !(element && (element->hasTagName(htmlTag) || element->hasTagName(bodyTag))))
981         style.setColumnStylesFromPaginationMode(WebCore::paginationModeForRenderStyle(style));
982
983     // Table rows, sections and the table itself will support overflow:hidden and will ignore scroll/auto.
984     // FIXME: Eventually table sections will support auto and scroll.
985     if (style.display() == TABLE || style.display() == INLINE_TABLE
986         || style.display() == TABLE_ROW_GROUP || style.display() == TABLE_ROW) {
987         if (style.overflowX() != OVISIBLE && style.overflowX() != OHIDDEN)
988             style.setOverflowX(OVISIBLE);
989         if (style.overflowY() != OVISIBLE && style.overflowY() != OHIDDEN)
990             style.setOverflowY(OVISIBLE);
991     }
992
993     // Menulists should have visible overflow
994     if (style.appearance() == MenulistPart) {
995         style.setOverflowX(OVISIBLE);
996         style.setOverflowY(OVISIBLE);
997     }
998
999 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
1000     // Touch overflow scrolling creates a stacking context.
1001     if (style.hasAutoZIndex() && style.useTouchOverflowScrolling() && (isScrollableOverflow(style.overflowX()) || isScrollableOverflow(style.overflowY())))
1002         style.setZIndex(0);
1003 #endif
1004
1005     // Cull out any useless layers and also repeat patterns into additional layers.
1006     style.adjustBackgroundLayers();
1007     style.adjustMaskLayers();
1008
1009     // Do the same for animations and transitions.
1010     style.adjustAnimations();
1011     style.adjustTransitions();
1012
1013     // Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
1014     // alter fonts and heights/widths.
1015     if (is<HTMLFormControlElement>(element) && style.fontSize() >= 11) {
1016         // Don't apply intrinsic margins to image buttons. The designer knows how big the images are,
1017         // so we have to treat all image buttons as though they were explicitly sized.
1018         if (!is<HTMLInputElement>(*element) || !downcast<HTMLInputElement>(*element).isImageButton())
1019             addIntrinsicMargins(style);
1020     }
1021
1022     // Let the theme also have a crack at adjusting the style.
1023     if (style.hasAppearance())
1024         RenderTheme::defaultTheme()->adjustStyle(*this, style, element, m_state.hasUAAppearance(), m_state.borderData(), m_state.backgroundData(), m_state.backgroundColor());
1025
1026     // If we have first-letter pseudo style, do not share this style.
1027     if (style.hasPseudoStyle(FIRST_LETTER))
1028         style.setUnique();
1029
1030     // FIXME: when dropping the -webkit prefix on transform-style, we should also have opacity < 1 cause flattening.
1031     if (style.preserves3D() && (style.overflowX() != OVISIBLE
1032         || style.overflowY() != OVISIBLE
1033         || style.hasClip()
1034         || style.clipPath()
1035         || style.hasFilter()
1036 #if ENABLE(FILTERS_LEVEL_2)
1037         || style.hasBackdropFilter()
1038 #endif
1039         || style.hasBlendMode()))
1040         style.setTransformStyle3D(TransformStyle3DFlat);
1041
1042     if (is<SVGElement>(element)) {
1043         // Only the root <svg> element in an SVG document fragment tree honors css position
1044         if (!(element->hasTagName(SVGNames::svgTag) && element->parentNode() && !element->parentNode()->isSVGElement()))
1045             style.setPosition(RenderStyle::initialPosition());
1046
1047         // RenderSVGRoot handles zooming for the whole SVG subtree, so foreignObject content should
1048         // not be scaled again.
1049         if (element->hasTagName(SVGNames::foreignObjectTag))
1050             style.setEffectiveZoom(RenderStyle::initialZoom());
1051
1052         // SVG text layout code expects us to be a block-level style element.
1053         if ((element->hasTagName(SVGNames::foreignObjectTag) || element->hasTagName(SVGNames::textTag)) && style.isDisplayInlineType())
1054             style.setDisplay(BLOCK);
1055     }
1056 }
1057
1058 bool StyleResolver::checkRegionStyle(const Element* regionElement)
1059 {
1060     unsigned rulesSize = m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().size();
1061     for (unsigned i = 0; i < rulesSize; ++i) {
1062         ASSERT(m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().at(i).ruleSet.get());
1063         if (checkRegionSelector(m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().at(i).selector, regionElement))
1064             return true;
1065     }
1066
1067     if (m_ruleSets.userStyle()) {
1068         rulesSize = m_ruleSets.userStyle()->regionSelectorsAndRuleSets().size();
1069         for (unsigned i = 0; i < rulesSize; ++i) {
1070             ASSERT(m_ruleSets.userStyle()->regionSelectorsAndRuleSets().at(i).ruleSet.get());
1071             if (checkRegionSelector(m_ruleSets.userStyle()->regionSelectorsAndRuleSets().at(i).selector, regionElement))
1072                 return true;
1073         }
1074     }
1075
1076     return false;
1077 }
1078
1079 static void checkForOrientationChange(RenderStyle* style)
1080 {
1081     FontOrientation fontOrientation;
1082     NonCJKGlyphOrientation glyphOrientation;
1083     std::tie(fontOrientation, glyphOrientation) = style->fontAndGlyphOrientation();
1084
1085     const auto& fontDescription = style->fontDescription();
1086     if (fontDescription.orientation() == fontOrientation && fontDescription.nonCJKGlyphOrientation() == glyphOrientation)
1087         return;
1088
1089     auto newFontDescription = fontDescription;
1090     newFontDescription.setNonCJKGlyphOrientation(glyphOrientation);
1091     newFontDescription.setOrientation(fontOrientation);
1092     style->setFontDescription(newFontDescription);
1093 }
1094
1095 void StyleResolver::updateFont()
1096 {
1097     if (!m_state.fontDirty())
1098         return;
1099
1100     RenderStyle* style = m_state.style();
1101 #if ENABLE(IOS_TEXT_AUTOSIZING)
1102     checkForTextSizeAdjust(style);
1103 #endif
1104     checkForGenericFamilyChange(style, m_state.parentStyle());
1105     checkForZoomChange(style, m_state.parentStyle());
1106     checkForOrientationChange(style);
1107     style->fontCascade().update(&document().fontSelector());
1108     if (m_state.fontSizeHasViewportUnits())
1109         style->setHasViewportUnits(true);
1110     m_state.setFontDirty(false);
1111 }
1112
1113 Vector<RefPtr<StyleRule>> StyleResolver::styleRulesForElement(const Element* element, unsigned rulesToInclude)
1114 {
1115     return pseudoStyleRulesForElement(element, NOPSEUDO, rulesToInclude);
1116 }
1117
1118 Vector<RefPtr<StyleRule>> StyleResolver::pseudoStyleRulesForElement(const Element* element, PseudoId pseudoId, unsigned rulesToInclude)
1119 {
1120     if (!element || !element->document().haveStylesheetsLoaded())
1121         return Vector<RefPtr<StyleRule>>();
1122
1123     m_state = State(*element, nullptr);
1124
1125     ElementRuleCollector collector(*element, m_ruleSets, m_state.selectorFilter());
1126     collector.setMode(SelectorChecker::Mode::CollectingRules);
1127     collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
1128     collector.setMedium(&m_mediaQueryEvaluator);
1129
1130     if (rulesToInclude & UAAndUserCSSRules) {
1131         // First we match rules from the user agent sheet.
1132         collector.matchUARules();
1133         
1134         // Now we check user sheet rules.
1135         if (m_matchAuthorAndUserStyles)
1136             collector.matchUserRules(rulesToInclude & EmptyCSSRules);
1137     }
1138
1139     if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
1140         collector.setSameOriginOnly(!(rulesToInclude & CrossOriginCSSRules));
1141
1142         // Check the rules in author sheets.
1143         collector.matchAuthorRules(rulesToInclude & EmptyCSSRules);
1144     }
1145
1146     return collector.matchedRuleList();
1147 }
1148
1149 static bool shouldApplyPropertyInParseOrder(CSSPropertyID propertyID)
1150 {
1151     switch (propertyID) {
1152     case CSSPropertyWebkitBackgroundClip:
1153     case CSSPropertyBackgroundClip:
1154     case CSSPropertyWebkitBackgroundOrigin:
1155     case CSSPropertyBackgroundOrigin:
1156     case CSSPropertyWebkitBackgroundSize:
1157     case CSSPropertyBackgroundSize:
1158     case CSSPropertyWebkitBorderImage:
1159     case CSSPropertyBorderImage:
1160     case CSSPropertyBorderImageSlice:
1161     case CSSPropertyBorderImageSource:
1162     case CSSPropertyBorderImageOutset:
1163     case CSSPropertyBorderImageRepeat:
1164     case CSSPropertyBorderImageWidth:
1165     case CSSPropertyWebkitBoxShadow:
1166     case CSSPropertyBoxShadow:
1167     case CSSPropertyWebkitTextDecoration:
1168     case CSSPropertyWebkitTextDecorationLine:
1169     case CSSPropertyWebkitTextDecorationStyle:
1170     case CSSPropertyWebkitTextDecorationColor:
1171     case CSSPropertyWebkitTextDecorationSkip:
1172     case CSSPropertyWebkitTextUnderlinePosition:
1173     case CSSPropertyTextDecoration:
1174         return true;
1175     default:
1176         return false;
1177     }
1178 }
1179
1180 static bool elementTypeHasAppearanceFromUAStyle(const Element& element)
1181 {
1182     // NOTE: This is just a hard-coded list of elements that have some -webkit-appearance value in html.css
1183     const auto& localName = element.localName();
1184     return localName == HTMLNames::inputTag
1185         || localName == HTMLNames::textareaTag
1186         || localName == HTMLNames::buttonTag
1187         || localName == HTMLNames::progressTag
1188         || localName == HTMLNames::selectTag
1189         || localName == HTMLNames::meterTag
1190         || localName == HTMLNames::isindexTag;
1191 }
1192
1193 unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
1194 {
1195     return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
1196 }
1197
1198 bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
1199 {
1200     return a.firstUARule == b.firstUARule
1201         && a.lastUARule == b.lastUARule
1202         && a.firstAuthorRule == b.firstAuthorRule
1203         && a.lastAuthorRule == b.lastAuthorRule
1204         && a.firstUserRule == b.firstUserRule
1205         && a.lastUserRule == b.lastUserRule;
1206 }
1207
1208 bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
1209 {
1210     return !(a == b);
1211 }
1212
1213 bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
1214 {
1215     return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
1216 }
1217
1218 bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
1219 {
1220     return !(a == b);
1221 }
1222
1223 const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
1224 {
1225     ASSERT(hash);
1226
1227     MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
1228     if (it == m_matchedPropertiesCache.end())
1229         return nullptr;
1230     MatchedPropertiesCacheItem& cacheItem = it->value;
1231
1232     size_t size = matchResult.matchedProperties().size();
1233     if (size != cacheItem.matchedProperties.size())
1234         return nullptr;
1235     for (size_t i = 0; i < size; ++i) {
1236         if (matchResult.matchedProperties()[i] != cacheItem.matchedProperties[i])
1237             return nullptr;
1238     }
1239     if (cacheItem.ranges != matchResult.ranges)
1240         return nullptr;
1241     return &cacheItem;
1242 }
1243
1244 void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
1245 {
1246     static const unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
1247     if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps
1248         && !m_matchedPropertiesCacheSweepTimer.isActive()) {
1249         static const unsigned matchedDeclarationCacheSweepTimeInSeconds = 60;
1250         m_matchedPropertiesCacheSweepTimer.startOneShot(matchedDeclarationCacheSweepTimeInSeconds);
1251     }
1252
1253     ASSERT(hash);
1254     MatchedPropertiesCacheItem cacheItem;
1255     cacheItem.matchedProperties.appendVector(matchResult.matchedProperties());
1256     cacheItem.ranges = matchResult.ranges;
1257     // Note that we don't cache the original RenderStyle instance. It may be further modified.
1258     // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
1259     cacheItem.renderStyle = RenderStyle::clonePtr(*style);
1260     cacheItem.parentRenderStyle = RenderStyle::clonePtr(*parentStyle);
1261     m_matchedPropertiesCache.add(hash, WTFMove(cacheItem));
1262 }
1263
1264 void StyleResolver::invalidateMatchedPropertiesCache()
1265 {
1266     m_matchedPropertiesCache.clear();
1267 }
1268
1269 void StyleResolver::clearCachedPropertiesAffectedByViewportUnits()
1270 {
1271     Vector<unsigned, 16> toRemove;
1272     for (auto& cacheKeyValue : m_matchedPropertiesCache) {
1273         if (cacheKeyValue.value.renderStyle->hasViewportUnits())
1274             toRemove.append(cacheKeyValue.key);
1275     }
1276     for (auto key : toRemove)
1277         m_matchedPropertiesCache.remove(key);
1278 }
1279
1280 static bool isCacheableInMatchedPropertiesCache(const Element& element, const RenderStyle* style, const RenderStyle* parentStyle)
1281 {
1282     // FIXME: Writing mode and direction properties modify state when applying to document element by calling
1283     // Document::setWritingMode/DirectionSetOnDocumentElement. We can't skip the applying by caching.
1284     if (&element == element.document().documentElement())
1285         return false;
1286     // content:attr() value depends on the element it is being applied to.
1287     if (style->hasAttrContent() || (style->styleType() != NOPSEUDO && parentStyle->hasAttrContent()))
1288         return false;
1289     if (style->hasAppearance())
1290         return false;
1291     if (style->zoom() != RenderStyle::initialZoom())
1292         return false;
1293     if (style->writingMode() != RenderStyle::initialWritingMode() || style->direction() != RenderStyle::initialDirection())
1294         return false;
1295     // The cache assumes static knowledge about which properties are inherited.
1296     if (style->hasExplicitlyInheritedProperties())
1297         return false;
1298     return true;
1299 }
1300
1301 void extractDirectionAndWritingMode(const RenderStyle& style, const StyleResolver::MatchResult& matchResult, TextDirection& direction, WritingMode& writingMode)
1302 {
1303     direction = style.direction();
1304     writingMode = style.writingMode();
1305
1306     bool hadImportantWebkitWritingMode = false;
1307     bool hadImportantDirection = false;
1308
1309     for (const auto& matchedProperties : matchResult.matchedProperties()) {
1310         for (unsigned i = 0, count = matchedProperties.properties->propertyCount(); i < count; ++i) {
1311             auto property = matchedProperties.properties->propertyAt(i);
1312             if (!property.value()->isPrimitiveValue())
1313                 continue;
1314             switch (property.id()) {
1315             case CSSPropertyWebkitWritingMode:
1316                 if (!hadImportantWebkitWritingMode || property.isImportant()) {
1317                     writingMode = downcast<CSSPrimitiveValue>(*property.value());
1318                     hadImportantWebkitWritingMode = property.isImportant();
1319                 }
1320                 break;
1321             case CSSPropertyDirection:
1322                 if (!hadImportantDirection || property.isImportant()) {
1323                     direction = downcast<CSSPrimitiveValue>(*property.value());
1324                     hadImportantDirection = property.isImportant();
1325                 }
1326                 break;
1327             default:
1328                 break;
1329             }
1330         }
1331     }
1332 }
1333
1334 void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element& element, ShouldUseMatchedPropertiesCache shouldUseMatchedPropertiesCache)
1335 {
1336     State& state = m_state;
1337     unsigned cacheHash = shouldUseMatchedPropertiesCache && matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties().data(), matchResult.matchedProperties().size()) : 0;
1338     bool applyInheritedOnly = false;
1339     const MatchedPropertiesCacheItem* cacheItem = nullptr;
1340     if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))
1341         && isCacheableInMatchedPropertiesCache(element, state.style(), state.parentStyle())) {
1342         // We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
1343         // style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the 
1344         // element context. This is fast and saves memory by reusing the style data structures.
1345         state.style()->copyNonInheritedFrom(cacheItem->renderStyle.get());
1346         if (state.parentStyle()->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
1347             EInsideLink linkStatus = state.style()->insideLink();
1348             // If the cache item parent style has identical inherited properties to the current parent style then the
1349             // resulting style will be identical too. We copy the inherited properties over from the cache and are done.
1350             state.style()->inheritFrom(cacheItem->renderStyle.get());
1351
1352             // Unfortunately the link status is treated like an inherited property. We need to explicitly restore it.
1353             state.style()->setInsideLink(linkStatus);
1354             return;
1355         }
1356         applyInheritedOnly = true; 
1357     }
1358
1359     // Directional properties (*-before/after) are aliases that depend on the TextDirection and WritingMode.
1360     // These must be resolved before we can begin the property cascade.
1361     TextDirection direction;
1362     WritingMode writingMode;
1363     extractDirectionAndWritingMode(*state.style(), matchResult, direction, writingMode);
1364
1365     if (elementTypeHasAppearanceFromUAStyle(*state.element())) {
1366         // FIXME: This is such a hack.
1367         // Find out if there's a -webkit-appearance property in effect from the UA sheet.
1368         // If so, we cache the border and background styles so that RenderTheme::adjustStyle()
1369         // can look at them later to figure out if this is a styled form control or not.
1370         CascadedProperties cascade(direction, writingMode);
1371         cascade.addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1372         cascade.addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1373
1374         applyCascadedProperties(cascade, CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition, &matchResult);
1375         adjustStyleForInterCharacterRuby();
1376     
1377         // Resolve custom variables first.
1378         applyCascadedProperties(cascade, CSSPropertyCustom, CSSPropertyCustom, &matchResult);
1379
1380         // Start by applying properties that other properties may depend on.
1381         applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty, &matchResult);
1382     
1383         updateFont();
1384         applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty, &matchResult);
1385
1386         state.cacheBorderAndBackground();
1387     }
1388
1389     CascadedProperties cascade(direction, writingMode);
1390     cascade.addNormalMatches(matchResult, 0, matchResult.matchedProperties().size() - 1, applyInheritedOnly);
1391     cascade.addImportantMatches(matchResult, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
1392     cascade.addImportantMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
1393     cascade.addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
1394     
1395     // Resolve custom properties first.
1396     applyCascadedProperties(cascade, CSSPropertyCustom, CSSPropertyCustom, &matchResult);
1397
1398     applyCascadedProperties(cascade, CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition, &matchResult);
1399     
1400     // Adjust the font size to be smaller if ruby-position is inter-character.
1401     adjustStyleForInterCharacterRuby();
1402
1403     // Start by applying properties that other properties may depend on.
1404     applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty, &matchResult);
1405
1406     // If the effective zoom value changes, we can't use the matched properties cache. Start over.
1407     if (cacheItem && cacheItem->renderStyle->effectiveZoom() != state.style()->effectiveZoom())
1408         return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
1409
1410     // If our font got dirtied, update it now.
1411     updateFont();
1412
1413     // If the font changed, we can't use the matched properties cache. Start over.
1414     if (cacheItem && cacheItem->renderStyle->fontDescription() != state.style()->fontDescription())
1415         return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
1416
1417     // Apply properties that no other properties depend on.
1418     applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty, &matchResult);
1419
1420     // Finally, some properties must be applied in the order they were parsed.
1421     // There are some CSS properties that affect the same RenderStyle values,
1422     // so to preserve behavior, we queue them up during cascade and flush here.
1423     cascade.applyDeferredProperties(*this, &matchResult);
1424
1425     // Start loading resources referenced by this style.
1426     loadPendingResources();
1427     
1428     ASSERT(!state.fontDirty());
1429     
1430     if (cacheItem || !cacheHash)
1431         return;
1432     if (!isCacheableInMatchedPropertiesCache(*state.element(), state.style(), state.parentStyle()))
1433         return;
1434     addToMatchedPropertiesCache(state.style(), state.parentStyle(), cacheHash, matchResult);
1435 }
1436
1437 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, std::unique_ptr<RenderStyle> style)
1438 {
1439     m_state = State();
1440     m_state.setParentStyle(RenderStyle::clonePtr(*style));
1441     m_state.setStyle(WTFMove(style));
1442     applyPropertyToCurrentStyle(id, value);
1443 }
1444
1445 void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
1446 {
1447     if (value)
1448         applyProperty(id, value);
1449 }
1450
1451 inline bool isValidVisitedLinkProperty(CSSPropertyID id)
1452 {
1453     switch (id) {
1454     case CSSPropertyBackgroundColor:
1455     case CSSPropertyBorderLeftColor:
1456     case CSSPropertyBorderRightColor:
1457     case CSSPropertyBorderTopColor:
1458     case CSSPropertyBorderBottomColor:
1459     case CSSPropertyColor:
1460     case CSSPropertyOutlineColor:
1461     case CSSPropertyColumnRuleColor:
1462     case CSSPropertyWebkitTextDecorationColor:
1463     case CSSPropertyWebkitTextEmphasisColor:
1464     case CSSPropertyWebkitTextFillColor:
1465     case CSSPropertyWebkitTextStrokeColor:
1466     case CSSPropertyFill:
1467     case CSSPropertyStroke:
1468         return true;
1469     default:
1470         break;
1471     }
1472
1473     return false;
1474 }
1475
1476 // http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
1477 // FIXME: add incremental support for other region styling properties.
1478 inline bool StyleResolver::isValidRegionStyleProperty(CSSPropertyID id)
1479 {
1480     switch (id) {
1481     case CSSPropertyBackgroundColor:
1482     case CSSPropertyColor:
1483         return true;
1484     default:
1485         break;
1486     }
1487
1488     return false;
1489 }
1490
1491 #if ENABLE(VIDEO_TRACK)
1492 inline bool StyleResolver::isValidCueStyleProperty(CSSPropertyID id)
1493 {
1494     switch (id) {
1495     case CSSPropertyBackground:
1496     case CSSPropertyBackgroundAttachment:
1497     case CSSPropertyBackgroundClip:
1498     case CSSPropertyBackgroundColor:
1499     case CSSPropertyBackgroundImage:
1500     case CSSPropertyBackgroundOrigin:
1501     case CSSPropertyBackgroundPosition:
1502     case CSSPropertyBackgroundPositionX:
1503     case CSSPropertyBackgroundPositionY:
1504     case CSSPropertyBackgroundRepeat:
1505     case CSSPropertyBackgroundRepeatX:
1506     case CSSPropertyBackgroundRepeatY:
1507     case CSSPropertyBackgroundSize:
1508     case CSSPropertyColor:
1509     case CSSPropertyFont:
1510     case CSSPropertyFontFamily:
1511     case CSSPropertyFontSize:
1512     case CSSPropertyFontStyle:
1513     case CSSPropertyFontVariantCaps:
1514     case CSSPropertyFontWeight:
1515     case CSSPropertyLineHeight:
1516     case CSSPropertyOpacity:
1517     case CSSPropertyOutline:
1518     case CSSPropertyOutlineColor:
1519     case CSSPropertyOutlineOffset:
1520     case CSSPropertyOutlineStyle:
1521     case CSSPropertyOutlineWidth:
1522     case CSSPropertyVisibility:
1523     case CSSPropertyWhiteSpace:
1524     case CSSPropertyTextDecoration:
1525     case CSSPropertyTextShadow:
1526     case CSSPropertyBorderStyle:
1527         return true;
1528     default:
1529         break;
1530     }
1531     return false;
1532 }
1533 #endif
1534 // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
1535 // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
1536 // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
1537 // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
1538 // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
1539 // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
1540 // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
1541 // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
1542 bool StyleResolver::useSVGZoomRules()
1543 {
1544     return m_state.element() && m_state.element()->isSVGElement();
1545 }
1546
1547 // Scale with/height properties on inline SVG root.
1548 bool StyleResolver::useSVGZoomRulesForLength()
1549 {
1550     return is<SVGElement>(m_state.element()) && !(is<SVGSVGElement>(*m_state.element()) && m_state.element()->parentNode());
1551 }
1552
1553 StyleResolver::CascadedProperties* StyleResolver::cascadedPropertiesForRollback(const MatchResult& matchResult)
1554 {
1555     ASSERT(cascadeLevel() != UserAgentLevel);
1556     
1557     TextDirection direction;
1558     WritingMode writingMode;
1559     extractDirectionAndWritingMode(*state().style(), matchResult, direction, writingMode);
1560
1561     if (cascadeLevel() == AuthorLevel) {
1562         CascadedProperties* authorRollback = state().authorRollback();
1563         if (authorRollback)
1564             return authorRollback;
1565         
1566         auto newAuthorRollback(std::make_unique<CascadedProperties>(direction, writingMode));
1567         
1568         // This special rollback cascade contains UA rules and user rules but no author rules.
1569         newAuthorRollback->addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1570         newAuthorRollback->addNormalMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, false);
1571         newAuthorRollback->addImportantMatches(matchResult, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, false);
1572         newAuthorRollback->addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1573     
1574         state().setAuthorRollback(newAuthorRollback);
1575         return state().authorRollback();
1576     }
1577     
1578     if (cascadeLevel() == UserLevel) {
1579         CascadedProperties* userRollback = state().userRollback();
1580         if (userRollback)
1581             return userRollback;
1582         
1583         auto newUserRollback(std::make_unique<CascadedProperties>(direction, writingMode));
1584         
1585         // This special rollback cascade contains only UA rules.
1586         newUserRollback->addNormalMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1587         newUserRollback->addImportantMatches(matchResult, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, false);
1588     
1589         state().setUserRollback(newUserRollback);
1590         return state().userRollback();
1591     }
1592     
1593     return nullptr;
1594 }
1595
1596 void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value, SelectorChecker::LinkMatchMask linkMatchMask, const MatchResult* matchResult)
1597 {
1598     ASSERT_WITH_MESSAGE(!isShorthandCSSProperty(id), "Shorthand property id = %d wasn't expanded at parsing time", id);
1599
1600     State& state = m_state;
1601     
1602     RefPtr<CSSValue> valueToApply = value;
1603     if (value->isVariableDependentValue()) {
1604         valueToApply = resolvedVariableValue(id, *downcast<CSSVariableDependentValue>(value));
1605         if (!valueToApply) {
1606             if (CSSProperty::isInheritedProperty(id))
1607                 valueToApply = CSSValuePool::singleton().createInheritedValue();
1608             else
1609                 valueToApply = CSSValuePool::singleton().createExplicitInitialValue();
1610         }
1611     }
1612
1613     if (CSSProperty::isDirectionAwareProperty(id)) {
1614         CSSPropertyID newId = CSSProperty::resolveDirectionAwareProperty(id, state.style()->direction(), state.style()->writingMode());
1615         ASSERT(newId != id);
1616         return applyProperty(newId, valueToApply.get(), linkMatchMask, matchResult);
1617     }
1618     
1619     CSSValue* valueToCheckForInheritInitial = valueToApply.get();
1620     CSSCustomPropertyValue* customPropertyValue = nullptr;
1621     
1622     if (id == CSSPropertyCustom) {
1623         customPropertyValue = &downcast<CSSCustomPropertyValue>(*valueToApply);
1624         valueToCheckForInheritInitial = customPropertyValue->value().get();
1625     }
1626
1627     bool isInherit = state.parentStyle() && valueToCheckForInheritInitial->isInheritedValue();
1628     bool isInitial = valueToCheckForInheritInitial->isInitialValue() || (!state.parentStyle() && valueToCheckForInheritInitial->isInheritedValue());
1629     
1630     bool isUnset = valueToCheckForInheritInitial->isUnsetValue();
1631     bool isRevert = valueToCheckForInheritInitial->isRevertValue();
1632
1633     if (isRevert) {
1634         if (cascadeLevel() == UserAgentLevel || !matchResult)
1635             isUnset = true;
1636         else {
1637             // Fetch the correct rollback object from the state, building it if necessary.
1638             // This requires having the original MatchResult available.
1639             auto* rollback = cascadedPropertiesForRollback(*matchResult);
1640             ASSERT(rollback);
1641
1642             // With the cascade built, we need to obtain the property and apply it. If the property is
1643             // not present, then we behave like "unset." Otherwise we apply the property instead of
1644             // our own.
1645             if (customPropertyValue) {
1646                 if (rollback->hasCustomProperty(customPropertyValue->name())) {
1647                     auto property = rollback->customProperty(customPropertyValue->name());
1648                     if (property.cssValue[linkMatchMask])
1649                         applyProperty(property.id, property.cssValue[linkMatchMask], linkMatchMask, matchResult);
1650                     return;
1651                 }
1652             } else if (rollback->hasProperty(id)) {
1653                 auto& property = rollback->property(id);
1654                 if (property.cssValue[linkMatchMask])
1655                     applyProperty(property.id, property.cssValue[linkMatchMask], linkMatchMask, matchResult);
1656                 return;
1657             }
1658         
1659             isUnset = true;
1660         }
1661     }
1662     
1663     if (isUnset) {
1664         if (CSSProperty::isInheritedProperty(id))
1665             isInherit = true;
1666         else
1667             isInitial = true;
1668     }
1669
1670     ASSERT(!isInherit || !isInitial); // isInherit -> !isInitial && isInitial -> !isInherit
1671
1672     if (!state.applyPropertyToRegularStyle() && (!state.applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
1673         // Limit the properties that can be applied to only the ones honored by :visited.
1674         return;
1675     }
1676
1677     if (isInherit && !CSSProperty::isInheritedProperty(id))
1678         state.style()->setHasExplicitlyInheritedProperties();
1679     
1680     if (id == CSSPropertyCustom) {
1681         CSSCustomPropertyValue* customProperty = &downcast<CSSCustomPropertyValue>(*valueToApply);
1682         if (isInherit) {
1683             RefPtr<CSSValue> customVal = state.parentStyle()->getCustomPropertyValue(customProperty->name());
1684             if (!customVal)
1685                 customVal = CSSCustomPropertyValue::createInvalid();
1686             state.style()->setCustomPropertyValue(customProperty->name(), customVal);
1687         } else if (isInitial)
1688             state.style()->setCustomPropertyValue(customProperty->name(), CSSCustomPropertyValue::createInvalid());
1689         else
1690             state.style()->setCustomPropertyValue(customProperty->name(), customProperty->value());
1691         return;
1692     }
1693
1694     // Use the generated StyleBuilder.
1695     StyleBuilder::applyProperty(id, *this, *valueToApply, isInitial, isInherit);
1696 }
1697
1698 RefPtr<CSSValue> StyleResolver::resolvedVariableValue(CSSPropertyID propID, const CSSVariableDependentValue& value)
1699 {
1700     CSSParser parser(m_state.document());
1701     return parser.parseVariableDependentValue(propID, value, m_state.style()->customProperties(), m_state.style()->direction(), m_state.style()->writingMode());
1702 }
1703
1704 RefPtr<StyleImage> StyleResolver::styleImage(CSSPropertyID property, CSSValue& value)
1705 {
1706     if (is<CSSImageValue>(value))
1707         return cachedOrPendingFromValue(property, downcast<CSSImageValue>(value));
1708
1709     if (is<CSSImageGeneratorValue>(value)) {
1710         if (is<CSSGradientValue>(value))
1711             return generatedOrPendingFromValue(property, *downcast<CSSGradientValue>(value).gradientWithStylesResolved(this));
1712         return generatedOrPendingFromValue(property, downcast<CSSImageGeneratorValue>(value));
1713     }
1714
1715 #if ENABLE(CSS_IMAGE_SET)
1716     if (is<CSSImageSetValue>(value))
1717         return setOrPendingFromValue(property, downcast<CSSImageSetValue>(value));
1718 #endif
1719
1720     if (is<CSSCursorImageValue>(value))
1721         return cursorOrPendingFromValue(property, downcast<CSSCursorImageValue>(value));
1722
1723     return nullptr;
1724 }
1725
1726 Ref<StyleImage> StyleResolver::cachedOrPendingFromValue(CSSPropertyID property, CSSImageValue& value)
1727 {
1728     Ref<StyleImage> image = value.cachedOrPendingImage();
1729     if (image->isPendingImage())
1730         m_state.pendingImageProperties().set(property, &value);
1731     return image;
1732 }
1733
1734 Ref<StyleImage> StyleResolver::generatedOrPendingFromValue(CSSPropertyID property, CSSImageGeneratorValue& value)
1735 {
1736     if (is<CSSFilterImageValue>(value)) {
1737         // FilterImage needs to calculate FilterOperations.
1738         downcast<CSSFilterImageValue>(value).createFilterOperations(this);
1739     }
1740
1741     if (value.isPending()) {
1742         m_state.pendingImageProperties().set(property, &value);
1743         return StylePendingImage::create(&value);
1744     }
1745     return StyleGeneratedImage::create(value);
1746 }
1747
1748 #if ENABLE(CSS_IMAGE_SET)
1749 RefPtr<StyleImage> StyleResolver::setOrPendingFromValue(CSSPropertyID property, CSSImageSetValue& value)
1750 {
1751     RefPtr<StyleImage> image = value.cachedOrPendingImageSet(document());
1752     if (image && image->isPendingImage())
1753         m_state.pendingImageProperties().set(property, &value);
1754     return image;
1755 }
1756 #endif
1757
1758 RefPtr<StyleImage> StyleResolver::cursorOrPendingFromValue(CSSPropertyID property, CSSCursorImageValue& value)
1759 {
1760     RefPtr<StyleImage> image = value.cachedOrPendingImage(document());
1761     if (image && image->isPendingImage())
1762         m_state.pendingImageProperties().set(property, &value);
1763     return image;
1764 }
1765
1766 #if ENABLE(IOS_TEXT_AUTOSIZING)
1767 void StyleResolver::checkForTextSizeAdjust(RenderStyle* style)
1768 {
1769     if (style->textSizeAdjust().isAuto())
1770         return;
1771
1772     auto newFontDescription = style->fontDescription();
1773     if (!style->textSizeAdjust().isNone())
1774         newFontDescription.setComputedSize(newFontDescription.specifiedSize() * style->textSizeAdjust().multiplier());
1775     else
1776         newFontDescription.setComputedSize(newFontDescription.specifiedSize());
1777     style->setFontDescription(newFontDescription);
1778 }
1779 #endif
1780
1781 void StyleResolver::checkForZoomChange(RenderStyle* style, const RenderStyle* parentStyle)
1782 {
1783     if (!parentStyle)
1784         return;
1785     
1786     if (style->effectiveZoom() == parentStyle->effectiveZoom() && style->textZoom() == parentStyle->textZoom())
1787         return;
1788
1789     const auto& childFont = style->fontDescription();
1790     auto newFontDescription = childFont;
1791     setFontSize(newFontDescription, childFont.specifiedSize());
1792     style->setFontDescription(newFontDescription);
1793 }
1794
1795 void StyleResolver::checkForGenericFamilyChange(RenderStyle* style, const RenderStyle* parentStyle)
1796 {
1797     const auto& childFont = style->fontDescription();
1798
1799     if (childFont.isAbsoluteSize() || !parentStyle)
1800         return;
1801
1802     const auto& parentFont = parentStyle->fontDescription();
1803     if (childFont.useFixedDefaultSize() == parentFont.useFixedDefaultSize())
1804         return;
1805     // We know the parent is monospace or the child is monospace, and that font
1806     // size was unspecified. We want to scale our font size as appropriate.
1807     // If the font uses a keyword size, then we refetch from the table rather than
1808     // multiplying by our scale factor.
1809     float size;
1810     if (CSSValueID sizeIdentifier = childFont.keywordSizeAsIdentifier())
1811         size = Style::fontSizeForKeyword(sizeIdentifier, childFont.useFixedDefaultSize(), document());
1812     else {
1813         Settings* settings = documentSettings();
1814         float fixedScaleFactor = (settings && settings->defaultFixedFontSize() && settings->defaultFontSize())
1815             ? static_cast<float>(settings->defaultFixedFontSize()) / settings->defaultFontSize()
1816             : 1;
1817         size = parentFont.useFixedDefaultSize() ?
1818                 childFont.specifiedSize() / fixedScaleFactor :
1819                 childFont.specifiedSize() * fixedScaleFactor;
1820     }
1821
1822     auto newFontDescription = childFont;
1823     setFontSize(newFontDescription, size);
1824     style->setFontDescription(newFontDescription);
1825 }
1826
1827 void StyleResolver::initializeFontStyle(Settings* settings)
1828 {
1829     FontCascadeDescription fontDescription;
1830     if (settings)
1831         fontDescription.setRenderingMode(settings->fontRenderingMode());
1832     fontDescription.setOneFamily(standardFamily);
1833     fontDescription.setKeywordSizeFromIdentifier(CSSValueMedium);
1834     setFontSize(fontDescription, Style::fontSizeForKeyword(CSSValueMedium, false, document()));
1835     setFontDescription(fontDescription);
1836 }
1837
1838 void StyleResolver::setFontSize(FontCascadeDescription& fontDescription, float size)
1839 {
1840     fontDescription.setSpecifiedSize(size);
1841     fontDescription.setComputedSize(Style::computedFontSizeFromSpecifiedSize(size, fontDescription.isAbsoluteSize(), useSVGZoomRules(), m_state.style(), document()));
1842 }
1843
1844 static Color colorForCSSValue(CSSValueID cssValueId)
1845 {
1846     struct ColorValue {
1847         CSSValueID cssValueId;
1848         RGBA32 color;
1849     };
1850
1851     static const ColorValue colorValues[] = {
1852         { CSSValueAqua, 0xFF00FFFF },
1853         { CSSValueBlack, 0xFF000000 },
1854         { CSSValueBlue, 0xFF0000FF },
1855         { CSSValueFuchsia, 0xFFFF00FF },
1856         { CSSValueGray, 0xFF808080 },
1857         { CSSValueGreen, 0xFF008000  },
1858         { CSSValueGrey, 0xFF808080 },
1859         { CSSValueLime, 0xFF00FF00 },
1860         { CSSValueMaroon, 0xFF800000 },
1861         { CSSValueNavy, 0xFF000080 },
1862         { CSSValueOlive, 0xFF808000  },
1863         { CSSValueOrange, 0xFFFFA500 },
1864         { CSSValuePurple, 0xFF800080 },
1865         { CSSValueRed, 0xFFFF0000 },
1866         { CSSValueSilver, 0xFFC0C0C0 },
1867         { CSSValueTeal, 0xFF008080  },
1868         { CSSValueTransparent, 0x00000000 },
1869         { CSSValueWhite, 0xFFFFFFFF },
1870         { CSSValueYellow, 0xFFFFFF00 },
1871         { CSSValueInvalid, CSSValueInvalid }
1872     };
1873
1874     for (const ColorValue* col = colorValues; col->cssValueId; ++col) {
1875         if (col->cssValueId == cssValueId)
1876             return col->color;
1877     }
1878     return RenderTheme::defaultTheme()->systemColor(cssValueId);
1879 }
1880
1881 bool StyleResolver::colorFromPrimitiveValueIsDerivedFromElement(const CSSPrimitiveValue& value)
1882 {
1883     int ident = value.getValueID();
1884     switch (ident) {
1885     case CSSValueWebkitText:
1886     case CSSValueWebkitLink:
1887     case CSSValueWebkitActivelink:
1888     case CSSValueCurrentcolor:
1889         return true;
1890     default:
1891         return false;
1892     }
1893 }
1894
1895 Color StyleResolver::colorFromPrimitiveValue(const CSSPrimitiveValue& value, bool forVisitedLink) const
1896 {
1897     if (value.isRGBColor())
1898         return Color(value.getRGBA32Value());
1899
1900     const State& state = m_state;
1901     CSSValueID ident = value.getValueID();
1902     switch (ident) {
1903     case 0:
1904         return Color();
1905     case CSSValueWebkitText:
1906         return state.document().textColor();
1907     case CSSValueWebkitLink:
1908         return (state.element()->isLink() && forVisitedLink) ? state.document().visitedLinkColor() : state.document().linkColor();
1909     case CSSValueWebkitActivelink:
1910         return state.document().activeLinkColor();
1911     case CSSValueWebkitFocusRingColor:
1912         return RenderTheme::focusRingColor();
1913     case CSSValueCurrentcolor:
1914         return state.style()->color();
1915     default:
1916         return colorForCSSValue(ident);
1917     }
1918 }
1919
1920 void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExpression& expression, bool result)
1921 {
1922     m_viewportDependentMediaQueryResults.append(MediaQueryResult { expression, result });
1923 }
1924
1925 bool StyleResolver::hasMediaQueriesAffectedByViewportChange() const
1926 {
1927     for (auto& result : m_viewportDependentMediaQueryResults) {
1928         if (m_mediaQueryEvaluator.evaluate(result.expression) != result.result)
1929             return true;
1930     }
1931     return false;
1932 }
1933
1934 static FilterOperation::OperationType filterOperationForType(WebKitCSSFilterValue::FilterOperationType type)
1935 {
1936     switch (type) {
1937     case WebKitCSSFilterValue::ReferenceFilterOperation:
1938         return FilterOperation::REFERENCE;
1939     case WebKitCSSFilterValue::GrayscaleFilterOperation:
1940         return FilterOperation::GRAYSCALE;
1941     case WebKitCSSFilterValue::SepiaFilterOperation:
1942         return FilterOperation::SEPIA;
1943     case WebKitCSSFilterValue::SaturateFilterOperation:
1944         return FilterOperation::SATURATE;
1945     case WebKitCSSFilterValue::HueRotateFilterOperation:
1946         return FilterOperation::HUE_ROTATE;
1947     case WebKitCSSFilterValue::InvertFilterOperation:
1948         return FilterOperation::INVERT;
1949     case WebKitCSSFilterValue::OpacityFilterOperation:
1950         return FilterOperation::OPACITY;
1951     case WebKitCSSFilterValue::BrightnessFilterOperation:
1952         return FilterOperation::BRIGHTNESS;
1953     case WebKitCSSFilterValue::ContrastFilterOperation:
1954         return FilterOperation::CONTRAST;
1955     case WebKitCSSFilterValue::BlurFilterOperation:
1956         return FilterOperation::BLUR;
1957     case WebKitCSSFilterValue::DropShadowFilterOperation:
1958         return FilterOperation::DROP_SHADOW;
1959     case WebKitCSSFilterValue::UnknownFilterOperation:
1960         return FilterOperation::NONE;
1961     }
1962     return FilterOperation::NONE;
1963 }
1964
1965 void StyleResolver::loadPendingSVGDocuments()
1966 {
1967     State& state = m_state;
1968
1969     // Crash reports indicate that we've seen calls to this function when our
1970     // style is NULL. We don't know exactly why this happens. Our guess is
1971     // reentering styleForElement().
1972     ASSERT(state.style());
1973     if (!state.style() || !state.style()->hasFilter() || state.filtersWithPendingSVGDocuments().isEmpty())
1974         return;
1975
1976     ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
1977     options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
1978
1979     CachedResourceLoader& cachedResourceLoader = state.document().cachedResourceLoader();
1980     
1981     for (auto& filterOperation : state.filtersWithPendingSVGDocuments())
1982         filterOperation->getOrCreateCachedSVGDocumentReference()->load(cachedResourceLoader, options);
1983
1984     state.filtersWithPendingSVGDocuments().clear();
1985 }
1986
1987 bool StyleResolver::createFilterOperations(const CSSValue& inValue, FilterOperations& outOperations)
1988 {
1989     State& state = m_state;
1990     ASSERT(outOperations.isEmpty());
1991     
1992     if (is<CSSPrimitiveValue>(inValue)) {
1993         auto& primitiveValue = downcast<CSSPrimitiveValue>(inValue);
1994         if (primitiveValue.getValueID() == CSSValueNone)
1995             return true;
1996     }
1997     
1998     if (!is<CSSValueList>(inValue))
1999         return false;
2000
2001     FilterOperations operations;
2002     for (auto& currentValue : downcast<CSSValueList>(inValue)) {
2003         if (!is<WebKitCSSFilterValue>(currentValue.get()))
2004             continue;
2005
2006         auto& filterValue = downcast<WebKitCSSFilterValue>(currentValue.get());
2007         FilterOperation::OperationType operationType = filterOperationForType(filterValue.operationType());
2008
2009         if (operationType == FilterOperation::REFERENCE) {
2010             if (filterValue.length() != 1)
2011                 continue;
2012             auto& argument = *filterValue.itemWithoutBoundsCheck(0);
2013
2014             if (!is<CSSPrimitiveValue>(argument))
2015                 continue;
2016
2017             auto& primitiveValue = downcast<CSSPrimitiveValue>(argument);
2018             String cssUrl = primitiveValue.getStringValue();
2019             URL url = m_state.document().completeURL(cssUrl);
2020
2021             RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(cssUrl, url.fragmentIdentifier());
2022             if (SVGURIReference::isExternalURIReference(cssUrl, m_state.document()))
2023                 state.filtersWithPendingSVGDocuments().append(operation);
2024
2025             operations.operations().append(operation);
2026             continue;
2027         }
2028
2029         // Check that all parameters are primitive values, with the
2030         // exception of drop shadow which has a CSSShadowValue parameter.
2031         const CSSPrimitiveValue* firstValue = nullptr;
2032         if (operationType != FilterOperation::DROP_SHADOW) {
2033             bool haveNonPrimitiveValue = false;
2034             for (unsigned j = 0; j < filterValue.length(); ++j) {
2035                 if (!is<CSSPrimitiveValue>(*filterValue.itemWithoutBoundsCheck(j))) {
2036                     haveNonPrimitiveValue = true;
2037                     break;
2038                 }
2039             }
2040             if (haveNonPrimitiveValue)
2041                 continue;
2042             if (filterValue.length())
2043                 firstValue = downcast<CSSPrimitiveValue>(filterValue.itemWithoutBoundsCheck(0));
2044         }
2045
2046         switch (filterValue.operationType()) {
2047         case WebKitCSSFilterValue::GrayscaleFilterOperation:
2048         case WebKitCSSFilterValue::SepiaFilterOperation:
2049         case WebKitCSSFilterValue::SaturateFilterOperation: {
2050             double amount = 1;
2051             if (filterValue.length() == 1) {
2052                 amount = firstValue->getDoubleValue();
2053                 if (firstValue->isPercentage())
2054                     amount /= 100;
2055             }
2056
2057             operations.operations().append(BasicColorMatrixFilterOperation::create(amount, operationType));
2058             break;
2059         }
2060         case WebKitCSSFilterValue::HueRotateFilterOperation: {
2061             double angle = 0;
2062             if (filterValue.length() == 1)
2063                 angle = firstValue->computeDegrees();
2064
2065             operations.operations().append(BasicColorMatrixFilterOperation::create(angle, operationType));
2066             break;
2067         }
2068         case WebKitCSSFilterValue::InvertFilterOperation:
2069         case WebKitCSSFilterValue::BrightnessFilterOperation:
2070         case WebKitCSSFilterValue::ContrastFilterOperation:
2071         case WebKitCSSFilterValue::OpacityFilterOperation: {
2072             double amount = (filterValue.operationType() == WebKitCSSFilterValue::BrightnessFilterOperation) ? 0 : 1;
2073             if (filterValue.length() == 1) {
2074                 amount = firstValue->getDoubleValue();
2075                 if (firstValue->isPercentage())
2076                     amount /= 100;
2077             }
2078
2079             operations.operations().append(BasicComponentTransferFilterOperation::create(amount, operationType));
2080             break;
2081         }
2082         case WebKitCSSFilterValue::BlurFilterOperation: {
2083             Length stdDeviation = Length(0, Fixed);
2084             if (filterValue.length() >= 1)
2085                 stdDeviation = convertToFloatLength(firstValue, state.cssToLengthConversionData());
2086             if (stdDeviation.isUndefined())
2087                 return false;
2088
2089             operations.operations().append(BlurFilterOperation::create(stdDeviation));
2090             break;
2091         }
2092         case WebKitCSSFilterValue::DropShadowFilterOperation: {
2093             if (filterValue.length() != 1)
2094                 return false;
2095
2096             auto& cssValue = *filterValue.itemWithoutBoundsCheck(0);
2097             if (!is<CSSShadowValue>(cssValue))
2098                 continue;
2099
2100             auto& item = downcast<CSSShadowValue>(cssValue);
2101             int x = item.x->computeLength<int>(state.cssToLengthConversionData());
2102             int y = item.y->computeLength<int>(state.cssToLengthConversionData());
2103             IntPoint location(x, y);
2104             int blur = item.blur ? item.blur->computeLength<int>(state.cssToLengthConversionData()) : 0;
2105             Color color;
2106             if (item.color)
2107                 color = colorFromPrimitiveValue(*item.color);
2108
2109             operations.operations().append(DropShadowFilterOperation::create(location, blur, color.isValid() ? color : Color::transparent));
2110             break;
2111         }
2112         case WebKitCSSFilterValue::UnknownFilterOperation:
2113         default:
2114             ASSERT_NOT_REACHED();
2115             break;
2116         }
2117     }
2118
2119     outOperations = operations;
2120     return true;
2121 }
2122
2123 RefPtr<StyleImage> StyleResolver::loadPendingImage(const StylePendingImage& pendingImage, const ResourceLoaderOptions& options)
2124 {
2125     if (auto imageValue = pendingImage.cssImageValue())
2126         return imageValue->cachedImage(m_state.document().cachedResourceLoader(), options);
2127
2128     if (auto imageGeneratorValue = pendingImage.cssImageGeneratorValue()) {
2129         imageGeneratorValue->loadSubimages(m_state.document().cachedResourceLoader(), options);
2130         return StyleGeneratedImage::create(*imageGeneratorValue);
2131     }
2132
2133     if (auto cursorImageValue = pendingImage.cssCursorImageValue())
2134         return cursorImageValue->cachedImage(m_state.document().cachedResourceLoader(), options);
2135
2136 #if ENABLE(CSS_IMAGE_SET)
2137     if (auto imageSetValue = pendingImage.cssImageSetValue())
2138         return imageSetValue->cachedImageSet(m_state.document().cachedResourceLoader(), options);
2139 #endif
2140
2141     return nullptr;
2142 }
2143
2144 RefPtr<StyleImage> StyleResolver::loadPendingImage(const StylePendingImage& pendingImage)
2145 {
2146     ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
2147     options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
2148     return loadPendingImage(pendingImage, options);
2149 }
2150
2151 #if ENABLE(CSS_SHAPES)
2152 void StyleResolver::loadPendingShapeImage(ShapeValue* shapeValue)
2153 {
2154     if (!shapeValue)
2155         return;
2156
2157     StyleImage* image = shapeValue->image();
2158     if (!is<StylePendingImage>(image))
2159         return;
2160
2161     auto& pendingImage = downcast<StylePendingImage>(*image);
2162
2163     ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
2164     options.setRequestOriginPolicy(PotentiallyCrossOriginEnabled);
2165     options.setAllowCredentials(DoNotAllowStoredCredentials);
2166     options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
2167
2168     shapeValue->setImage(loadPendingImage(pendingImage, options));
2169 }
2170 #endif
2171
2172 void StyleResolver::loadPendingImages()
2173 {
2174     RELEASE_ASSERT(!m_inLoadPendingImages);
2175     TemporaryChange<bool> changeInLoadPendingImages(m_inLoadPendingImages, true);
2176
2177     if (m_state.pendingImageProperties().isEmpty())
2178         return;
2179
2180     auto end = m_state.pendingImageProperties().end().keys();
2181     for (auto it = m_state.pendingImageProperties().begin().keys(); it != end; ++it) {
2182         CSSPropertyID currentProperty = *it;
2183
2184         switch (currentProperty) {
2185         case CSSPropertyBackgroundImage: {
2186             for (FillLayer* backgroundLayer = &m_state.style()->ensureBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
2187                 auto* styleImage = backgroundLayer->image();
2188                 if (is<StylePendingImage>(styleImage))
2189                     backgroundLayer->setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2190             }
2191             break;
2192         }
2193         case CSSPropertyContent: {
2194             for (ContentData* contentData = const_cast<ContentData*>(m_state.style()->contentData()); contentData; contentData = contentData->next()) {
2195                 if (is<ImageContentData>(*contentData)) {
2196                     auto& styleImage = downcast<ImageContentData>(*contentData).image();
2197                     if (is<StylePendingImage>(styleImage)) {
2198                         if (RefPtr<StyleImage> loadedImage = loadPendingImage(downcast<StylePendingImage>(styleImage)))
2199                             downcast<ImageContentData>(*contentData).setImage(loadedImage.release());
2200                     }
2201                 }
2202             }
2203             break;
2204         }
2205         case CSSPropertyCursor: {
2206             if (CursorList* cursorList = m_state.style()->cursors()) {
2207                 for (size_t i = 0; i < cursorList->size(); ++i) {
2208                     CursorData& currentCursor = cursorList->at(i);
2209                     auto* styleImage = currentCursor.image();
2210                     if (is<StylePendingImage>(styleImage))
2211                         currentCursor.setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2212                 }
2213             }
2214             break;
2215         }
2216         case CSSPropertyListStyleImage: {
2217             auto* styleImage = m_state.style()->listStyleImage();
2218             if (is<StylePendingImage>(styleImage))
2219                 m_state.style()->setListStyleImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2220             break;
2221         }
2222         case CSSPropertyBorderImageSource: {
2223             auto* styleImage = m_state.style()->borderImageSource();
2224             if (is<StylePendingImage>(styleImage))
2225                 m_state.style()->setBorderImageSource(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2226             break;
2227         }
2228         case CSSPropertyWebkitBoxReflect: {
2229             if (StyleReflection* reflection = m_state.style()->boxReflect()) {
2230                 const NinePieceImage& maskImage = reflection->mask();
2231                 auto* styleImage = maskImage.image();
2232                 if (is<StylePendingImage>(styleImage)) {
2233                     RefPtr<StyleImage> loadedImage = loadPendingImage(downcast<StylePendingImage>(*styleImage));
2234                     reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
2235                 }
2236             }
2237             break;
2238         }
2239         case CSSPropertyWebkitMaskBoxImageSource: {
2240             auto* styleImage = m_state.style()->maskBoxImageSource();
2241             if (is<StylePendingImage>(styleImage))
2242                 m_state.style()->setMaskBoxImageSource(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2243             break;
2244         }
2245         case CSSPropertyWebkitMaskImage: {
2246             for (FillLayer* maskLayer = &m_state.style()->ensureMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
2247                 auto* styleImage = maskLayer->image();
2248                 if (is<StylePendingImage>(styleImage))
2249                     maskLayer->setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
2250             }
2251             break;
2252         }
2253 #if ENABLE(CSS_SHAPES)
2254         case CSSPropertyWebkitShapeOutside:
2255             loadPendingShapeImage(m_state.style()->shapeOutside());
2256             break;
2257 #endif
2258         default:
2259             ASSERT_NOT_REACHED();
2260         }
2261     }
2262
2263     m_state.pendingImageProperties().clear();
2264 }
2265
2266 #ifndef NDEBUG
2267 static bool inLoadPendingResources = false;
2268 #endif
2269
2270 void StyleResolver::loadPendingResources()
2271 {
2272     // We've seen crashes in all three of the functions below. Some of them
2273     // indicate that style() is NULL. This NULL check will cut down on total
2274     // crashes, while the ASSERT will help us find the cause in debug builds.
2275     ASSERT(style());
2276     if (!style())
2277         return;
2278
2279 #ifndef NDEBUG
2280     // Re-entering this function will probably mean trouble. Catch it in debug builds.
2281     ASSERT(!inLoadPendingResources);
2282     inLoadPendingResources = true;
2283 #endif
2284
2285     // Start loading images referenced by this style.
2286     loadPendingImages();
2287
2288     // Start loading the SVG Documents referenced by this style.
2289     loadPendingSVGDocuments();
2290
2291 #ifndef NDEBUG
2292     inLoadPendingResources = false;
2293 #endif
2294 }
2295
2296 inline StyleResolver::MatchedProperties::MatchedProperties()
2297     : possiblyPaddedMember(nullptr)
2298 {
2299 }
2300
2301 StyleResolver::MatchedProperties::~MatchedProperties()
2302 {
2303 }
2304
2305 StyleResolver::CascadedProperties::CascadedProperties(TextDirection direction, WritingMode writingMode)
2306     : m_direction(direction)
2307     , m_writingMode(writingMode)
2308 {
2309 }
2310
2311 inline bool StyleResolver::CascadedProperties::hasProperty(CSSPropertyID id) const
2312 {
2313     ASSERT(id < m_propertyIsPresent.size());
2314     return m_propertyIsPresent[id];
2315 }
2316
2317 inline StyleResolver::CascadedProperties::Property& StyleResolver::CascadedProperties::property(CSSPropertyID id)
2318 {
2319     return m_properties[id];
2320 }
2321
2322 inline bool StyleResolver::CascadedProperties::hasCustomProperty(const String& name) const
2323 {
2324     return m_customProperties.contains(name);
2325 }
2326
2327 inline StyleResolver::CascadedProperties::Property StyleResolver::CascadedProperties::customProperty(const String& name) const
2328 {
2329     return m_customProperties.get(name);
2330 }
2331
2332 void StyleResolver::CascadedProperties::setPropertyInternal(Property& property, CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel)
2333 {
2334     ASSERT(linkMatchType <= SelectorChecker::MatchAll);
2335     property.id = id;
2336     property.level = cascadeLevel;
2337     if (linkMatchType == SelectorChecker::MatchAll) {
2338         property.cssValue[0] = &cssValue;
2339         property.cssValue[SelectorChecker::MatchLink] = &cssValue;
2340         property.cssValue[SelectorChecker::MatchVisited] = &cssValue;
2341     } else
2342         property.cssValue[linkMatchType] = &cssValue;
2343 }
2344
2345 void StyleResolver::CascadedProperties::set(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel)
2346 {
2347     if (CSSProperty::isDirectionAwareProperty(id))
2348         id = CSSProperty::resolveDirectionAwareProperty(id, m_direction, m_writingMode);
2349
2350     ASSERT(!shouldApplyPropertyInParseOrder(id));
2351
2352     auto& property = m_properties[id];
2353     ASSERT(id < m_propertyIsPresent.size());
2354     if (id == CSSPropertyCustom) {
2355         m_propertyIsPresent.set(id);
2356         const auto& customValue = downcast<CSSCustomPropertyValue>(cssValue);
2357         bool hasValue = customProperties().contains(customValue.name());
2358         if (!hasValue) {
2359             Property property;
2360             property.id = id;
2361             memset(property.cssValue, 0, sizeof(property.cssValue));
2362             setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel);
2363             customProperties().set(customValue.name(), property);
2364         } else {
2365             Property property = customProperties().get(customValue.name());
2366             setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel);
2367             customProperties().set(customValue.name(), property);
2368         }
2369         return;
2370     }
2371     
2372     if (!m_propertyIsPresent[id])
2373         memset(property.cssValue, 0, sizeof(property.cssValue));
2374     m_propertyIsPresent.set(id);
2375     setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel);
2376 }
2377
2378 void StyleResolver::CascadedProperties::setDeferred(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType, CascadeLevel cascadeLevel)
2379 {
2380     ASSERT(!CSSProperty::isDirectionAwareProperty(id));
2381     ASSERT(shouldApplyPropertyInParseOrder(id));
2382
2383     Property property;
2384     memset(property.cssValue, 0, sizeof(property.cssValue));
2385     setPropertyInternal(property, id, cssValue, linkMatchType, cascadeLevel);
2386     m_deferredProperties.append(property);
2387 }
2388
2389 void StyleResolver::CascadedProperties::addStyleProperties(const StyleProperties& properties, StyleRule&, bool isImportant, bool inheritedOnly, PropertyWhitelistType propertyWhitelistType, unsigned linkMatchType, CascadeLevel cascadeLevel)
2390 {
2391     for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
2392         auto current = properties.propertyAt(i);
2393         if (isImportant != current.isImportant())
2394             continue;
2395         if (inheritedOnly && !current.isInherited()) {
2396             // We apply the inherited properties only when using the property cache.
2397             // A match with a value that is explicitely inherited should never have been cached.
2398             ASSERT(!current.value()->isInheritedValue());
2399             continue;
2400         }
2401         CSSPropertyID propertyID = current.id();
2402
2403         if (propertyWhitelistType == PropertyWhitelistRegion && !StyleResolver::isValidRegionStyleProperty(propertyID))
2404             continue;
2405 #if ENABLE(VIDEO_TRACK)
2406         if (propertyWhitelistType == PropertyWhitelistCue && !StyleResolver::isValidCueStyleProperty(propertyID))
2407             continue;
2408 #endif
2409
2410         if (shouldApplyPropertyInParseOrder(propertyID))
2411             setDeferred(propertyID, *current.value(), linkMatchType, cascadeLevel);
2412         else
2413             set(propertyID, *current.value(), linkMatchType, cascadeLevel);
2414     }
2415 }
2416
2417 static CascadeLevel cascadeLevelForIndex(const StyleResolver::MatchResult& matchResult, int index)
2418 {
2419     if (index >= matchResult.ranges.firstUARule && index <= matchResult.ranges.lastUARule)
2420         return UserAgentLevel;
2421     if (index >= matchResult.ranges.firstUserRule && index <= matchResult.ranges.lastUserRule)
2422         return UserLevel;
2423     return AuthorLevel;
2424 }
2425
2426 void StyleResolver::CascadedProperties::addMatch(const MatchResult& matchResult, unsigned index, bool isImportant, bool inheritedOnly)
2427 {
2428     const MatchedProperties& matchedProperties = matchResult.matchedProperties()[index];
2429
2430     auto propertyWhitelistType = static_cast<PropertyWhitelistType>(matchedProperties.whitelistType);
2431     auto cascadeLevel = cascadeLevelForIndex(matchResult, index);
2432
2433     addStyleProperties(*matchedProperties.properties, *matchResult.matchedRules[index], isImportant, inheritedOnly, propertyWhitelistType, matchedProperties.linkMatchType, cascadeLevel);
2434 }
2435
2436 void StyleResolver::CascadedProperties::addNormalMatches(const MatchResult& matchResult, int startIndex, int endIndex, bool inheritedOnly)
2437 {
2438     if (startIndex == -1)
2439         return;
2440
2441     for (int i = startIndex; i <= endIndex; ++i)
2442         addMatch(matchResult, i, false, inheritedOnly);
2443 }
2444
2445 static bool hasImportantProperties(const StyleProperties& properties)
2446 {
2447     for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
2448         if (properties.propertyAt(i).isImportant())
2449             return true;
2450     }
2451     return false;
2452 }
2453
2454 void StyleResolver::CascadedProperties::addImportantMatches(const MatchResult& matchResult, int startIndex, int endIndex, bool inheritedOnly)
2455 {
2456     if (startIndex == -1)
2457         return;
2458
2459     struct IndexAndOrdinal {
2460         int index;
2461         unsigned ordinal;
2462     };
2463     Vector<IndexAndOrdinal> shadowTreeMatches;
2464
2465     for (int i = startIndex; i <= endIndex; ++i) {
2466         const MatchedProperties& matchedProperties = matchResult.matchedProperties()[i];
2467
2468         if (!hasImportantProperties(*matchedProperties.properties))
2469             continue;
2470
2471         if (matchedProperties.treeContextOrdinal) {
2472             shadowTreeMatches.append({ i, matchedProperties.treeContextOrdinal });
2473             continue;
2474         }
2475
2476         addMatch(matchResult, i, true, inheritedOnly);
2477     }
2478
2479     if (shadowTreeMatches.isEmpty())
2480         return;
2481
2482     // For !important properties a later shadow tree wins.
2483     // Match results are sorted in reverse tree context order so this is not needed for normal properties.
2484     std::stable_sort(shadowTreeMatches.begin(), shadowTreeMatches.end(), [] (const IndexAndOrdinal& a, const IndexAndOrdinal& b) {
2485         return a.ordinal < b.ordinal;
2486     });
2487
2488     for (auto& match : shadowTreeMatches)
2489         addMatch(matchResult, match.index, true, inheritedOnly);
2490 }
2491
2492 void StyleResolver::CascadedProperties::applyDeferredProperties(StyleResolver& resolver, const MatchResult* matchResult)
2493 {
2494     for (auto& property : m_deferredProperties)
2495         property.apply(resolver, matchResult);
2496 }
2497
2498 void StyleResolver::CascadedProperties::Property::apply(StyleResolver& resolver, const MatchResult* matchResult)
2499 {
2500     State& state = resolver.state();
2501     state.setCascadeLevel(level);
2502
2503     if (cssValue[SelectorChecker::MatchDefault]) {
2504         state.setApplyPropertyToRegularStyle(true);
2505         state.setApplyPropertyToVisitedLinkStyle(false);
2506         resolver.applyProperty(id, cssValue[SelectorChecker::MatchDefault], SelectorChecker::MatchDefault, matchResult);
2507     }
2508
2509     if (state.style()->insideLink() == NotInsideLink)
2510         return;
2511
2512     if (cssValue[SelectorChecker::MatchLink]) {
2513         state.setApplyPropertyToRegularStyle(true);
2514         state.setApplyPropertyToVisitedLinkStyle(false);
2515         resolver.applyProperty(id, cssValue[SelectorChecker::MatchLink], SelectorChecker::MatchLink, matchResult);
2516     }
2517
2518     if (cssValue[SelectorChecker::MatchVisited]) {
2519         state.setApplyPropertyToRegularStyle(false);
2520         state.setApplyPropertyToVisitedLinkStyle(true);
2521         resolver.applyProperty(id, cssValue[SelectorChecker::MatchVisited], SelectorChecker::MatchVisited, matchResult);
2522     }
2523
2524     state.setApplyPropertyToRegularStyle(true);
2525     state.setApplyPropertyToVisitedLinkStyle(false);
2526 }
2527
2528 void StyleResolver::applyCascadedProperties(CascadedProperties& cascade, int firstProperty, int lastProperty, const MatchResult* matchResult)
2529 {
2530     for (int id = firstProperty; id <= lastProperty; ++id) {
2531         CSSPropertyID propertyID = static_cast<CSSPropertyID>(id);
2532         if (!cascade.hasProperty(propertyID))
2533             continue;
2534         if (propertyID == CSSPropertyCustom) {
2535             HashMap<AtomicString, CascadedProperties::Property>::iterator end = cascade.customProperties().end();
2536             for (HashMap<AtomicString, CascadedProperties::Property>::iterator it = cascade.customProperties().begin(); it != end; ++it)
2537                 it->value.apply(*this, matchResult);
2538             continue;
2539         }
2540         auto& property = cascade.property(propertyID);
2541         ASSERT(!shouldApplyPropertyInParseOrder(propertyID));
2542         property.apply(*this, matchResult);
2543     }
2544     
2545     if (firstProperty == CSSPropertyCustom)
2546         m_state.style()->checkVariablesInCustomProperties();
2547 }
2548
2549 } // namespace WebCore