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