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