#include "config.h"
#include "StyleResolver.h"
#include "CSSBorderImage.h"
#include "CSSCalculationValue.h"
#include "CSSCursorImageValue.h"
#include "CSSDefaultStyleSheets.h"
#include "CSSFilterImageValue.h"
#include "CSSFontFaceRule.h"
#include "CSSFontFeatureValue.h"
#include "CSSFontSelector.h"
#include "CSSFontValue.h"
#include "CSSFunctionValue.h"
#include "CSSKeyframeRule.h"
#include "CSSKeyframesRule.h"
#include "CSSLineBoxContainValue.h"
#include "CSSPageRule.h"
#include "CSSParser.h"
#include "CSSPrimitiveValueMappings.h"
#include "CSSPropertyNames.h"
#include "CSSReflectValue.h"
#include "CSSSelector.h"
#include "CSSSelectorList.h"
#include "CSSShadowValue.h"
#include "CSSStyleRule.h"
#include "CSSSupportsRule.h"
#include "CSSTimingFunctionValue.h"
#include "CSSValueList.h"
#include "CachedImage.h"
#include "CachedResourceLoader.h"
#include "CachedSVGDocument.h"
#include "CachedSVGDocumentReference.h"
#include "CalculationValue.h"
#include "ContentData.h"
#include "Counter.h"
#include "CounterContent.h"
#include "CursorList.h"
#include "DocumentStyleSheetCollection.h"
#include "ElementRuleCollector.h"
#include "FilterOperation.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "FrameView.h"
#include "HTMLDocument.h"
#include "HTMLIFrameElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLOptGroupElement.h"
#include "HTMLOptionElement.h"
#include "HTMLProgressElement.h"
#include "HTMLStyleElement.h"
#include "HTMLTableElement.h"
#include "HTMLTextAreaElement.h"
#include "InsertionPoint.h"
#include "InspectorInstrumentation.h"
#include "KeyframeList.h"
#include "LinkHash.h"
#include "LocaleToScriptMapping.h"
#include "MathMLNames.h"
#include "MediaList.h"
#include "MediaQueryEvaluator.h"
#include "NodeRenderStyle.h"
#include "Page.h"
#include "PageRuleCollector.h"
#include "Pair.h"
#include "PseudoElement.h"
#include "QuotesData.h"
#include "Rect.h"
#include "RenderGrid.h"
#include "RenderRegion.h"
#include "RenderScrollbar.h"
#include "RenderScrollbarTheme.h"
#include "RenderStyleConstants.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "RuleSet.h"
#include "SVGDocument.h"
#include "SVGDocumentExtensions.h"
#include "SVGFontFaceElement.h"
#include "SVGNames.h"
#include "SVGSVGElement.h"
#include "SVGURIReference.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "ShadowData.h"
#include "ShadowRoot.h"
#include "StyleBuilder.h"
#include "StyleCachedImage.h"
#include "StyleFontSizeFunctions.h"
#include "StyleGeneratedImage.h"
#include "StylePendingImage.h"
#include "StyleProperties.h"
#include "StylePropertyShorthand.h"
#include "StyleRule.h"
#include "StyleRuleImport.h"
#include "StyleScrollSnapPoints.h"
#include "StyleSheetContents.h"
#include "StyleSheetList.h"
#include "Text.h"
#include "TransformFunctions.h"
#include "TransformOperations.h"
#include "UserAgentStyleSheets.h"
#include "ViewportStyleResolver.h"
#include "VisitedLinkState.h"
#include "WebKitCSSFilterValue.h"
#include "WebKitCSSRegionRule.h"
#include "WebKitCSSTransformValue.h"
#include "WebKitFontFamilyNames.h"
#include "XMLNames.h"
#include <bitset>
#include <wtf/StdLibExtras.h>
#include <wtf/TemporaryChange.h>
#include <wtf/Vector.h>
#if ENABLE(CSS_GRID_LAYOUT)
#include "CSSGridLineNamesValue.h"
#include "CSSGridTemplateAreasValue.h"
#endif
#if ENABLE(CSS_IMAGE_SET)
#include "CSSImageSetValue.h"
#include "StyleCachedImageSet.h"
#endif
#if ENABLE(DASHBOARD_SUPPORT)
#include "DashboardRegion.h"
#endif
#if ENABLE(VIDEO_TRACK)
#include "WebVTTElement.h"
#endif
#if ENABLE(CSS_SCROLL_SNAP)
#include "LengthRepeat.h"
#endif
namespace WebCore {
using namespace HTMLNames;
static const CSSPropertyID lastHighPriorityProperty = CSSPropertyFontSynthesis;
static const CSSPropertyID firstLowPriorityProperty = static_cast<CSSPropertyID>(lastHighPriorityProperty + 1);
class StyleResolver::CascadedProperties {
public:
CascadedProperties(TextDirection, WritingMode);
struct Property {
void apply(StyleResolver&);
CSSPropertyID id;
CSSValue* cssValue[3];
};
bool hasProperty(CSSPropertyID id) const;
Property& property(CSSPropertyID);
void addMatches(const MatchResult&, bool important, int startIndex, int endIndex, bool inheritedOnly = false);
void set(CSSPropertyID, CSSValue&, unsigned linkMatchType);
void setDeferred(CSSPropertyID, CSSValue&, unsigned linkMatchType);
void applyDeferredProperties(StyleResolver&);
private:
void addStyleProperties(const StyleProperties&, StyleRule&, bool isImportant, bool inheritedOnly, PropertyWhitelistType, unsigned linkMatchType);
static void setPropertyInternal(Property&, CSSPropertyID, CSSValue&, unsigned linkMatchType);
Property m_properties[numCSSProperties + 1];
std::bitset<numCSSProperties + 1> m_propertyIsPresent;
Vector<Property, 8> m_deferredProperties;
TextDirection m_direction;
WritingMode m_writingMode;
};
static void extractDirectionAndWritingMode(const RenderStyle&, const StyleResolver::MatchResult&, TextDirection&, WritingMode&);
#define HANDLE_INHERIT(prop, Prop) \
if (isInherit) { \
m_state.style()->set##Prop(m_state.parentStyle()->prop()); \
return; \
}
#define HANDLE_INHERIT_AND_INITIAL(prop, Prop) \
HANDLE_INHERIT(prop, Prop) \
if (isInitial) { \
m_state.style()->set##Prop(RenderStyle::initial##Prop()); \
return; \
}
RenderStyle* StyleResolver::s_styleNotYetAvailable;
inline void StyleResolver::State::cacheBorderAndBackground()
{
m_hasUAAppearance = m_style->hasAppearance();
if (m_hasUAAppearance) {
m_borderData = m_style->border();
m_backgroundData = *m_style->backgroundLayers();
m_backgroundColor = m_style->backgroundColor();
}
}
inline void StyleResolver::State::clear()
{
m_element = nullptr;
m_styledElement = nullptr;
m_parentStyle = nullptr;
m_regionForStyling = nullptr;
m_pendingImageProperties.clear();
m_filtersWithPendingSVGDocuments.clear();
m_cssToLengthConversionData = CSSToLengthConversionData();
}
void StyleResolver::MatchResult::addMatchedProperties(const StyleProperties& properties, StyleRule* rule, unsigned linkMatchType, PropertyWhitelistType propertyWhitelistType)
{
m_matchedProperties.grow(m_matchedProperties.size() + 1);
StyleResolver::MatchedProperties& newProperties = m_matchedProperties.last();
newProperties.properties = const_cast<StyleProperties*>(&properties);
newProperties.linkMatchType = linkMatchType;
newProperties.whitelistType = propertyWhitelistType;
matchedRules.append(rule);
if (isCacheable) {
for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
StyleProperties::PropertyReference current = properties.propertyAt(i);
if (!current.isInherited()) {
const CSSValue& value = *current.value();
if (value.isInheritedValue()) {
isCacheable = false;
break;
}
if (is<CSSPrimitiveValue>(value) && downcast<CSSPrimitiveValue>(value).getValueID() == CSSValueCurrentcolor) {
isCacheable = false;
break;
}
}
}
}
}
StyleResolver::StyleResolver(Document& document, bool matchAuthorAndUserStyles)
: m_matchedPropertiesCacheAdditionsSinceLastSweep(0)
, m_matchedPropertiesCacheSweepTimer(*this, &StyleResolver::sweepMatchedPropertiesCache)
, m_document(document)
, m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
#if ENABLE(CSS_DEVICE_ADAPTATION)
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
#endif
, m_styleMap(this)
{
Element* root = m_document.documentElement();
CSSDefaultStyleSheets::initDefaultStyle(root);
FrameView* view = m_document.view();
if (view)
m_medium = std::make_unique<MediaQueryEvaluator>(view->mediaType());
else
m_medium = std::make_unique<MediaQueryEvaluator>("all");
if (root)
m_rootDefaultStyle = styleForElement(root, m_document.renderStyle(), DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = std::make_unique<MediaQueryEvaluator>(view->mediaType(), &view->frame(), m_rootDefaultStyle.get());
m_ruleSets.resetAuthorStyle();
DocumentStyleSheetCollection& styleSheetCollection = m_document.styleSheetCollection();
m_ruleSets.initUserStyle(styleSheetCollection, *m_medium, *this);
#if ENABLE(SVG_FONTS)
if (m_document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = m_document.svgExtensions()->svgFontFaceElements();
for (auto* svgFontFaceElement : svgFontFaceElements)
m_document.fontSelector().addFontFaceRule(svgFontFaceElement->fontFaceRule(), svgFontFaceElement->isInUserAgentShadowTree());
}
#endif
appendAuthorStyleSheets(0, styleSheetCollection.activeAuthorStyleSheets());
}
void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet>>& styleSheets)
{
m_ruleSets.appendAuthorStyleSheets(firstNew, styleSheets, m_medium.get(), m_inspectorCSSOMWrappers, this);
if (auto renderView = document().renderView())
renderView->style().fontCascade().update(&document().fontSelector());
#if ENABLE(CSS_DEVICE_ADAPTATION)
viewportStyleResolver()->resolve();
#endif
}
void StyleResolver::pushParentElement(Element* parent)
{
const ContainerNode* parentsParent = parent->parentOrShadowHostElement();
if (!parentsParent || m_selectorFilter.parentStackIsEmpty())
m_selectorFilter.setupParentStack(parent);
else
m_selectorFilter.pushParent(parent);
}
void StyleResolver::popParentElement(Element* parent)
{
if (m_selectorFilter.parentStackIsConsistent(parent))
m_selectorFilter.popParent();
}
void StyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
{
AtomicString s(rule->name());
m_keyframesRuleMap.set(s.impl(), rule);
}
StyleResolver::~StyleResolver()
{
RELEASE_ASSERT(!m_inLoadPendingImages);
#if ENABLE(CSS_DEVICE_ADAPTATION)
m_viewportStyleResolver->clearDocument();
#endif
}
void StyleResolver::sweepMatchedPropertiesCache()
{
Vector<unsigned, 16> toRemove;
MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.begin();
MatchedPropertiesCache::iterator end = m_matchedPropertiesCache.end();
for (; it != end; ++it) {
Vector<MatchedProperties>& matchedProperties = it->value.matchedProperties;
for (size_t i = 0; i < matchedProperties.size(); ++i) {
if (matchedProperties[i].properties->hasOneRef()) {
toRemove.append(it->key);
break;
}
}
}
for (size_t i = 0; i < toRemove.size(); ++i)
m_matchedPropertiesCache.remove(toRemove[i]);
m_matchedPropertiesCacheAdditionsSinceLastSweep = 0;
}
bool StyleResolver::classNamesAffectedByRules(const SpaceSplitString& classNames) const
{
for (unsigned i = 0; i < classNames.size(); ++i) {
if (m_ruleSets.features().classesInRules.contains(classNames[i].impl()))
return true;
}
return false;
}
inline void StyleResolver::State::updateConversionData()
{
m_cssToLengthConversionData = CSSToLengthConversionData(m_style.get(), m_rootElementStyle, m_element ? document().renderView() : nullptr);
}
inline void StyleResolver::State::initElement(Element* element)
{
m_element = element;
m_styledElement = element && is<StyledElement>(*element) ? downcast<StyledElement>(element) : nullptr;
m_elementLinkState = element ? element->document().visitedLinkState().determineLinkState(*element) : NotInsideLink;
updateConversionData();
}
inline void StyleResolver::initElement(Element* e)
{
if (m_state.element() != e) {
m_state.initElement(e);
if (e && e == e->document().documentElement()) {
e->document().setDirectionSetOnDocumentElement(false);
e->document().setWritingModeSetOnDocumentElement(false);
}
}
}
inline void StyleResolver::State::initForStyleResolve(Document& document, Element* e, RenderStyle* parentStyle, const RenderRegion* regionForStyling)
{
m_regionForStyling = regionForStyling;
if (e) {
bool resetStyleInheritance = hasShadowRootParent(*e) && downcast<ShadowRoot>(*e->parentNode()).resetStyleInheritance();
m_parentStyle = resetStyleInheritance ? nullptr : parentStyle;
} else
m_parentStyle = parentStyle;
Node* docElement = e ? e->document().documentElement() : nullptr;
RenderStyle* docStyle = document.renderStyle();
m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
m_style = nullptr;
m_pendingImageProperties.clear();
m_fontDirty = false;
updateConversionData();
}
inline void StyleResolver::State::setStyle(Ref<RenderStyle>&& style)
{
m_style = WTF::move(style);
updateConversionData();
}
static const unsigned cStyleSearchThreshold = 10;
static const unsigned cStyleSearchLevelThreshold = 10;
static inline bool parentElementPreventsSharing(const Element* parentElement)
{
if (!parentElement)
return false;
return parentElement->hasFlagsSetDuringStylingOfChildren();
}
Node* StyleResolver::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
{
if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
return nullptr;
if (!is<StyledElement>(parent))
return nullptr;
StyledElement* styledParent = downcast<StyledElement>(parent);
if (styledParent->inlineStyle())
return nullptr;
if (is<SVGElement>(*styledParent) && downcast<SVGElement>(*styledParent).animatedSMILStyleProperties())
return nullptr;
if (styledParent->hasID() && m_ruleSets.features().idsInRules.contains(styledParent->idForStyleResolution().impl()))
return nullptr;
RenderStyle* parentStyle = styledParent->renderStyle();
unsigned subcount = 0;
Node* thisCousin = styledParent;
Node* currentNode = styledParent->previousSibling();
visitedNodeCount += cStyleSearchThreshold;
while (thisCousin) {
while (currentNode) {
++subcount;
if (currentNode->renderStyle() == parentStyle && currentNode->lastChild()
&& is<Element>(*currentNode) && !parentElementPreventsSharing(downcast<Element>(currentNode))
) {
visitedNodeCount -= cStyleSearchThreshold - subcount;
return currentNode->lastChild();
}
if (subcount >= cStyleSearchThreshold)
return nullptr;
currentNode = currentNode->previousSibling();
}
currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
thisCousin = currentNode;
}
return nullptr;
}
bool StyleResolver::styleSharingCandidateMatchesRuleSet(RuleSet* ruleSet)
{
if (!ruleSet)
return false;
ElementRuleCollector collector(*m_state.element(), m_state.style(), m_ruleSets, m_selectorFilter);
return collector.hasAnyMatchingRules(ruleSet);
}
bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
{
const State& state = m_state;
HTMLInputElement* thisInputElement = element->toInputElement();
HTMLInputElement* otherInputElement = state.element()->toInputElement();
if (!thisInputElement || !otherInputElement)
return false;
if (thisInputElement->isAutoFilled() != otherInputElement->isAutoFilled())
return false;
if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
return false;
if (thisInputElement->shouldAppearIndeterminate() != otherInputElement->shouldAppearIndeterminate())
return false;
if (thisInputElement->isRequired() != otherInputElement->isRequired())
return false;
if (element->isDisabledFormControl() != state.element()->isDisabledFormControl())
return false;
if (element->isDefaultButtonForForm() != state.element()->isDefaultButtonForForm())
return false;
if (element->isInRange() != state.element()->isInRange())
return false;
if (element->isOutOfRange() != state.element()->isOutOfRange())
return false;
return true;
}
static inline bool elementHasDirectionAuto(Element* element)
{
return is<HTMLElement>(*element) && downcast<HTMLElement>(*element).hasDirectionAuto();
}
bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement* sharingCandidate) const
{
const State& state = m_state;
if (state.element()->elementData() == sharingCandidate->elementData())
return true;
if (state.element()->fastGetAttribute(XMLNames::langAttr) != sharingCandidate->fastGetAttribute(XMLNames::langAttr))
return false;
if (state.element()->fastGetAttribute(langAttr) != sharingCandidate->fastGetAttribute(langAttr))
return false;
if (!state.elementAffectedByClassRules()) {
if (sharingCandidate->hasClass() && classNamesAffectedByRules(sharingCandidate->classNames()))
return false;
} else if (sharingCandidate->hasClass()) {
if (state.element()->isSVGElement()) {
if (state.element()->getAttribute(classAttr) != sharingCandidate->getAttribute(classAttr))
return false;
} else {
if (state.element()->classNames() != sharingCandidate->classNames())
return false;
}
} else
return false;
if (state.styledElement()->presentationAttributeStyle() != sharingCandidate->presentationAttributeStyle())
return false;
if (state.element()->hasTagName(progressTag)) {
if (state.element()->shouldAppearIndeterminate() != sharingCandidate->shouldAppearIndeterminate())
return false;
}
return true;
}
bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
{
RenderStyle* style = element->renderStyle();
const State& state = m_state;
if (!style)
return false;
if (style->unique())
return false;
if (style->hasUniquePseudoStyle())
return false;
if (element->tagQName() != state.element()->tagQName())
return false;
if (element->inlineStyle())
return false;
if (element->needsStyleRecalc())
return false;
if (element->isSVGElement() && downcast<SVGElement>(*element).animatedSMILStyleProperties())
return false;
if (element->isLink() != state.element()->isLink())
return false;
if (element->hovered() != state.element()->hovered())
return false;
if (element->active() != state.element()->active())
return false;
if (element->focused() != state.element()->focused())
return false;
if (element->shadowPseudoId() != state.element()->shadowPseudoId())
return false;
if (element == element->document().cssTarget())
return false;
if (!sharingCandidateHasIdenticalStyleAffectingAttributes(element))
return false;
if (element->additionalPresentationAttributeStyle() != state.styledElement()->additionalPresentationAttributeStyle())
return false;
if (element->affectsNextSiblingElementStyle() || element->styleIsAffectedByPreviousSibling())
return false;
if (element->hasID() && m_ruleSets.features().idsInRules.contains(element->idForStyleResolution().impl()))
return false;
bool isControl = is<HTMLFormControlElement>(*element);
if (isControl != is<HTMLFormControlElement>(*state.element()))
return false;
if (isControl && !canShareStyleWithControl(element))
return false;
if (style->transitions() || style->animations())
return false;
if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag) || element->hasTagName(canvasTag))
return false;
if (elementHasDirectionAuto(element))
return false;
if (element->isLink() && state.elementLinkState() != style->insideLink())
return false;
if (element->elementData() != state.element()->elementData()) {
if (element->fastGetAttribute(readonlyAttr) != state.element()->fastGetAttribute(readonlyAttr))
return false;
if (element->isSVGElement()) {
if (element->getAttribute(typeAttr) != state.element()->getAttribute(typeAttr))
return false;
} else {
if (element->fastGetAttribute(typeAttr) != state.element()->fastGetAttribute(typeAttr))
return false;
}
}
if (element->matchesValidPseudoClass() != state.element()->matchesValidPseudoClass())
return false;
if (element->matchesInvalidPseudoClass() != state.element()->matchesValidPseudoClass())
return false;
#if ENABLE(VIDEO_TRACK)
if (is<WebVTTElement>(*state.element()))
return false;
#endif
#if ENABLE(FULLSCREEN_API)
if (element == element->document().webkitCurrentFullScreenElement() || state.element() == state.document().webkitCurrentFullScreenElement())
return false;
#endif
return true;
}
inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
{
for (; node; node = node->previousSibling()) {
if (!is<StyledElement>(*node))
continue;
if (canShareStyleWithElement(downcast<StyledElement>(node)))
break;
if (count++ == cStyleSearchThreshold)
return nullptr;
}
return downcast<StyledElement>(node);
}
RenderStyle* StyleResolver::locateSharedStyle()
{
State& state = m_state;
if (!state.styledElement() || !state.parentStyle())
return nullptr;
if (state.styledElement()->inlineStyle())
return nullptr;
if (state.styledElement()->isSVGElement() && downcast<SVGElement>(*state.styledElement()).animatedSMILStyleProperties())
return nullptr;
if (state.styledElement()->hasID() && m_ruleSets.features().idsInRules.contains(state.styledElement()->idForStyleResolution().impl()))
return nullptr;
if (parentElementPreventsSharing(state.element()->parentElement()))
return nullptr;
if (state.element() == state.document().cssTarget())
return nullptr;
if (elementHasDirectionAuto(state.element()))
return nullptr;
state.setElementAffectedByClassRules(state.element() && state.element()->hasClass() && classNamesAffectedByRules(state.element()->classNames()));
unsigned count = 0;
unsigned visitedNodeCount = 0;
StyledElement* shareElement = nullptr;
Node* cousinList = state.styledElement()->previousSibling();
while (cousinList) {
shareElement = findSiblingForStyleSharing(cousinList, count);
if (shareElement)
break;
cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
}
if (!shareElement)
return nullptr;
if (styleSharingCandidateMatchesRuleSet(m_ruleSets.sibling()))
return nullptr;
if (styleSharingCandidateMatchesRuleSet(m_ruleSets.uncommonAttribute()))
return nullptr;
if (parentElementPreventsSharing(state.element()->parentElement()))
return nullptr;
return shareElement->renderStyle();
}
static inline bool isAtShadowBoundary(const Element* element)
{
if (!element)
return false;
ContainerNode* parentNode = element->parentNode();
return parentNode && parentNode->isShadowRoot();
}
Ref<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent,
StyleSharingBehavior sharingBehavior, RuleMatchingBehavior matchingBehavior, const RenderRegion* regionForStyling)
{
RELEASE_ASSERT(!m_inLoadPendingImages);
if (sharingBehavior == AllowStyleSharing && !element->document().haveStylesheetsLoaded() && !element->renderer()) {
if (!s_styleNotYetAvailable) {
s_styleNotYetAvailable = &RenderStyle::create().leakRef();
s_styleNotYetAvailable->setDisplay(NONE);
s_styleNotYetAvailable->fontCascade().update(&document().fontSelector());
}
element->document().setHasNodesWithPlaceholderStyle();
return *s_styleNotYetAvailable;
}
State& state = m_state;
initElement(element);
state.initForStyleResolve(document(), element, defaultParent, regionForStyling);
if (sharingBehavior == AllowStyleSharing) {
if (RenderStyle* sharedStyle = locateSharedStyle()) {
state.clear();
return *sharedStyle;
}
}
if (state.parentStyle()) {
state.setStyle(RenderStyle::create());
state.style()->inheritFrom(state.parentStyle(), isAtShadowBoundary(element) ? RenderStyle::AtShadowBoundary : RenderStyle::NotAtShadowBoundary);
} else {
state.setStyle(defaultStyleForElement());
state.setParentStyle(RenderStyle::clone(state.style()));
}
if (element->isLink()) {
state.style()->setIsLink(true);
EInsideLink linkState = state.elementLinkState();
if (linkState != NotInsideLink) {
bool forceVisited = InspectorInstrumentation::forcePseudoState(*element, CSSSelector::PseudoClassVisited);
if (forceVisited)
linkState = InsideVisitedLink;
}
state.style()->setInsideLink(linkState);
}
bool needsCollection = false;
CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(*element, needsCollection);
if (needsCollection)
m_ruleSets.collectFeatures();
ElementRuleCollector collector(*element, state.style(), m_ruleSets, m_selectorFilter);
collector.setRegionForStyling(regionForStyling);
collector.setMedium(m_medium.get());
if (matchingBehavior == MatchOnlyUserAgentRules)
collector.matchUARules();
else
collector.matchAllRules(m_matchAuthorAndUserStyles, matchingBehavior != MatchAllRulesExcludingSMIL);
applyMatchedProperties(collector.matchedResult(), element);
adjustRenderStyle(*state.style(), *state.parentStyle(), element);
if (state.style()->hasViewportUnits())
document().setHasStyleWithViewportUnits();
state.clear();
return state.takeStyle();
}
Ref<RenderStyle> StyleResolver::styleForKeyframe(const RenderStyle* elementStyle, const StyleKeyframe* keyframe, KeyframeValue& keyframeValue)
{
RELEASE_ASSERT(!m_inLoadPendingImages);
MatchResult result;
result.addMatchedProperties(keyframe->properties());
ASSERT(!m_state.style());
State& state = m_state;
state.setStyle(RenderStyle::clone(elementStyle));
state.setParentStyle(RenderStyle::clone(elementStyle));
TextDirection direction;
WritingMode writingMode;
extractDirectionAndWritingMode(*state.style(), result, direction, writingMode);
CascadedProperties cascade(direction, writingMode);
cascade.addMatches(result, false, 0, result.matchedProperties().size() - 1);
applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty);
updateFont();
applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty);
updateFont();
cascade.applyDeferredProperties(*this);
loadPendingResources();
unsigned propertyCount = keyframe->properties().propertyCount();
for (unsigned i = 0; i < propertyCount; ++i) {
CSSPropertyID property = keyframe->properties().propertyAt(i).id();
if (property != CSSPropertyWebkitAnimationTimingFunction && property != CSSPropertyAnimationTimingFunction)
keyframeValue.addProperty(property);
}
return state.takeStyle();
}
void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
{
list.clear();
if (!e || list.animationName().isEmpty())
return;
m_keyframesRuleMap.checkConsistency();
KeyframesRuleMap::iterator it = m_keyframesRuleMap.find(list.animationName().impl());
if (it == m_keyframesRuleMap.end())
return;
const StyleRuleKeyframes* keyframesRule = it->value.get();
const Vector<RefPtr<StyleKeyframe>>& keyframes = keyframesRule->keyframes();
for (unsigned i = 0; i < keyframes.size(); ++i) {
initElement(e);
m_state.initForStyleResolve(document(), e, nullptr);
const StyleKeyframe* keyframe = keyframes[i].get();
KeyframeValue keyframeValue(0, nullptr);
keyframeValue.setStyle(styleForKeyframe(elementStyle, keyframe, keyframeValue));
for (auto& key: keyframe->keys()) {
keyframeValue.setKey(key);
list.insert(keyframeValue);
}
}
int initialListSize = list.size();
if (initialListSize > 0 && list[0].key()) {
static StyleKeyframe* zeroPercentKeyframe;
if (!zeroPercentKeyframe) {
zeroPercentKeyframe = &StyleKeyframe::create(MutableStyleProperties::create()).leakRef();
zeroPercentKeyframe->setKeyText("0%");
}
KeyframeValue keyframeValue(0, nullptr);
keyframeValue.setStyle(styleForKeyframe(elementStyle, zeroPercentKeyframe, keyframeValue));
list.insert(keyframeValue);
}
if (initialListSize > 0 && (list[list.size() - 1].key() != 1)) {
static StyleKeyframe* hundredPercentKeyframe;
if (!hundredPercentKeyframe) {
hundredPercentKeyframe = &StyleKeyframe::create(MutableStyleProperties::create()).leakRef();
hundredPercentKeyframe->setKeyText("100%");
}
KeyframeValue keyframeValue(1, nullptr);
keyframeValue.setStyle(styleForKeyframe(elementStyle, hundredPercentKeyframe, keyframeValue));
list.insert(keyframeValue);
}
}
PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
{
ASSERT(parentStyle);
if (!element)
return nullptr;
State& state = m_state;
initElement(element);
state.initForStyleResolve(document(), element, parentStyle);
if (m_state.parentStyle()) {
state.setStyle(RenderStyle::create());
state.style()->inheritFrom(m_state.parentStyle());
} else {
state.setStyle(defaultStyleForElement());
state.setParentStyle(RenderStyle::clone(state.style()));
}
ElementRuleCollector collector(*element, m_state.style(), m_ruleSets, m_selectorFilter);
collector.setPseudoStyleRequest(pseudoStyleRequest);
collector.setMedium(m_medium.get());
collector.matchUARules();
if (m_matchAuthorAndUserStyles) {
collector.matchUserRules(false);
collector.matchAuthorRules(false);
}
if (collector.matchedResult().matchedProperties().isEmpty())
return nullptr;
state.style()->setStyleType(pseudoStyleRequest.pseudoId);
applyMatchedProperties(collector.matchedResult(), element);
adjustRenderStyle(*state.style(), *m_state.parentStyle(), nullptr);
if (state.style()->hasViewportUnits())
document().setHasStyleWithViewportUnits();
loadPendingResources();
return state.takeStyle();
}
Ref<RenderStyle> StyleResolver::styleForPage(int pageIndex)
{
RELEASE_ASSERT(!m_inLoadPendingImages);
m_state.initForStyleResolve(m_document, m_document.documentElement(), m_document.renderStyle());
m_state.setStyle(RenderStyle::create());
m_state.style()->inheritFrom(m_state.rootElementStyle());
PageRuleCollector collector(m_state, m_ruleSets);
collector.matchAllPageRules(pageIndex);
MatchResult& result = collector.matchedResult();
TextDirection direction;
WritingMode writingMode;
extractDirectionAndWritingMode(*m_state.style(), result, direction, writingMode);
CascadedProperties cascade(direction, writingMode);
cascade.addMatches(result, false, 0, result.matchedProperties().size() - 1);
applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty);
updateFont();
applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty);
cascade.applyDeferredProperties(*this);
loadPendingResources();
return m_state.takeStyle();
}
Ref<RenderStyle> StyleResolver::defaultStyleForElement()
{
m_state.setStyle(RenderStyle::create());
if (Settings* settings = documentSettings()) {
initializeFontStyle(settings);
m_state.style()->fontCascade().update(&document().fontSelector());
} else
m_state.style()->fontCascade().update(nullptr);
return m_state.takeStyle();
}
static void addIntrinsicMargins(RenderStyle& style)
{
const int intrinsicMargin = 2 * style.effectiveZoom();
if (style.width().isIntrinsicOrAuto()) {
if (style.marginLeft().hasQuirk())
style.setMarginLeft(Length(intrinsicMargin, Fixed));
if (style.marginRight().hasQuirk())
style.setMarginRight(Length(intrinsicMargin, Fixed));
}
if (style.height().isAuto()) {
if (style.marginTop().hasQuirk())
style.setMarginTop(Length(intrinsicMargin, Fixed));
if (style.marginBottom().hasQuirk())
style.setMarginBottom(Length(intrinsicMargin, Fixed));
}
}
static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool strictParsing)
{
switch (display) {
case BLOCK:
case TABLE:
case BOX:
case FLEX:
case WEBKIT_FLEX:
#if ENABLE(CSS_GRID_LAYOUT)
case GRID:
#endif
return display;
case LIST_ITEM:
if (!strictParsing && isFloating)
return BLOCK;
return display;
case INLINE_TABLE:
return TABLE;
case INLINE_BOX:
return BOX;
case INLINE_FLEX:
case WEBKIT_INLINE_FLEX:
return FLEX;
#if ENABLE(CSS_GRID_LAYOUT)
case INLINE_GRID:
return GRID;
#endif
case INLINE:
case COMPACT:
case INLINE_BLOCK:
case TABLE_ROW_GROUP:
case TABLE_HEADER_GROUP:
case TABLE_FOOTER_GROUP:
case TABLE_ROW:
case TABLE_COLUMN_GROUP:
case TABLE_COLUMN:
case TABLE_CELL:
case TABLE_CAPTION:
return BLOCK;
case NONE:
ASSERT_NOT_REACHED();
return NONE;
}
ASSERT_NOT_REACHED();
return BLOCK;
}
static bool doesNotInheritTextDecoration(const RenderStyle& style, Element* e)
{
return style.display() == TABLE || style.display() == INLINE_TABLE
|| style.display() == INLINE_BLOCK || style.display() == INLINE_BOX || isAtShadowBoundary(e)
|| style.isFloating() || style.hasOutOfFlowPosition();
}
#if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
static bool isScrollableOverflow(EOverflow overflow)
{
return overflow == OSCROLL || overflow == OAUTO || overflow == OOVERLAY;
}
#endif
void StyleResolver::adjustStyleForInterCharacterRuby()
{
RenderStyle* style = m_state.style();
if (style->rubyPosition() != RubyPositionInterCharacter || !m_state.element() || !m_state.element()->hasTagName(rtTag))
return;
style->setTextAlign(CENTER);
if (style->isHorizontalWritingMode())
style->setWritingMode(LeftToRightWritingMode);
}
void StyleResolver::adjustRenderStyle(RenderStyle& style, const RenderStyle& parentStyle, Element *e)
{
style.setOriginalDisplay(style.display());
if (style.display() != NONE) {
if (document().inQuirksMode() && e) {
if (e->hasTagName(tdTag)) {
style.setDisplay(TABLE_CELL);
style.setFloating(NoFloat);
} else if (is<HTMLTableElement>(*e))
style.setDisplay(style.isDisplayInlineType() ? INLINE_TABLE : TABLE);
}
if (e && (e->hasTagName(tdTag) || e->hasTagName(thTag))) {
if (style.whiteSpace() == KHTML_NOWRAP) {
if (style.width().isFixed())
style.setWhiteSpace(NORMAL);
else
style.setWhiteSpace(NOWRAP);
}
}
if (is<HTMLTableElement>(e) && (style.textAlign() == WEBKIT_LEFT || style.textAlign() == WEBKIT_CENTER || style.textAlign() == WEBKIT_RIGHT))
style.setTextAlign(TASTART);
if (e && (e->hasTagName(frameTag) || e->hasTagName(framesetTag))) {
style.setPosition(StaticPosition);
style.setDisplay(BLOCK);
}
if (e && e->hasTagName(rtTag)) {
style.setPosition(StaticPosition);
style.setFloating(NoFloat);
}
if (e && e->hasTagName(thTag) && style.textAlign() == TASTART)
style.setTextAlign(CENTER);
if (e && e->hasTagName(legendTag))
style.setDisplay(BLOCK);
if (style.hasOutOfFlowPosition() || style.isFloating() || (e && e->document().documentElement() == e))
style.setDisplay(equivalentBlockDisplay(style.display(), style.isFloating(), !document().inQuirksMode()));
if (style.display() == INLINE && style.styleType() == NOPSEUDO && style.writingMode() != parentStyle.writingMode())
style.setDisplay(INLINE_BLOCK);
if ((style.display() == TABLE_HEADER_GROUP || style.display() == TABLE_ROW_GROUP
|| style.display() == TABLE_FOOTER_GROUP || style.display() == TABLE_ROW)
&& style.position() == RelativePosition)
style.setPosition(StaticPosition);
if (style.display() == TABLE_COLUMN || style.display() == TABLE_COLUMN_GROUP || style.display() == TABLE_FOOTER_GROUP
|| style.display() == TABLE_HEADER_GROUP || style.display() == TABLE_ROW || style.display() == TABLE_ROW_GROUP
|| style.display() == TABLE_CELL)
style.setWritingMode(parentStyle.writingMode());
if (style.writingMode() != TopToBottomWritingMode && (style.display() == BOX || style.display() == INLINE_BOX))
style.setWritingMode(TopToBottomWritingMode);
if (parentStyle.isDisplayFlexibleOrGridBox()) {
style.setFloating(NoFloat);
style.setDisplay(equivalentBlockDisplay(style.display(), style.isFloating(), !document().inQuirksMode()));
}
}
if (style.position() == StaticPosition && !parentStyle.isDisplayFlexibleOrGridBox())
style.setHasAutoZIndex();
if (style.hasAutoZIndex() && ((e && e->document().documentElement() == e)
|| style.opacity() < 1.0f
|| style.hasTransformRelatedProperty()
|| style.hasMask()
|| style.clipPath()
|| style.boxReflect()
|| style.hasFilter()
#if ENABLE(FILTERS_LEVEL_2)
|| style.hasBackdropFilter()
#endif
|| style.hasBlendMode()
|| style.hasIsolation()
|| style.position() == StickyPosition
|| (style.position() == FixedPosition && documentSettings() && documentSettings()->fixedPositionCreatesStackingContext())
|| style.hasFlowFrom()
))
style.setZIndex(0);
if (is<HTMLTextAreaElement>(e)) {
style.setOverflowX(style.overflowX() == OVISIBLE ? OAUTO : style.overflowX());
style.setOverflowY(style.overflowY() == OVISIBLE ? OAUTO : style.overflowY());
}
if (e && !e->shadowPseudoId().isNull())
style.setUserModify(READ_ONLY);
if (doesNotInheritTextDecoration(style, e))
style.setTextDecorationsInEffect(style.textDecoration());
else
style.addToTextDecorationsInEffect(style.textDecoration());
if (style.overflowX() == OMARQUEE && style.overflowY() != OMARQUEE)
style.setOverflowY(OMARQUEE);
else if (style.overflowY() == OMARQUEE && style.overflowX() != OMARQUEE)
style.setOverflowX(OMARQUEE);
else if (style.overflowX() == OVISIBLE && style.overflowY() != OVISIBLE) {
style.setOverflowX(OAUTO);
} else if (style.overflowY() == OVISIBLE && style.overflowX() != OVISIBLE)
style.setOverflowY(OAUTO);
if ((style.overflowY() == OPAGEDX || style.overflowY() == OPAGEDY) && !(e && (e->hasTagName(htmlTag) || e->hasTagName(bodyTag))))
style.setColumnStylesFromPaginationMode(WebCore::paginationModeForRenderStyle(style));
if (style.display() == TABLE || style.display() == INLINE_TABLE
|| style.display() == TABLE_ROW_GROUP || style.display() == TABLE_ROW) {
if (style.overflowX() != OVISIBLE && style.overflowX() != OHIDDEN)
style.setOverflowX(OVISIBLE);
if (style.overflowY() != OVISIBLE && style.overflowY() != OHIDDEN)
style.setOverflowY(OVISIBLE);
}
if (style.appearance() == MenulistPart) {
style.setOverflowX(OVISIBLE);
style.setOverflowY(OVISIBLE);
}
#if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
if (style.hasAutoZIndex() && style.useTouchOverflowScrolling() && (isScrollableOverflow(style.overflowX()) || isScrollableOverflow(style.overflowY())))
style.setZIndex(0);
#endif
style.adjustBackgroundLayers();
style.adjustMaskLayers();
style.adjustAnimations();
style.adjustTransitions();
if (is<HTMLFormControlElement>(e) && style.fontSize() >= 11) {
if (!is<HTMLInputElement>(*e) || !downcast<HTMLInputElement>(*e).isImageButton())
addIntrinsicMargins(style);
}
if (style.hasAppearance())
RenderTheme::defaultTheme()->adjustStyle(*this, style, e, m_state.hasUAAppearance(), m_state.borderData(), m_state.backgroundData(), m_state.backgroundColor());
if (style.hasPseudoStyle(FIRST_LETTER))
style.setUnique();
if (style.preserves3D() && (style.overflowX() != OVISIBLE
|| style.overflowY() != OVISIBLE
|| style.hasFilter()
#if ENABLE(FILTERS_LEVEL_2)
|| style.hasBackdropFilter()
#endif
|| style.hasBlendMode()))
style.setTransformStyle3D(TransformStyle3DFlat);
if (e && e->isSVGElement()) {
if (!(e->hasTagName(SVGNames::svgTag) && e->parentNode() && !e->parentNode()->isSVGElement()))
style.setPosition(RenderStyle::initialPosition());
if (e->hasTagName(SVGNames::foreignObjectTag))
style.setEffectiveZoom(RenderStyle::initialZoom());
if ((e->hasTagName(SVGNames::foreignObjectTag) || e->hasTagName(SVGNames::textTag)) && style.isDisplayInlineType())
style.setDisplay(BLOCK);
}
if (parentStyle.justifyItemsPositionType() == LegacyPosition && style.justifyItemsPosition() == ItemPositionAuto)
style.setJustifyItems(parentStyle.justifyItems());
}
bool StyleResolver::checkRegionStyle(Element* regionElement)
{
unsigned rulesSize = m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().size();
for (unsigned i = 0; i < rulesSize; ++i) {
ASSERT(m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().at(i).ruleSet.get());
if (checkRegionSelector(m_ruleSets.authorStyle()->regionSelectorsAndRuleSets().at(i).selector, regionElement))
return true;
}
if (m_ruleSets.userStyle()) {
rulesSize = m_ruleSets.userStyle()->regionSelectorsAndRuleSets().size();
for (unsigned i = 0; i < rulesSize; ++i) {
ASSERT(m_ruleSets.userStyle()->regionSelectorsAndRuleSets().at(i).ruleSet.get());
if (checkRegionSelector(m_ruleSets.userStyle()->regionSelectorsAndRuleSets().at(i).selector, regionElement))
return true;
}
}
return false;
}
static void checkForOrientationChange(RenderStyle* style)
{
FontOrientation fontOrientation;
NonCJKGlyphOrientation glyphOrientation;
style->getFontAndGlyphOrientation(fontOrientation, glyphOrientation);
const FontDescription& fontDescription = style->fontDescription();
if (fontDescription.orientation() == fontOrientation && fontDescription.nonCJKGlyphOrientation() == glyphOrientation)
return;
FontDescription newFontDescription(fontDescription);
newFontDescription.setNonCJKGlyphOrientation(glyphOrientation);
newFontDescription.setOrientation(fontOrientation);
style->setFontDescription(newFontDescription);
}
void StyleResolver::updateFont()
{
if (!m_state.fontDirty())
return;
RenderStyle* style = m_state.style();
#if ENABLE(IOS_TEXT_AUTOSIZING)
checkForTextSizeAdjust(style);
#endif
checkForGenericFamilyChange(style, m_state.parentStyle());
checkForZoomChange(style, m_state.parentStyle());
checkForOrientationChange(style);
style->fontCascade().update(&document().fontSelector());
if (m_state.fontSizeHasViewportUnits())
style->setHasViewportUnits(true);
m_state.setFontDirty(false);
}
Vector<RefPtr<StyleRule>> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
{
return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
}
Vector<RefPtr<StyleRule>> StyleResolver::pseudoStyleRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude)
{
if (!element || !element->document().haveStylesheetsLoaded())
return Vector<RefPtr<StyleRule>>();
initElement(element);
m_state.initForStyleResolve(document(), element, nullptr);
ElementRuleCollector collector(*element, m_state.style(), m_ruleSets, m_selectorFilter);
collector.setMode(SelectorChecker::Mode::CollectingRules);
collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
collector.setMedium(m_medium.get());
if (rulesToInclude & UAAndUserCSSRules) {
collector.matchUARules();
if (m_matchAuthorAndUserStyles)
collector.matchUserRules(rulesToInclude & EmptyCSSRules);
}
if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
collector.setSameOriginOnly(!(rulesToInclude & CrossOriginCSSRules));
collector.matchAuthorRules(rulesToInclude & EmptyCSSRules);
}
return collector.matchedRuleList();
}
static Length convertToFloatLength(const CSSPrimitiveValue* primitiveValue, const CSSToLengthConversionData& conversionData)
{
return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | CalculatedConversion>(conversionData) : Length(Undefined);
}
static bool shouldApplyPropertyInParseOrder(CSSPropertyID propertyID)
{
switch (propertyID) {
case CSSPropertyWebkitBackgroundClip:
case CSSPropertyBackgroundClip:
case CSSPropertyWebkitBackgroundOrigin:
case CSSPropertyBackgroundOrigin:
case CSSPropertyWebkitBackgroundSize:
case CSSPropertyBackgroundSize:
case CSSPropertyWebkitBorderImage:
case CSSPropertyBorderImage:
case CSSPropertyBorderImageSlice:
case CSSPropertyBorderImageSource:
case CSSPropertyBorderImageOutset:
case CSSPropertyBorderImageRepeat:
case CSSPropertyBorderImageWidth:
case CSSPropertyWebkitBoxShadow:
case CSSPropertyBoxShadow:
case CSSPropertyWebkitTextDecoration:
case CSSPropertyWebkitTextDecorationLine:
case CSSPropertyWebkitTextDecorationStyle:
case CSSPropertyWebkitTextDecorationColor:
case CSSPropertyWebkitTextDecorationSkip:
case CSSPropertyWebkitTextUnderlinePosition:
case CSSPropertyTextDecoration:
return true;
default:
return false;
}
}
static bool elementTypeHasAppearanceFromUAStyle(const Element& element)
{
const auto& localName = element.localName();
return localName == HTMLNames::inputTag
|| localName == HTMLNames::textareaTag
|| localName == HTMLNames::buttonTag
|| localName == HTMLNames::progressTag
|| localName == HTMLNames::selectTag
|| localName == HTMLNames::meterTag
|| localName == HTMLNames::isindexTag;
}
unsigned StyleResolver::computeMatchedPropertiesHash(const MatchedProperties* properties, unsigned size)
{
return StringHasher::hashMemory(properties, sizeof(MatchedProperties) * size);
}
bool operator==(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
{
return a.firstUARule == b.firstUARule
&& a.lastUARule == b.lastUARule
&& a.firstAuthorRule == b.firstAuthorRule
&& a.lastAuthorRule == b.lastAuthorRule
&& a.firstUserRule == b.firstUserRule
&& a.lastUserRule == b.lastUserRule;
}
bool operator!=(const StyleResolver::MatchRanges& a, const StyleResolver::MatchRanges& b)
{
return !(a == b);
}
bool operator==(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
{
return a.properties == b.properties && a.linkMatchType == b.linkMatchType;
}
bool operator!=(const StyleResolver::MatchedProperties& a, const StyleResolver::MatchedProperties& b)
{
return !(a == b);
}
const StyleResolver::MatchedPropertiesCacheItem* StyleResolver::findFromMatchedPropertiesCache(unsigned hash, const MatchResult& matchResult)
{
ASSERT(hash);
MatchedPropertiesCache::iterator it = m_matchedPropertiesCache.find(hash);
if (it == m_matchedPropertiesCache.end())
return nullptr;
MatchedPropertiesCacheItem& cacheItem = it->value;
size_t size = matchResult.matchedProperties().size();
if (size != cacheItem.matchedProperties.size())
return nullptr;
for (size_t i = 0; i < size; ++i) {
if (matchResult.matchedProperties()[i] != cacheItem.matchedProperties[i])
return nullptr;
}
if (cacheItem.ranges != matchResult.ranges)
return nullptr;
return &cacheItem;
}
void StyleResolver::addToMatchedPropertiesCache(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
{
static const unsigned matchedDeclarationCacheAdditionsBetweenSweeps = 100;
if (++m_matchedPropertiesCacheAdditionsSinceLastSweep >= matchedDeclarationCacheAdditionsBetweenSweeps
&& !m_matchedPropertiesCacheSweepTimer.isActive()) {
static const unsigned matchedDeclarationCacheSweepTimeInSeconds = 60;
m_matchedPropertiesCacheSweepTimer.startOneShot(matchedDeclarationCacheSweepTimeInSeconds);
}
ASSERT(hash);
MatchedPropertiesCacheItem cacheItem;
cacheItem.matchedProperties.appendVector(matchResult.matchedProperties());
cacheItem.ranges = matchResult.ranges;
cacheItem.renderStyle = RenderStyle::clone(style);
cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
m_matchedPropertiesCache.add(hash, WTF::move(cacheItem));
}
void StyleResolver::invalidateMatchedPropertiesCache()
{
m_matchedPropertiesCache.clear();
}
void StyleResolver::clearCachedPropertiesAffectedByViewportUnits()
{
Vector<unsigned, 16> toRemove;
for (auto& cacheKeyValue : m_matchedPropertiesCache) {
if (cacheKeyValue.value.renderStyle->hasViewportUnits())
toRemove.append(cacheKeyValue.key);
}
for (auto key : toRemove)
m_matchedPropertiesCache.remove(key);
}
static bool isCacheableInMatchedPropertiesCache(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
{
if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement())
return false;
if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
return false;
if (style->hasAppearance())
return false;
if (style->zoom() != RenderStyle::initialZoom())
return false;
if (style->writingMode() != RenderStyle::initialWritingMode() || style->direction() != RenderStyle::initialDirection())
return false;
if (parentStyle->hasExplicitlyInheritedProperties())
return false;
return true;
}
void extractDirectionAndWritingMode(const RenderStyle& style, const StyleResolver::MatchResult& matchResult, TextDirection& direction, WritingMode& writingMode)
{
direction = style.direction();
writingMode = style.writingMode();
bool hadImportantWebkitWritingMode = false;
bool hadImportantDirection = false;
for (const auto& matchedProperties : matchResult.matchedProperties()) {
for (unsigned i = 0, count = matchedProperties.properties->propertyCount(); i < count; ++i) {
auto property = matchedProperties.properties->propertyAt(i);
if (!property.value()->isPrimitiveValue())
continue;
switch (property.id()) {
case CSSPropertyWebkitWritingMode:
if (!hadImportantWebkitWritingMode || property.isImportant()) {
writingMode = downcast<CSSPrimitiveValue>(*property.value());
hadImportantWebkitWritingMode = property.isImportant();
}
break;
case CSSPropertyDirection:
if (!hadImportantDirection || property.isImportant()) {
direction = downcast<CSSPrimitiveValue>(*property.value());
hadImportantDirection = property.isImportant();
}
break;
default:
break;
}
}
}
}
void StyleResolver::applyMatchedProperties(const MatchResult& matchResult, const Element* element, ShouldUseMatchedPropertiesCache shouldUseMatchedPropertiesCache)
{
ASSERT(element);
State& state = m_state;
unsigned cacheHash = shouldUseMatchedPropertiesCache && matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties().data(), matchResult.matchedProperties().size()) : 0;
bool applyInheritedOnly = false;
const MatchedPropertiesCacheItem* cacheItem = nullptr;
if (cacheHash && (cacheItem = findFromMatchedPropertiesCache(cacheHash, matchResult))
&& isCacheableInMatchedPropertiesCache(element, state.style(), state.parentStyle())) {
state.style()->copyNonInheritedFrom(cacheItem->renderStyle.get());
if (state.parentStyle()->inheritedDataShared(cacheItem->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
EInsideLink linkStatus = state.style()->insideLink();
state.style()->inheritFrom(cacheItem->renderStyle.get());
state.style()->setInsideLink(linkStatus);
return;
}
applyInheritedOnly = true;
}
TextDirection direction;
WritingMode writingMode;
extractDirectionAndWritingMode(*state.style(), matchResult, direction, writingMode);
if (elementTypeHasAppearanceFromUAStyle(*state.element())) {
CascadedProperties cascade(direction, writingMode);
cascade.addMatches(matchResult, false, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
cascade.addMatches(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
applyCascadedProperties(cascade, CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition);
adjustStyleForInterCharacterRuby();
applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty);
updateFont();
applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty);
state.cacheBorderAndBackground();
}
CascadedProperties cascade(direction, writingMode);
cascade.addMatches(matchResult, false, 0, matchResult.matchedProperties().size() - 1, applyInheritedOnly);
cascade.addMatches(matchResult, true, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
cascade.addMatches(matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
cascade.addMatches(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
applyCascadedProperties(cascade, CSSPropertyWebkitRubyPosition, CSSPropertyWebkitRubyPosition);
adjustStyleForInterCharacterRuby();
applyCascadedProperties(cascade, firstCSSProperty, lastHighPriorityProperty);
if (cacheItem && cacheItem->renderStyle->effectiveZoom() != state.style()->effectiveZoom())
return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
updateFont();
if (cacheItem && cacheItem->renderStyle->fontDescription() != state.style()->fontDescription())
return applyMatchedProperties(matchResult, element, DoNotUseMatchedPropertiesCache);
applyCascadedProperties(cascade, firstLowPriorityProperty, lastCSSProperty);
cascade.applyDeferredProperties(*this);
loadPendingResources();
ASSERT(!state.fontDirty());
if (cacheItem || !cacheHash)
return;
if (!isCacheableInMatchedPropertiesCache(state.element(), state.style(), state.parentStyle()))
return;
addToMatchedPropertiesCache(state.style(), state.parentStyle(), cacheHash, matchResult);
}
void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
{
initElement(nullptr);
m_state.initForStyleResolve(document(), nullptr, style);
m_state.setStyle(*style);
applyPropertyToCurrentStyle(id, value);
}
void StyleResolver::applyPropertyToCurrentStyle(CSSPropertyID id, CSSValue* value)
{
if (value)
applyProperty(id, value);
}
inline bool isValidVisitedLinkProperty(CSSPropertyID id)
{
switch (id) {
case CSSPropertyBackgroundColor:
case CSSPropertyBorderLeftColor:
case CSSPropertyBorderRightColor:
case CSSPropertyBorderTopColor:
case CSSPropertyBorderBottomColor:
case CSSPropertyColor:
case CSSPropertyOutlineColor:
case CSSPropertyColumnRuleColor:
case CSSPropertyWebkitTextDecorationColor:
case CSSPropertyWebkitTextEmphasisColor:
case CSSPropertyWebkitTextFillColor:
case CSSPropertyWebkitTextStrokeColor:
case CSSPropertyFill:
case CSSPropertyStroke:
return true;
default:
break;
}
return false;
}
inline bool StyleResolver::isValidRegionStyleProperty(CSSPropertyID id)
{
switch (id) {
case CSSPropertyBackgroundColor:
case CSSPropertyColor:
return true;
default:
break;
}
return false;
}
#if ENABLE(VIDEO_TRACK)
inline bool StyleResolver::isValidCueStyleProperty(CSSPropertyID id)
{
switch (id) {
case CSSPropertyBackground:
case CSSPropertyBackgroundAttachment:
case CSSPropertyBackgroundClip:
case CSSPropertyBackgroundColor:
case CSSPropertyBackgroundImage:
case CSSPropertyBackgroundOrigin:
case CSSPropertyBackgroundPosition:
case CSSPropertyBackgroundPositionX:
case CSSPropertyBackgroundPositionY:
case CSSPropertyBackgroundRepeat:
case CSSPropertyBackgroundRepeatX:
case CSSPropertyBackgroundRepeatY:
case CSSPropertyBackgroundSize:
case CSSPropertyColor:
case CSSPropertyFont:
case CSSPropertyFontFamily:
case CSSPropertyFontSize:
case CSSPropertyFontStyle:
case CSSPropertyFontVariant:
case CSSPropertyFontWeight:
case CSSPropertyLineHeight:
case CSSPropertyOpacity:
case CSSPropertyOutline:
case CSSPropertyOutlineColor:
case CSSPropertyOutlineOffset:
case CSSPropertyOutlineStyle:
case CSSPropertyOutlineWidth:
case CSSPropertyVisibility:
case CSSPropertyWhiteSpace:
case CSSPropertyTextDecoration:
case CSSPropertyTextShadow:
case CSSPropertyBorderStyle:
return true;
default:
break;
}
return false;
}
#endif
bool StyleResolver::useSVGZoomRules()
{
return m_state.element() && m_state.element()->isSVGElement();
}
bool StyleResolver::useSVGZoomRulesForLength()
{
return is<SVGElement>(m_state.element()) && !(is<SVGSVGElement>(*m_state.element()) && m_state.element()->parentNode());
}
void StyleResolver::applyProperty(CSSPropertyID id, CSSValue* value)
{
ASSERT_WITH_MESSAGE(!isShorthandCSSProperty(id), "Shorthand property id = %d wasn't expanded at parsing time", id);
State& state = m_state;
if (CSSProperty::isDirectionAwareProperty(id)) {
CSSPropertyID newId = CSSProperty::resolveDirectionAwareProperty(id, state.style()->direction(), state.style()->writingMode());
ASSERT(newId != id);
return applyProperty(newId, value);
}
bool isInherit = state.parentStyle() && value->isInheritedValue();
bool isInitial = value->isInitialValue() || (!state.parentStyle() && value->isInheritedValue());
ASSERT(!isInherit || !isInitial);
if (!state.applyPropertyToRegularStyle() && (!state.applyPropertyToVisitedLinkStyle() || !isValidVisitedLinkProperty(id))) {
return;
}
if (isInherit && !state.parentStyle()->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))
state.parentStyle()->setHasExplicitlyInheritedProperties();
StyleBuilder::applyProperty(id, *this, *value, isInitial, isInherit);
}
PassRefPtr<StyleImage> StyleResolver::styleImage(CSSPropertyID property, CSSValue& value)
{
if (is<CSSImageValue>(value))
return cachedOrPendingFromValue(property, downcast<CSSImageValue>(value));
if (is<CSSImageGeneratorValue>(value)) {
if (is<CSSGradientValue>(value))
return generatedOrPendingFromValue(property, *downcast<CSSGradientValue>(value).gradientWithStylesResolved(this));
return generatedOrPendingFromValue(property, downcast<CSSImageGeneratorValue>(value));
}
#if ENABLE(CSS_IMAGE_SET)
if (is<CSSImageSetValue>(value))
return setOrPendingFromValue(property, downcast<CSSImageSetValue>(value));
#endif
if (is<CSSCursorImageValue>(value))
return cursorOrPendingFromValue(property, downcast<CSSCursorImageValue>(value));
return nullptr;
}
PassRefPtr<StyleImage> StyleResolver::cachedOrPendingFromValue(CSSPropertyID property, CSSImageValue& value)
{
RefPtr<StyleImage> image = value.cachedOrPendingImage();
if (image && image->isPendingImage())
m_state.pendingImageProperties().set(property, &value);
return image.release();
}
PassRefPtr<StyleImage> StyleResolver::generatedOrPendingFromValue(CSSPropertyID property, CSSImageGeneratorValue& value)
{
if (is<CSSFilterImageValue>(value)) {
downcast<CSSFilterImageValue>(value).createFilterOperations(this);
}
if (value.isPending()) {
m_state.pendingImageProperties().set(property, &value);
return StylePendingImage::create(&value);
}
return StyleGeneratedImage::create(value);
}
#if ENABLE(CSS_IMAGE_SET)
PassRefPtr<StyleImage> StyleResolver::setOrPendingFromValue(CSSPropertyID property, CSSImageSetValue& value)
{
RefPtr<StyleImage> image = value.cachedOrPendingImageSet(document());
if (image && image->isPendingImage())
m_state.pendingImageProperties().set(property, &value);
return image.release();
}
#endif
PassRefPtr<StyleImage> StyleResolver::cursorOrPendingFromValue(CSSPropertyID property, CSSCursorImageValue& value)
{
RefPtr<StyleImage> image = value.cachedOrPendingImage(document());
if (image && image->isPendingImage())
m_state.pendingImageProperties().set(property, &value);
return image.release();
}
#if ENABLE(IOS_TEXT_AUTOSIZING)
void StyleResolver::checkForTextSizeAdjust(RenderStyle* style)
{
if (style->textSizeAdjust().isAuto())
return;
FontDescription newFontDescription(style->fontDescription());
if (!style->textSizeAdjust().isNone())
newFontDescription.setComputedSize(newFontDescription.specifiedSize() * style->textSizeAdjust().multiplier());
else
newFontDescription.setComputedSize(newFontDescription.specifiedSize());
style->setFontDescription(newFontDescription);
}
#endif
void StyleResolver::checkForZoomChange(RenderStyle* style, RenderStyle* parentStyle)
{
if (!parentStyle)
return;
if (style->effectiveZoom() == parentStyle->effectiveZoom())
return;
const FontDescription& childFont = style->fontDescription();
FontDescription newFontDescription(childFont);
setFontSize(newFontDescription, childFont.specifiedSize());
style->setFontDescription(newFontDescription);
}
void StyleResolver::checkForGenericFamilyChange(RenderStyle* style, RenderStyle* parentStyle)
{
const FontDescription& childFont = style->fontDescription();
if (childFont.isAbsoluteSize() || !parentStyle)
return;
const FontDescription& parentFont = parentStyle->fontDescription();
if (childFont.useFixedDefaultSize() == parentFont.useFixedDefaultSize())
return;
float size;
if (CSSValueID sizeIdentifier = childFont.keywordSizeAsIdentifier())
size = Style::fontSizeForKeyword(sizeIdentifier, childFont.useFixedDefaultSize(), document());
else {
Settings* settings = documentSettings();
float fixedScaleFactor = (settings && settings->defaultFixedFontSize() && settings->defaultFontSize())
? static_cast<float>(settings->defaultFixedFontSize()) / settings->defaultFontSize()
: 1;
size = parentFont.useFixedDefaultSize() ?
childFont.specifiedSize() / fixedScaleFactor :
childFont.specifiedSize() * fixedScaleFactor;
}
FontDescription newFontDescription(childFont);
setFontSize(newFontDescription, size);
style->setFontDescription(newFontDescription);
}
void StyleResolver::initializeFontStyle(Settings* settings)
{
FontDescription fontDescription;
fontDescription.setRenderingMode(settings->fontRenderingMode());
fontDescription.setOneFamily(standardFamily);
fontDescription.setKeywordSizeFromIdentifier(CSSValueMedium);
setFontSize(fontDescription, Style::fontSizeForKeyword(CSSValueMedium, false, document()));
setFontDescription(fontDescription);
}
void StyleResolver::setFontSize(FontDescription& fontDescription, float size)
{
fontDescription.setSpecifiedSize(size);
fontDescription.setComputedSize(Style::computedFontSizeFromSpecifiedSize(size, fontDescription.isAbsoluteSize(), useSVGZoomRules(), m_state.style(), document()));
}
static Color colorForCSSValue(CSSValueID cssValueId)
{
struct ColorValue {
CSSValueID cssValueId;
RGBA32 color;
};
static const ColorValue colorValues[] = {
{ CSSValueAqua, 0xFF00FFFF },
{ CSSValueBlack, 0xFF000000 },
{ CSSValueBlue, 0xFF0000FF },
{ CSSValueFuchsia, 0xFFFF00FF },
{ CSSValueGray, 0xFF808080 },
{ CSSValueGreen, 0xFF008000 },
{ CSSValueGrey, 0xFF808080 },
{ CSSValueLime, 0xFF00FF00 },
{ CSSValueMaroon, 0xFF800000 },
{ CSSValueNavy, 0xFF000080 },
{ CSSValueOlive, 0xFF808000 },
{ CSSValueOrange, 0xFFFFA500 },
{ CSSValuePurple, 0xFF800080 },
{ CSSValueRed, 0xFFFF0000 },
{ CSSValueSilver, 0xFFC0C0C0 },
{ CSSValueTeal, 0xFF008080 },
{ CSSValueTransparent, 0x00000000 },
{ CSSValueWhite, 0xFFFFFFFF },
{ CSSValueYellow, 0xFFFFFF00 },
{ CSSValueInvalid, CSSValueInvalid }
};
for (const ColorValue* col = colorValues; col->cssValueId; ++col) {
if (col->cssValueId == cssValueId)
return col->color;
}
return RenderTheme::defaultTheme()->systemColor(cssValueId);
}
bool StyleResolver::colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue& value)
{
int ident = value.getValueID();
switch (ident) {
case CSSValueWebkitText:
case CSSValueWebkitLink:
case CSSValueWebkitActivelink:
case CSSValueCurrentcolor:
return true;
default:
return false;
}
}
Color StyleResolver::colorFromPrimitiveValue(CSSPrimitiveValue& value, bool forVisitedLink) const
{
if (value.isRGBColor())
return Color(value.getRGBA32Value());
const State& state = m_state;
CSSValueID ident = value.getValueID();
switch (ident) {
case 0:
return Color();
case CSSValueWebkitText:
return state.document().textColor();
case CSSValueWebkitLink:
return (state.element()->isLink() && forVisitedLink) ? state.document().visitedLinkColor() : state.document().linkColor();
case CSSValueWebkitActivelink:
return state.document().activeLinkColor();
case CSSValueWebkitFocusRingColor:
return RenderTheme::focusRingColor();
case CSSValueCurrentcolor:
return state.style()->color();
default:
return colorForCSSValue(ident);
}
}
void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExp* expr, bool result)
{
m_viewportDependentMediaQueryResults.append(std::make_unique<MediaQueryResult>(*expr, result));
}
bool StyleResolver::hasMediaQueriesAffectedByViewportChange() const
{
unsigned s = m_viewportDependentMediaQueryResults.size();
for (unsigned i = 0; i < s; i++) {
if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
return true;
}
return false;
}
static FilterOperation::OperationType filterOperationForType(WebKitCSSFilterValue::FilterOperationType type)
{
switch (type) {
case WebKitCSSFilterValue::ReferenceFilterOperation:
return FilterOperation::REFERENCE;
case WebKitCSSFilterValue::GrayscaleFilterOperation:
return FilterOperation::GRAYSCALE;
case WebKitCSSFilterValue::SepiaFilterOperation:
return FilterOperation::SEPIA;
case WebKitCSSFilterValue::SaturateFilterOperation:
return FilterOperation::SATURATE;
case WebKitCSSFilterValue::HueRotateFilterOperation:
return FilterOperation::HUE_ROTATE;
case WebKitCSSFilterValue::InvertFilterOperation:
return FilterOperation::INVERT;
case WebKitCSSFilterValue::OpacityFilterOperation:
return FilterOperation::OPACITY;
case WebKitCSSFilterValue::BrightnessFilterOperation:
return FilterOperation::BRIGHTNESS;
case WebKitCSSFilterValue::ContrastFilterOperation:
return FilterOperation::CONTRAST;
case WebKitCSSFilterValue::BlurFilterOperation:
return FilterOperation::BLUR;
case WebKitCSSFilterValue::DropShadowFilterOperation:
return FilterOperation::DROP_SHADOW;
case WebKitCSSFilterValue::UnknownFilterOperation:
return FilterOperation::NONE;
}
return FilterOperation::NONE;
}
void StyleResolver::loadPendingSVGDocuments()
{
State& state = m_state;
ASSERT(state.style());
if (!state.style() || !state.style()->hasFilter() || state.filtersWithPendingSVGDocuments().isEmpty())
return;
ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
CachedResourceLoader& cachedResourceLoader = state.document().cachedResourceLoader();
for (auto& filterOperation : state.filtersWithPendingSVGDocuments())
filterOperation->getOrCreateCachedSVGDocumentReference()->load(cachedResourceLoader, options);
state.filtersWithPendingSVGDocuments().clear();
}
bool StyleResolver::createFilterOperations(CSSValue& inValue, FilterOperations& outOperations)
{
State& state = m_state;
ASSERT(outOperations.isEmpty());
if (is<CSSPrimitiveValue>(inValue)) {
CSSPrimitiveValue& primitiveValue = downcast<CSSPrimitiveValue>(inValue);
if (primitiveValue.getValueID() == CSSValueNone)
return true;
}
if (!is<CSSValueList>(inValue))
return false;
FilterOperations operations;
for (auto& currentValue : downcast<CSSValueList>(inValue)) {
if (!is<WebKitCSSFilterValue>(currentValue.get()))
continue;
auto& filterValue = downcast<WebKitCSSFilterValue>(currentValue.get());
FilterOperation::OperationType operationType = filterOperationForType(filterValue.operationType());
if (operationType == FilterOperation::REFERENCE) {
if (filterValue.length() != 1)
continue;
CSSValue& argument = *filterValue.itemWithoutBoundsCheck(0);
if (!is<CSSPrimitiveValue>(argument))
continue;
CSSPrimitiveValue& primitiveValue = downcast<CSSPrimitiveValue>(argument);
String cssUrl = primitiveValue.getStringValue();
URL url = m_state.document().completeURL(cssUrl);
RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(cssUrl, url.fragmentIdentifier());
if (SVGURIReference::isExternalURIReference(cssUrl, m_state.document()))
state.filtersWithPendingSVGDocuments().append(operation);
operations.operations().append(operation);
continue;
}
CSSPrimitiveValue* firstValue = nullptr;
if (operationType != FilterOperation::DROP_SHADOW) {
bool haveNonPrimitiveValue = false;
for (unsigned j = 0; j < filterValue.length(); ++j) {
if (!is<CSSPrimitiveValue>(*filterValue.itemWithoutBoundsCheck(j))) {
haveNonPrimitiveValue = true;
break;
}
}
if (haveNonPrimitiveValue)
continue;
if (filterValue.length())
firstValue = downcast<CSSPrimitiveValue>(filterValue.itemWithoutBoundsCheck(0));
}
switch (filterValue.operationType()) {
case WebKitCSSFilterValue::GrayscaleFilterOperation:
case WebKitCSSFilterValue::SepiaFilterOperation:
case WebKitCSSFilterValue::SaturateFilterOperation: {
double amount = 1;
if (filterValue.length() == 1) {
amount = firstValue->getDoubleValue();
if (firstValue->isPercentage())
amount /= 100;
}
operations.operations().append(BasicColorMatrixFilterOperation::create(amount, operationType));
break;
}
case WebKitCSSFilterValue::HueRotateFilterOperation: {
double angle = 0;
if (filterValue.length() == 1)
angle = firstValue->computeDegrees();
operations.operations().append(BasicColorMatrixFilterOperation::create(angle, operationType));
break;
}
case WebKitCSSFilterValue::InvertFilterOperation:
case WebKitCSSFilterValue::BrightnessFilterOperation:
case WebKitCSSFilterValue::ContrastFilterOperation:
case WebKitCSSFilterValue::OpacityFilterOperation: {
double amount = (filterValue.operationType() == WebKitCSSFilterValue::BrightnessFilterOperation) ? 0 : 1;
if (filterValue.length() == 1) {
amount = firstValue->getDoubleValue();
if (firstValue->isPercentage())
amount /= 100;
}
operations.operations().append(BasicComponentTransferFilterOperation::create(amount, operationType));
break;
}
case WebKitCSSFilterValue::BlurFilterOperation: {
Length stdDeviation = Length(0, Fixed);
if (filterValue.length() >= 1)
stdDeviation = convertToFloatLength(firstValue, state.cssToLengthConversionData());
if (stdDeviation.isUndefined())
return false;
operations.operations().append(BlurFilterOperation::create(stdDeviation));
break;
}
case WebKitCSSFilterValue::DropShadowFilterOperation: {
if (filterValue.length() != 1)
return false;
CSSValue& cssValue = *filterValue.itemWithoutBoundsCheck(0);
if (!is<CSSShadowValue>(cssValue))
continue;
CSSShadowValue& item = downcast<CSSShadowValue>(cssValue);
int x = item.x->computeLength<int>(state.cssToLengthConversionData());
int y = item.y->computeLength<int>(state.cssToLengthConversionData());
IntPoint location(x, y);
int blur = item.blur ? item.blur->computeLength<int>(state.cssToLengthConversionData()) : 0;
Color color;
if (item.color)
color = colorFromPrimitiveValue(*item.color);
operations.operations().append(DropShadowFilterOperation::create(location, blur, color.isValid() ? color : Color::transparent));
break;
}
case WebKitCSSFilterValue::UnknownFilterOperation:
default:
ASSERT_NOT_REACHED();
break;
}
}
outOperations = operations;
return true;
}
PassRefPtr<StyleImage> StyleResolver::loadPendingImage(const StylePendingImage& pendingImage, const ResourceLoaderOptions& options)
{
if (auto imageValue = pendingImage.cssImageValue())
return imageValue->cachedImage(m_state.document().cachedResourceLoader(), options);
if (auto imageGeneratorValue = pendingImage.cssImageGeneratorValue()) {
imageGeneratorValue->loadSubimages(m_state.document().cachedResourceLoader(), options);
return StyleGeneratedImage::create(*imageGeneratorValue);
}
if (auto cursorImageValue = pendingImage.cssCursorImageValue())
return cursorImageValue->cachedImage(m_state.document().cachedResourceLoader(), options);
#if ENABLE(CSS_IMAGE_SET)
if (auto imageSetValue = pendingImage.cssImageSetValue())
return imageSetValue->cachedImageSet(m_state.document().cachedResourceLoader(), options);
#endif
return nullptr;
}
PassRefPtr<StyleImage> StyleResolver::loadPendingImage(const StylePendingImage& pendingImage)
{
ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
return loadPendingImage(pendingImage, options);
}
#if ENABLE(CSS_SHAPES)
void StyleResolver::loadPendingShapeImage(ShapeValue* shapeValue)
{
if (!shapeValue)
return;
StyleImage* image = shapeValue->image();
if (!is<StylePendingImage>(image))
return;
auto& pendingImage = downcast<StylePendingImage>(*image);
ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
options.setRequestOriginPolicy(PotentiallyCrossOriginEnabled);
options.setAllowCredentials(DoNotAllowStoredCredentials);
options.setContentSecurityPolicyImposition(m_state.element() && m_state.element()->isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
shapeValue->setImage(loadPendingImage(pendingImage, options));
}
#endif
void StyleResolver::loadPendingImages()
{
RELEASE_ASSERT(!m_inLoadPendingImages);
TemporaryChange<bool> changeInLoadPendingImages(m_inLoadPendingImages, true);
if (m_state.pendingImageProperties().isEmpty())
return;
auto end = m_state.pendingImageProperties().end().keys();
for (auto it = m_state.pendingImageProperties().begin().keys(); it != end; ++it) {
CSSPropertyID currentProperty = *it;
switch (currentProperty) {
case CSSPropertyBackgroundImage: {
for (FillLayer* backgroundLayer = &m_state.style()->ensureBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
auto* styleImage = backgroundLayer->image();
if (is<StylePendingImage>(styleImage))
backgroundLayer->setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
}
break;
}
case CSSPropertyContent: {
for (ContentData* contentData = const_cast<ContentData*>(m_state.style()->contentData()); contentData; contentData = contentData->next()) {
if (is<ImageContentData>(*contentData)) {
auto& styleImage = downcast<ImageContentData>(*contentData).image();
if (is<StylePendingImage>(styleImage)) {
if (RefPtr<StyleImage> loadedImage = loadPendingImage(downcast<StylePendingImage>(styleImage)))
downcast<ImageContentData>(*contentData).setImage(loadedImage.release());
}
}
}
break;
}
case CSSPropertyCursor: {
if (CursorList* cursorList = m_state.style()->cursors()) {
for (size_t i = 0; i < cursorList->size(); ++i) {
CursorData& currentCursor = cursorList->at(i);
auto* styleImage = currentCursor.image();
if (is<StylePendingImage>(styleImage))
currentCursor.setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
}
}
break;
}
case CSSPropertyListStyleImage: {
auto* styleImage = m_state.style()->listStyleImage();
if (is<StylePendingImage>(styleImage))
m_state.style()->setListStyleImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
break;
}
case CSSPropertyBorderImageSource: {
auto* styleImage = m_state.style()->borderImageSource();
if (is<StylePendingImage>(styleImage))
m_state.style()->setBorderImageSource(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
break;
}
case CSSPropertyWebkitBoxReflect: {
if (StyleReflection* reflection = m_state.style()->boxReflect()) {
const NinePieceImage& maskImage = reflection->mask();
auto* styleImage = maskImage.image();
if (is<StylePendingImage>(styleImage)) {
RefPtr<StyleImage> loadedImage = loadPendingImage(downcast<StylePendingImage>(*styleImage));
reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
}
}
break;
}
case CSSPropertyWebkitMaskBoxImageSource: {
auto* styleImage = m_state.style()->maskBoxImageSource();
if (is<StylePendingImage>(styleImage))
m_state.style()->setMaskBoxImageSource(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
break;
}
case CSSPropertyWebkitMaskImage: {
for (FillLayer* maskLayer = &m_state.style()->ensureMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
auto* styleImage = maskLayer->image();
if (is<StylePendingImage>(styleImage))
maskLayer->setImage(loadPendingImage(downcast<StylePendingImage>(*styleImage)));
}
break;
}
#if ENABLE(CSS_SHAPES)
case CSSPropertyWebkitShapeOutside:
loadPendingShapeImage(m_state.style()->shapeOutside());
break;
#endif
default:
ASSERT_NOT_REACHED();
}
}
m_state.pendingImageProperties().clear();
}
#ifndef NDEBUG
static bool inLoadPendingResources = false;
#endif
void StyleResolver::loadPendingResources()
{
ASSERT(style());
if (!style())
return;
#ifndef NDEBUG
ASSERT(!inLoadPendingResources);
inLoadPendingResources = true;
#endif
loadPendingImages();
loadPendingSVGDocuments();
#ifndef NDEBUG
inLoadPendingResources = false;
#endif
}
inline StyleResolver::MatchedProperties::MatchedProperties()
: possiblyPaddedMember(nullptr)
{
}
StyleResolver::MatchedProperties::~MatchedProperties()
{
}
StyleResolver::CascadedProperties::CascadedProperties(TextDirection direction, WritingMode writingMode)
: m_direction(direction)
, m_writingMode(writingMode)
{
}
inline bool StyleResolver::CascadedProperties::hasProperty(CSSPropertyID id) const
{
ASSERT(id < m_propertyIsPresent.size());
return m_propertyIsPresent[id];
}
inline StyleResolver::CascadedProperties::Property& StyleResolver::CascadedProperties::property(CSSPropertyID id)
{
return m_properties[id];
}
void StyleResolver::CascadedProperties::setPropertyInternal(Property& property, CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType)
{
ASSERT(linkMatchType <= SelectorChecker::MatchAll);
property.id = id;
if (linkMatchType == SelectorChecker::MatchAll) {
property.cssValue[0] = &cssValue;
property.cssValue[SelectorChecker::MatchLink] = &cssValue;
property.cssValue[SelectorChecker::MatchVisited] = &cssValue;
} else
property.cssValue[linkMatchType] = &cssValue;
}
void StyleResolver::CascadedProperties::set(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType)
{
if (CSSProperty::isDirectionAwareProperty(id))
id = CSSProperty::resolveDirectionAwareProperty(id, m_direction, m_writingMode);
ASSERT(!shouldApplyPropertyInParseOrder(id));
auto& property = m_properties[id];
ASSERT(id < m_propertyIsPresent.size());
if (!m_propertyIsPresent[id])
memset(property.cssValue, 0, sizeof(property.cssValue));
m_propertyIsPresent.set(id);
setPropertyInternal(property, id, cssValue, linkMatchType);
}
void StyleResolver::CascadedProperties::setDeferred(CSSPropertyID id, CSSValue& cssValue, unsigned linkMatchType)
{
ASSERT(!CSSProperty::isDirectionAwareProperty(id));
ASSERT(shouldApplyPropertyInParseOrder(id));
Property property;
memset(property.cssValue, 0, sizeof(property.cssValue));
setPropertyInternal(property, id, cssValue, linkMatchType);
m_deferredProperties.append(property);
}
void StyleResolver::CascadedProperties::addStyleProperties(const StyleProperties& properties, StyleRule&, bool isImportant, bool inheritedOnly, PropertyWhitelistType propertyWhitelistType, unsigned linkMatchType)
{
for (unsigned i = 0, count = properties.propertyCount(); i < count; ++i) {
auto current = properties.propertyAt(i);
if (isImportant != current.isImportant())
continue;
if (inheritedOnly && !current.isInherited()) {
ASSERT(!current.value()->isInheritedValue());
continue;
}
CSSPropertyID propertyID = current.id();
if (propertyWhitelistType == PropertyWhitelistRegion && !StyleResolver::isValidRegionStyleProperty(propertyID))
continue;
#if ENABLE(VIDEO_TRACK)
if (propertyWhitelistType == PropertyWhitelistCue && !StyleResolver::isValidCueStyleProperty(propertyID))
continue;
#endif
if (shouldApplyPropertyInParseOrder(propertyID))
setDeferred(propertyID, *current.value(), linkMatchType);
else
set(propertyID, *current.value(), linkMatchType);
}
}
void StyleResolver::CascadedProperties::addMatches(const MatchResult& matchResult, bool important, int startIndex, int endIndex, bool inheritedOnly)
{
if (startIndex == -1)
return;
for (int i = startIndex; i <= endIndex; ++i) {
const MatchedProperties& matchedProperties = matchResult.matchedProperties()[i];
addStyleProperties(*matchedProperties.properties, *matchResult.matchedRules[i], important, inheritedOnly, static_cast<PropertyWhitelistType>(matchedProperties.whitelistType), matchedProperties.linkMatchType);
}
}
void StyleResolver::CascadedProperties::applyDeferredProperties(StyleResolver& resolver)
{
for (auto& property : m_deferredProperties)
property.apply(resolver);
}
void StyleResolver::CascadedProperties::Property::apply(StyleResolver& resolver)
{
State& state = resolver.state();
if (cssValue[0]) {
state.setApplyPropertyToRegularStyle(true);
state.setApplyPropertyToVisitedLinkStyle(false);
resolver.applyProperty(id, cssValue[0]);
}
if (state.style()->insideLink() == NotInsideLink)
return;
if (cssValue[SelectorChecker::MatchLink]) {
state.setApplyPropertyToRegularStyle(true);
state.setApplyPropertyToVisitedLinkStyle(false);
resolver.applyProperty(id, cssValue[SelectorChecker::MatchLink]);
}
if (cssValue[SelectorChecker::MatchVisited]) {
state.setApplyPropertyToRegularStyle(false);
state.setApplyPropertyToVisitedLinkStyle(true);
resolver.applyProperty(id, cssValue[SelectorChecker::MatchVisited]);
}
state.setApplyPropertyToRegularStyle(true);
state.setApplyPropertyToVisitedLinkStyle(false);
}
void StyleResolver::applyCascadedProperties(CascadedProperties& cascade, int firstProperty, int lastProperty)
{
for (int id = firstProperty; id <= lastProperty; ++id) {
CSSPropertyID propertyID = static_cast<CSSPropertyID>(id);
if (!cascade.hasProperty(propertyID))
continue;
auto& property = cascade.property(propertyID);
ASSERT(!shouldApplyPropertyInParseOrder(propertyID));
property.apply(*this);
}
}
}