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