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