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