[CSS Parser] Remove the old CSS Parser
[WebKit-https.git] / Source / WebCore / rendering / style / RenderStyle.cpp
1 /*
2  * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
3  * Copyright (C) 2004-2015 Apple Inc. All rights reserved.
4  * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public License
17  * along with this library; see the file COPYING.LIB.  If not, write to
18  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  *
21  */
22
23 #include "config.h"
24 #include "RenderStyle.h"
25
26 #include "ContentData.h"
27 #include "CSSCustomPropertyValue.h"
28 #include "CSSParser.h"
29 #include "CSSPropertyNames.h"
30 #include "CursorList.h"
31 #include "FloatRoundedRect.h"
32 #include "FontCascade.h"
33 #include "FontSelector.h"
34 #include "InlineTextBoxStyle.h"
35 #include "Pagination.h"
36 #include "QuotesData.h"
37 #include "RenderObject.h"
38 #include "RenderTheme.h"
39 #include "RuntimeEnabledFeatures.h"
40 #include "ScaleTransformOperation.h"
41 #include "ShadowData.h"
42 #include "StyleImage.h"
43 #include "StyleInheritedData.h"
44 #include "StyleResolver.h"
45 #include "StyleScrollSnapPoints.h"
46 #include "StyleSelfAlignmentData.h"
47 #include "StyleTreeResolver.h"
48 #include "WillChangeData.h"
49 #include <wtf/MathExtras.h>
50 #include <wtf/PointerComparison.h>
51 #include <wtf/StdLibExtras.h>
52 #include <algorithm>
53
54 #if ENABLE(TEXT_AUTOSIZING)
55 #include <wtf/text/StringHash.h>
56 #endif
57
58 namespace WebCore {
59
60 struct SameSizeAsBorderValue {
61     float m_width;
62     Color m_color;
63     int m_restBits;
64 };
65
66 COMPILE_ASSERT(sizeof(BorderValue) == sizeof(SameSizeAsBorderValue), BorderValue_should_not_grow);
67
68 struct SameSizeAsRenderStyle {
69     void* dataRefs[7];
70     void* ownPtrs[1];
71     void* dataRefSvgStyle;
72     struct InheritedFlags {
73         unsigned m_bitfields[2];
74     } inherited_flags;
75
76     struct NonInheritedFlags {
77         uint64_t m_flags;
78     } noninherited_flags;
79 #if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
80     bool deletionCheck;
81 #endif
82 };
83
84 COMPILE_ASSERT(sizeof(RenderStyle) == sizeof(SameSizeAsRenderStyle), RenderStyle_should_stay_small);
85
86 RenderStyle& RenderStyle::defaultStyle()
87 {
88     static RenderStyle& style = *new RenderStyle(CreateDefaultStyle);
89     return style;
90 }
91
92 RenderStyle RenderStyle::create()
93 {
94     return clone(defaultStyle());
95 }
96
97 std::unique_ptr<RenderStyle> RenderStyle::createPtr()
98 {
99     return clonePtr(defaultStyle());
100 }
101
102 RenderStyle RenderStyle::clone(const RenderStyle& style)
103 {
104     return RenderStyle(style, Clone);
105 }
106
107 std::unique_ptr<RenderStyle> RenderStyle::clonePtr(const RenderStyle& style)
108 {
109     return std::make_unique<RenderStyle>(style, Clone);
110 }
111
112 RenderStyle RenderStyle::createAnonymousStyleWithDisplay(const RenderStyle& parentStyle, EDisplay display)
113 {
114     auto newStyle = create();
115     newStyle.inheritFrom(&parentStyle);
116     newStyle.inheritUnicodeBidiFrom(&parentStyle);
117     newStyle.setDisplay(display);
118     return newStyle;
119 }
120
121 RenderStyle RenderStyle::createStyleInheritingFromPseudoStyle(const RenderStyle& pseudoStyle)
122 {
123     ASSERT(pseudoStyle.styleType() == BEFORE || pseudoStyle.styleType() == AFTER);
124
125     auto style = create();
126     style.inheritFrom(&pseudoStyle);
127     return style;
128 }
129
130 RenderStyle::RenderStyle(CreateDefaultStyleTag)
131     : m_box(StyleBoxData::create())
132     , visual(StyleVisualData::create())
133     , m_background(StyleBackgroundData::create())
134     , surround(StyleSurroundData::create())
135     , rareNonInheritedData(StyleRareNonInheritedData::create())
136     , rareInheritedData(StyleRareInheritedData::create())
137     , inherited(StyleInheritedData::create())
138     , m_svgStyle(SVGRenderStyle::create())
139 {
140     inherited_flags._empty_cells = initialEmptyCells();
141     inherited_flags._caption_side = initialCaptionSide();
142     inherited_flags._list_style_type = initialListStyleType();
143     inherited_flags._list_style_position = initialListStylePosition();
144     inherited_flags._visibility = initialVisibility();
145     inherited_flags._text_align = initialTextAlign();
146     inherited_flags._text_transform = initialTextTransform();
147     inherited_flags._text_decorations = initialTextDecoration();
148     inherited_flags._cursor_style = initialCursor();
149 #if ENABLE(CURSOR_VISIBILITY)
150     inherited_flags.m_cursorVisibility = initialCursorVisibility();
151 #endif
152     inherited_flags._direction = initialDirection();
153     inherited_flags._white_space = initialWhiteSpace();
154     inherited_flags._border_collapse = initialBorderCollapse();
155     inherited_flags.m_rtlOrdering = initialRTLOrdering();
156     inherited_flags._box_direction = initialBoxDirection();
157     inherited_flags.m_printColorAdjust = initialPrintColorAdjust();
158     inherited_flags._pointerEvents = initialPointerEvents();
159     inherited_flags._insideLink = NotInsideLink;
160     inherited_flags._insideDefaultButton = false;
161     inherited_flags.m_writingMode = initialWritingMode();
162
163     static_assert((sizeof(InheritedFlags) <= 8), "InheritedFlags does not grow");
164     static_assert((sizeof(NonInheritedFlags) <= 8), "NonInheritedFlags does not grow");
165 }
166
167 RenderStyle::RenderStyle(const RenderStyle& other, CloneTag)
168     : m_box(other.m_box)
169     , visual(other.visual)
170     , m_background(other.m_background)
171     , surround(other.surround)
172     , rareNonInheritedData(other.rareNonInheritedData)
173     , rareInheritedData(other.rareInheritedData)
174     , inherited(other.inherited)
175     , m_svgStyle(other.m_svgStyle)
176     , inherited_flags(other.inherited_flags)
177     , noninherited_flags(other.noninherited_flags)
178 {
179 }
180
181 RenderStyle::~RenderStyle()
182 {
183 #if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
184     ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
185     m_deletionHasBegun = true;
186 #endif
187 }
188
189 bool RenderStyle::isCSSGridLayoutEnabled()
190 {
191 #if ENABLE(CSS_GRID_LAYOUT)
192     return RuntimeEnabledFeatures::sharedFeatures().isCSSGridLayoutEnabled();
193 #else
194     return false;
195 #endif
196 }
197
198 static StyleSelfAlignmentData resolvedSelfAlignment(const StyleSelfAlignmentData& value, ItemPosition normalValueBehavior)
199 {
200     ASSERT(value.position() != ItemPositionAuto);
201     if (value.position() == ItemPositionNormal)
202         return { normalValueBehavior, OverflowAlignmentDefault };
203     return value;
204 }
205
206 StyleSelfAlignmentData RenderStyle::resolvedAlignItems(ItemPosition normalValueBehaviour) const
207 {
208     return resolvedSelfAlignment(alignItems(), normalValueBehaviour);
209 }
210
211 StyleSelfAlignmentData RenderStyle::resolvedAlignSelf(const RenderStyle& parentStyle, ItemPosition normalValueBehaviour) const
212 {
213     // The auto keyword computes to the parent's align-items computed value.
214     // We will return the behaviour of 'normal' value if needed, which is specific of each layout model.
215     if (alignSelfPosition() == ItemPositionAuto)
216         return parentStyle.resolvedAlignItems(normalValueBehaviour);
217     return resolvedSelfAlignment(alignSelf(), normalValueBehaviour);
218 }
219
220 StyleSelfAlignmentData RenderStyle::resolvedJustifyItems(ItemPosition normalValueBehaviour) const
221 {
222     // FIXME: justify-items 'auto' value is allowed only to provide the 'legacy' keyword's behavior, which it's still not implemented for layout.
223     // "If the inherited value of justify-items includes the legacy keyword, auto computes to the inherited value."
224     // https://drafts.csswg.org/css-align/#justify-items-property
225     if (justifyItemsPosition() == ItemPositionAuto)
226         return { normalValueBehaviour, OverflowAlignmentDefault };
227
228     return resolvedSelfAlignment(justifyItems(), normalValueBehaviour);
229 }
230
231 StyleSelfAlignmentData RenderStyle::resolvedJustifySelf(const RenderStyle& parentStyle, ItemPosition normalValueBehaviour) const
232 {
233     // The auto keyword computes to the parent's justify-items computed value.
234     // We will return the behaviour of 'normal' value if needed, which is specific of each layout model.
235     if (justifySelfPosition() == ItemPositionAuto)
236         return parentStyle.resolvedJustifyItems(normalValueBehaviour);
237     return resolvedSelfAlignment(justifySelf(), normalValueBehaviour);
238 }
239
240 static inline ContentPosition resolvedContentAlignmentPosition(const StyleContentAlignmentData& value, const StyleContentAlignmentData& normalValueBehavior)
241 {
242     return (value.position() == ContentPositionNormal && value.distribution() == ContentDistributionDefault) ? normalValueBehavior.position() : value.position();
243 }
244
245 static inline ContentDistributionType resolvedContentAlignmentDistribution(const StyleContentAlignmentData& value, const StyleContentAlignmentData& normalValueBehavior)
246 {
247     return (value.position() == ContentPositionNormal && value.distribution() == ContentDistributionDefault) ? normalValueBehavior.distribution() : value.distribution();
248 }
249
250 ContentPosition RenderStyle::resolvedJustifyContentPosition(const StyleContentAlignmentData& normalValueBehavior) const
251 {
252     return resolvedContentAlignmentPosition(justifyContent(), normalValueBehavior);
253 }
254
255 ContentDistributionType RenderStyle::resolvedJustifyContentDistribution(const StyleContentAlignmentData& normalValueBehavior) const
256 {
257     return resolvedContentAlignmentDistribution(justifyContent(), normalValueBehavior);
258 }
259
260 ContentPosition RenderStyle::resolvedAlignContentPosition(const StyleContentAlignmentData& normalValueBehavior) const
261 {
262     return resolvedContentAlignmentPosition(alignContent(), normalValueBehavior);
263 }
264
265 ContentDistributionType RenderStyle::resolvedAlignContentDistribution(const StyleContentAlignmentData& normalValueBehavior) const
266 {
267     return resolvedContentAlignmentDistribution(alignContent(), normalValueBehavior);
268 }
269
270 void RenderStyle::inheritFrom(const RenderStyle* inheritParent, IsAtShadowBoundary isAtShadowBoundary)
271 {
272     if (isAtShadowBoundary == AtShadowBoundary) {
273         // Even if surrounding content is user-editable, shadow DOM should act as a single unit, and not necessarily be editable
274         EUserModify currentUserModify = userModify();
275         rareInheritedData = inheritParent->rareInheritedData;
276         setUserModify(currentUserModify);
277     } else
278         rareInheritedData = inheritParent->rareInheritedData;
279     inherited = inheritParent->inherited;
280     inherited_flags = inheritParent->inherited_flags;
281
282     if (m_svgStyle != inheritParent->m_svgStyle)
283         m_svgStyle.access()->inheritFrom(inheritParent->m_svgStyle.get());
284 }
285
286 void RenderStyle::copyNonInheritedFrom(const RenderStyle* other)
287 {
288     m_box = other->m_box;
289     visual = other->visual;
290     m_background = other->m_background;
291     surround = other->surround;
292     rareNonInheritedData = other->rareNonInheritedData;
293     noninherited_flags.copyNonInheritedFrom(other->noninherited_flags);
294
295     if (m_svgStyle != other->m_svgStyle)
296         m_svgStyle.access()->copyNonInheritedFrom(other->m_svgStyle.get());
297
298     ASSERT(zoom() == initialZoom());
299 }
300
301 bool RenderStyle::operator==(const RenderStyle& o) const
302 {
303     // compare everything except the pseudoStyle pointer
304     return inherited_flags == o.inherited_flags
305         && noninherited_flags == o.noninherited_flags
306         && m_box == o.m_box
307         && visual == o.visual
308         && m_background == o.m_background
309         && surround == o.surround
310         && rareNonInheritedData == o.rareNonInheritedData
311         && rareInheritedData == o.rareInheritedData
312         && inherited == o.inherited
313         && m_svgStyle == o.m_svgStyle
314             ;
315 }
316
317 bool RenderStyle::hasUniquePseudoStyle() const
318 {
319     if (!m_cachedPseudoStyles || styleType() != NOPSEUDO)
320         return false;
321
322     for (size_t i = 0; i < m_cachedPseudoStyles->size(); ++i) {
323         RenderStyle* pseudoStyle = m_cachedPseudoStyles->at(i).get();
324         if (pseudoStyle->unique())
325             return true;
326     }
327
328     return false;
329 }
330
331 RenderStyle* RenderStyle::getCachedPseudoStyle(PseudoId pid) const
332 {
333     if (!m_cachedPseudoStyles || !m_cachedPseudoStyles->size())
334         return nullptr;
335
336     if (styleType() != NOPSEUDO) 
337         return nullptr;
338
339     for (size_t i = 0; i < m_cachedPseudoStyles->size(); ++i) {
340         RenderStyle* pseudoStyle = m_cachedPseudoStyles->at(i).get();
341         if (pseudoStyle->styleType() == pid)
342             return pseudoStyle;
343     }
344
345     return nullptr;
346 }
347
348 RenderStyle* RenderStyle::addCachedPseudoStyle(std::unique_ptr<RenderStyle> pseudo)
349 {
350     if (!pseudo)
351         return nullptr;
352
353     ASSERT(pseudo->styleType() > NOPSEUDO);
354
355     RenderStyle* result = pseudo.get();
356
357     if (!m_cachedPseudoStyles)
358         m_cachedPseudoStyles = std::make_unique<PseudoStyleCache>();
359
360     m_cachedPseudoStyles->append(WTFMove(pseudo));
361
362     return result;
363 }
364
365 void RenderStyle::removeCachedPseudoStyle(PseudoId pid)
366 {
367     if (!m_cachedPseudoStyles)
368         return;
369     for (size_t i = 0; i < m_cachedPseudoStyles->size(); ++i) {
370         RenderStyle* pseudoStyle = m_cachedPseudoStyles->at(i).get();
371         if (pseudoStyle->styleType() == pid) {
372             m_cachedPseudoStyles->remove(i);
373             return;
374         }
375     }
376 }
377
378 bool RenderStyle::inheritedNotEqual(const RenderStyle* other) const
379 {
380     return inherited_flags != other->inherited_flags
381            || inherited != other->inherited
382            || m_svgStyle->inheritedNotEqual(other->m_svgStyle.get())
383            || rareInheritedData != other->rareInheritedData;
384 }
385
386 #if ENABLE(TEXT_AUTOSIZING)
387
388 static inline unsigned computeFontHash(const FontCascade& font)
389 {
390     IntegerHasher hasher;
391     hasher.add(ASCIICaseInsensitiveHash::hash(font.fontDescription().firstFamily()));
392     hasher.add(font.fontDescription().specifiedSize());
393     return hasher.hash();
394 }
395
396 unsigned RenderStyle::hashForTextAutosizing() const
397 {
398     // FIXME: Not a very smart hash. Could be improved upon. See <https://bugs.webkit.org/show_bug.cgi?id=121131>.
399     unsigned hash = rareNonInheritedData->m_appearance;
400     hash ^= rareNonInheritedData->marginBeforeCollapse;
401     hash ^= rareNonInheritedData->marginAfterCollapse;
402     hash ^= rareNonInheritedData->lineClamp.value();
403     hash ^= rareInheritedData->overflowWrap;
404     hash ^= rareInheritedData->nbspMode;
405     hash ^= rareInheritedData->lineBreak;
406     hash ^= WTF::FloatHash<float>::hash(inherited->specifiedLineHeight.value());
407     hash ^= computeFontHash(inherited->fontCascade);
408     hash ^= WTF::FloatHash<float>::hash(inherited->horizontal_border_spacing);
409     hash ^= WTF::FloatHash<float>::hash(inherited->vertical_border_spacing);
410     hash ^= inherited_flags._box_direction;
411     hash ^= inherited_flags.m_rtlOrdering;
412     hash ^= noninherited_flags.position();
413     hash ^= noninherited_flags.floating();
414     hash ^= rareNonInheritedData->textOverflow;
415     hash ^= rareInheritedData->textSecurity;
416     return hash;
417 }
418
419 bool RenderStyle::equalForTextAutosizing(const RenderStyle& other) const
420 {
421     return rareNonInheritedData->m_appearance == other.rareNonInheritedData->m_appearance
422         && rareNonInheritedData->marginBeforeCollapse == other.rareNonInheritedData->marginBeforeCollapse
423         && rareNonInheritedData->marginAfterCollapse == other.rareNonInheritedData->marginAfterCollapse
424         && rareNonInheritedData->lineClamp == other.rareNonInheritedData->lineClamp
425         && rareInheritedData->textSizeAdjust == other.rareInheritedData->textSizeAdjust
426         && rareInheritedData->overflowWrap == other.rareInheritedData->overflowWrap
427         && rareInheritedData->nbspMode == other.rareInheritedData->nbspMode
428         && rareInheritedData->lineBreak == other.rareInheritedData->lineBreak
429         && rareInheritedData->textSecurity == other.rareInheritedData->textSecurity
430         && inherited->specifiedLineHeight == other.inherited->specifiedLineHeight
431         && inherited->fontCascade.equalForTextAutoSizing(other.inherited->fontCascade)
432         && inherited->horizontal_border_spacing == other.inherited->horizontal_border_spacing
433         && inherited->vertical_border_spacing == other.inherited->vertical_border_spacing
434         && inherited_flags._box_direction == other.inherited_flags._box_direction
435         && inherited_flags.m_rtlOrdering == other.inherited_flags.m_rtlOrdering
436         && noninherited_flags.position() == other.noninherited_flags.position()
437         && noninherited_flags.floating() == other.noninherited_flags.floating()
438         && rareNonInheritedData->textOverflow == other.rareNonInheritedData->textOverflow;
439 }
440
441 #endif // ENABLE(TEXT_AUTOSIZING)
442
443 bool RenderStyle::inheritedDataShared(const RenderStyle* other) const
444 {
445     // This is a fast check that only looks if the data structures are shared.
446     return inherited_flags == other->inherited_flags
447         && inherited.get() == other->inherited.get()
448         && m_svgStyle.get() == other->m_svgStyle.get()
449         && rareInheritedData.get() == other->rareInheritedData.get();
450 }
451
452 static bool positionChangeIsMovementOnly(const LengthBox& a, const LengthBox& b, const Length& width)
453 {
454     // If any unit types are different, then we can't guarantee
455     // that this was just a movement.
456     if (a.left().type() != b.left().type()
457         || a.right().type() != b.right().type()
458         || a.top().type() != b.top().type()
459         || a.bottom().type() != b.bottom().type())
460         return false;
461
462     // Only one unit can be non-auto in the horizontal direction and
463     // in the vertical direction.  Otherwise the adjustment of values
464     // is changing the size of the box.
465     if (!a.left().isIntrinsicOrAuto() && !a.right().isIntrinsicOrAuto())
466         return false;
467     if (!a.top().isIntrinsicOrAuto() && !a.bottom().isIntrinsicOrAuto())
468         return false;
469     // If our width is auto and left or right is specified then this 
470     // is not just a movement - we need to resize to our container.
471     if ((!a.left().isIntrinsicOrAuto() || !a.right().isIntrinsicOrAuto()) && width.isIntrinsicOrAuto())
472         return false;
473
474     // One of the units is fixed or percent in both directions and stayed
475     // that way in the new style.  Therefore all we are doing is moving.
476     return true;
477 }
478
479 inline bool RenderStyle::changeAffectsVisualOverflow(const RenderStyle& other) const
480 {
481     if (rareNonInheritedData.get() != other.rareNonInheritedData.get()
482         && !arePointingToEqualData(rareNonInheritedData->m_boxShadow, other.rareNonInheritedData->m_boxShadow))
483         return true;
484
485     if (rareInheritedData.get() != other.rareInheritedData.get()
486         && !arePointingToEqualData(rareInheritedData->textShadow, other.rareInheritedData->textShadow))
487         return true;
488
489     if (inherited_flags._text_decorations != other.inherited_flags._text_decorations
490         || visual->textDecoration != other.visual->textDecoration
491         || rareNonInheritedData->m_textDecorationStyle != other.rareNonInheritedData->m_textDecorationStyle) {
492         // Underlines are always drawn outside of their textbox bounds when text-underline-position: under;
493         // is specified. We can take an early out here.
494         if (textUnderlinePosition() == TextUnderlinePositionUnder
495             || other.textUnderlinePosition() == TextUnderlinePositionUnder)
496             return true;
497         return visualOverflowForDecorations(*this, nullptr) != visualOverflowForDecorations(other, nullptr);
498     }
499
500     if (hasOutlineInVisualOverflow() != other.hasOutlineInVisualOverflow())
501         return true;
502     return false;
503 }
504
505 bool RenderStyle::changeRequiresLayout(const RenderStyle& other, unsigned& changedContextSensitiveProperties) const
506 {
507     if (m_box->width() != other.m_box->width()
508         || m_box->minWidth() != other.m_box->minWidth()
509         || m_box->maxWidth() != other.m_box->maxWidth()
510         || m_box->height() != other.m_box->height()
511         || m_box->minHeight() != other.m_box->minHeight()
512         || m_box->maxHeight() != other.m_box->maxHeight())
513         return true;
514
515     if (m_box->verticalAlign() != other.m_box->verticalAlign() || noninherited_flags.verticalAlign() != other.noninherited_flags.verticalAlign())
516         return true;
517
518     if (m_box->boxSizing() != other.m_box->boxSizing())
519         return true;
520
521     if (surround->margin != other.surround->margin)
522         return true;
523
524     if (surround->padding != other.surround->padding)
525         return true;
526
527     // FIXME: We should add an optimized form of layout that just recomputes visual overflow.
528     if (changeAffectsVisualOverflow(other))
529         return true;
530
531     if (rareNonInheritedData.get() != other.rareNonInheritedData.get()) {
532         if (rareNonInheritedData->m_appearance != other.rareNonInheritedData->m_appearance
533             || rareNonInheritedData->marginBeforeCollapse != other.rareNonInheritedData->marginBeforeCollapse
534             || rareNonInheritedData->marginAfterCollapse != other.rareNonInheritedData->marginAfterCollapse
535             || rareNonInheritedData->lineClamp != other.rareNonInheritedData->lineClamp
536             || rareNonInheritedData->m_initialLetter != other.rareNonInheritedData->m_initialLetter
537             || rareNonInheritedData->textOverflow != other.rareNonInheritedData->textOverflow)
538             return true;
539
540         if (rareNonInheritedData->m_regionFragment != other.rareNonInheritedData->m_regionFragment)
541             return true;
542
543         if (rareNonInheritedData->m_shapeMargin != other.rareNonInheritedData->m_shapeMargin)
544             return true;
545
546         if (rareNonInheritedData->m_deprecatedFlexibleBox != other.rareNonInheritedData->m_deprecatedFlexibleBox)
547             return true;
548
549         if (rareNonInheritedData->m_flexibleBox != other.rareNonInheritedData->m_flexibleBox)
550             return true;
551
552         if (rareNonInheritedData->m_order != other.rareNonInheritedData->m_order
553             || rareNonInheritedData->m_alignContent != other.rareNonInheritedData->m_alignContent
554             || rareNonInheritedData->m_alignItems != other.rareNonInheritedData->m_alignItems
555             || rareNonInheritedData->m_alignSelf != other.rareNonInheritedData->m_alignSelf
556             || rareNonInheritedData->m_justifyContent != other.rareNonInheritedData->m_justifyContent
557             || rareNonInheritedData->m_justifyItems != other.rareNonInheritedData->m_justifyItems
558             || rareNonInheritedData->m_justifySelf != other.rareNonInheritedData->m_justifySelf)
559             return true;
560
561         if (!arePointingToEqualData(rareNonInheritedData->m_boxReflect, other.rareNonInheritedData->m_boxReflect))
562             return true;
563
564         if (rareNonInheritedData->m_multiCol != other.rareNonInheritedData->m_multiCol)
565             return true;
566
567         if (rareNonInheritedData->m_transform != other.rareNonInheritedData->m_transform) {
568             if (rareNonInheritedData->m_transform->hasTransform() != other.rareNonInheritedData->m_transform->hasTransform())
569                 return true;
570             if (*rareNonInheritedData->m_transform != *other.rareNonInheritedData->m_transform) {
571                 changedContextSensitiveProperties |= ContextSensitivePropertyTransform;
572                 // Don't return; keep looking for another change
573             }
574         }
575
576 #if ENABLE(CSS_GRID_LAYOUT)
577         if (rareNonInheritedData->m_grid != other.rareNonInheritedData->m_grid
578             || rareNonInheritedData->m_gridItem != other.rareNonInheritedData->m_gridItem)
579             return true;
580 #endif
581
582 #if ENABLE(DASHBOARD_SUPPORT)
583         // If regions change, trigger a relayout to re-calc regions.
584         if (rareNonInheritedData->m_dashboardRegions != other.rareNonInheritedData->m_dashboardRegions)
585             return true;
586 #endif
587
588         if (!arePointingToEqualData(rareNonInheritedData->m_willChange, other.rareNonInheritedData->m_willChange)) {
589             changedContextSensitiveProperties |= ContextSensitivePropertyWillChange;
590             // Don't return; keep looking for another change
591         }
592     }
593
594     if (rareInheritedData.get() != other.rareInheritedData.get()) {
595         if (rareInheritedData->indent != other.rareInheritedData->indent
596 #if ENABLE(CSS3_TEXT)
597             || rareInheritedData->m_textAlignLast != other.rareInheritedData->m_textAlignLast
598             || rareInheritedData->m_textJustify != other.rareInheritedData->m_textJustify
599             || rareInheritedData->m_textIndentLine != other.rareInheritedData->m_textIndentLine
600 #endif
601             || rareInheritedData->m_effectiveZoom != other.rareInheritedData->m_effectiveZoom
602             || rareInheritedData->m_textZoom != other.rareInheritedData->m_textZoom
603 #if ENABLE(TEXT_AUTOSIZING)
604             || rareInheritedData->textSizeAdjust != other.rareInheritedData->textSizeAdjust
605 #endif
606             || rareInheritedData->wordBreak != other.rareInheritedData->wordBreak
607             || rareInheritedData->overflowWrap != other.rareInheritedData->overflowWrap
608             || rareInheritedData->nbspMode != other.rareInheritedData->nbspMode
609             || rareInheritedData->lineBreak != other.rareInheritedData->lineBreak
610             || rareInheritedData->textSecurity != other.rareInheritedData->textSecurity
611             || rareInheritedData->hyphens != other.rareInheritedData->hyphens
612             || rareInheritedData->hyphenationLimitBefore != other.rareInheritedData->hyphenationLimitBefore
613             || rareInheritedData->hyphenationLimitAfter != other.rareInheritedData->hyphenationLimitAfter
614             || rareInheritedData->hyphenationString != other.rareInheritedData->hyphenationString
615             || rareInheritedData->m_rubyPosition != other.rareInheritedData->m_rubyPosition
616             || rareInheritedData->textEmphasisMark != other.rareInheritedData->textEmphasisMark
617             || rareInheritedData->textEmphasisPosition != other.rareInheritedData->textEmphasisPosition
618             || rareInheritedData->textEmphasisCustomMark != other.rareInheritedData->textEmphasisCustomMark
619             || rareInheritedData->m_textOrientation != other.rareInheritedData->m_textOrientation
620             || rareInheritedData->m_tabSize != other.rareInheritedData->m_tabSize
621             || rareInheritedData->m_lineBoxContain != other.rareInheritedData->m_lineBoxContain
622             || rareInheritedData->m_lineGrid != other.rareInheritedData->m_lineGrid
623 #if ENABLE(CSS_IMAGE_ORIENTATION)
624             || rareInheritedData->m_imageOrientation != other.rareInheritedData->m_imageOrientation
625 #endif
626 #if ENABLE(CSS_IMAGE_RESOLUTION)
627             || rareInheritedData->m_imageResolutionSource != other.rareInheritedData->m_imageResolutionSource
628             || rareInheritedData->m_imageResolutionSnap != other.rareInheritedData->m_imageResolutionSnap
629             || rareInheritedData->m_imageResolution != other.rareInheritedData->m_imageResolution
630 #endif
631             || rareInheritedData->m_lineSnap != other.rareInheritedData->m_lineSnap
632             || rareInheritedData->m_lineAlign != other.rareInheritedData->m_lineAlign
633             || rareInheritedData->m_hangingPunctuation != other.rareInheritedData->m_hangingPunctuation
634 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
635             || rareInheritedData->useTouchOverflowScrolling != other.rareInheritedData->useTouchOverflowScrolling
636 #endif
637             || rareInheritedData->listStyleImage != other.rareInheritedData->listStyleImage) // FIXME: needs arePointingToEqualData()?
638             return true;
639
640         if (textStrokeWidth() != other.textStrokeWidth())
641             return true;
642     }
643
644     if (inherited->line_height != other.inherited->line_height
645 #if ENABLE(TEXT_AUTOSIZING)
646         || inherited->specifiedLineHeight != other.inherited->specifiedLineHeight
647 #endif
648         || inherited->fontCascade != other.inherited->fontCascade
649         || inherited->horizontal_border_spacing != other.inherited->horizontal_border_spacing
650         || inherited->vertical_border_spacing != other.inherited->vertical_border_spacing
651         || inherited_flags._box_direction != other.inherited_flags._box_direction
652         || inherited_flags.m_rtlOrdering != other.inherited_flags.m_rtlOrdering
653         || noninherited_flags.position() != other.noninherited_flags.position()
654         || noninherited_flags.floating() != other.noninherited_flags.floating()
655         || noninherited_flags.originalDisplay() != other.noninherited_flags.originalDisplay())
656         return true;
657
658
659     if ((noninherited_flags.effectiveDisplay()) >= TABLE) {
660         if (inherited_flags._border_collapse != other.inherited_flags._border_collapse
661             || inherited_flags._empty_cells != other.inherited_flags._empty_cells
662             || inherited_flags._caption_side != other.inherited_flags._caption_side
663             || noninherited_flags.tableLayout() != other.noninherited_flags.tableLayout())
664             return true;
665
666         // In the collapsing border model, 'hidden' suppresses other borders, while 'none'
667         // does not, so these style differences can be width differences.
668         if (inherited_flags._border_collapse
669             && ((borderTopStyle() == BHIDDEN && other.borderTopStyle() == BNONE)
670                 || (borderTopStyle() == BNONE && other.borderTopStyle() == BHIDDEN)
671                 || (borderBottomStyle() == BHIDDEN && other.borderBottomStyle() == BNONE)
672                 || (borderBottomStyle() == BNONE && other.borderBottomStyle() == BHIDDEN)
673                 || (borderLeftStyle() == BHIDDEN && other.borderLeftStyle() == BNONE)
674                 || (borderLeftStyle() == BNONE && other.borderLeftStyle() == BHIDDEN)
675                 || (borderRightStyle() == BHIDDEN && other.borderRightStyle() == BNONE)
676                 || (borderRightStyle() == BNONE && other.borderRightStyle() == BHIDDEN)))
677             return true;
678     }
679
680     if (noninherited_flags.effectiveDisplay() == LIST_ITEM) {
681         if (inherited_flags._list_style_type != other.inherited_flags._list_style_type
682             || inherited_flags._list_style_position != other.inherited_flags._list_style_position)
683             return true;
684     }
685
686     if (inherited_flags._text_align != other.inherited_flags._text_align
687         || inherited_flags._text_transform != other.inherited_flags._text_transform
688         || inherited_flags._direction != other.inherited_flags._direction
689         || inherited_flags._white_space != other.inherited_flags._white_space
690         || noninherited_flags.clear() != other.noninherited_flags.clear()
691         || noninherited_flags.unicodeBidi() != other.noninherited_flags.unicodeBidi())
692         return true;
693
694     // Check block flow direction.
695     if (inherited_flags.m_writingMode != other.inherited_flags.m_writingMode)
696         return true;
697
698     // Check text combine mode.
699     if (rareNonInheritedData->m_textCombine != other.rareNonInheritedData->m_textCombine)
700         return true;
701
702     // Check breaks.
703     if (rareNonInheritedData->m_breakBefore != other.rareNonInheritedData->m_breakBefore
704         || rareNonInheritedData->m_breakAfter != other.rareNonInheritedData->m_breakAfter
705         || rareNonInheritedData->m_breakInside != other.rareNonInheritedData->m_breakInside)
706         return true;
707
708     // Overflow returns a layout hint.
709     if (noninherited_flags.overflowX() != other.noninherited_flags.overflowX()
710         || noninherited_flags.overflowY() != other.noninherited_flags.overflowY())
711         return true;
712
713     // If our border widths change, then we need to layout.  Other changes to borders
714     // only necessitate a repaint.
715     if (borderLeftWidth() != other.borderLeftWidth()
716         || borderTopWidth() != other.borderTopWidth()
717         || borderBottomWidth() != other.borderBottomWidth()
718         || borderRightWidth() != other.borderRightWidth())
719         return true;
720
721     // If the counter directives change, trigger a relayout to re-calculate counter values and rebuild the counter node tree.
722     if (!arePointingToEqualData(rareNonInheritedData->m_counterDirectives, other.rareNonInheritedData->m_counterDirectives))
723         return true;
724
725     if ((visibility() == COLLAPSE) != (other.visibility() == COLLAPSE))
726         return true;
727
728     if (rareNonInheritedData->hasOpacity() != other.rareNonInheritedData->hasOpacity()) {
729         // FIXME: We would like to use SimplifiedLayout here, but we can't quite do that yet.
730         // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
731         // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
732         // In addition we need to solve the floating object issue when layers come and go. Right now
733         // a full layout is necessary to keep floating object lists sane.
734         return true;
735     }
736
737     if (rareNonInheritedData->hasFilters() != other.rareNonInheritedData->hasFilters())
738         return true;
739
740 #if ENABLE(FILTERS_LEVEL_2)
741     if (rareNonInheritedData->hasBackdropFilters() != other.rareNonInheritedData->hasBackdropFilters())
742         return true;
743 #endif
744
745     if (!arePointingToEqualData(rareInheritedData->quotes, other.rareInheritedData->quotes))
746         return true;
747
748     if (position() != StaticPosition) {
749         if (surround->offset != other.surround->offset) {
750             // FIXME: We would like to use SimplifiedLayout for relative positioning, but we can't quite do that yet.
751             // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
752             // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
753             if (position() != AbsolutePosition)
754                 return true;
755
756             // Optimize for the case where a positioned layer is moving but not changing size.
757             if (!positionChangeIsMovementOnly(surround->offset, other.surround->offset, m_box->width()))
758                 return true;
759         }
760     }
761
762     bool hasFirstLineStyle = hasPseudoStyle(FIRST_LINE);
763     if (hasFirstLineStyle != other.hasPseudoStyle(FIRST_LINE))
764         return true;
765     if (hasFirstLineStyle) {
766         auto* firstLineStyle = getCachedPseudoStyle(FIRST_LINE);
767         if (!firstLineStyle)
768             return true;
769         auto* otherFirstLineStyle = other.getCachedPseudoStyle(FIRST_LINE);
770         if (!otherFirstLineStyle)
771             return true;
772         // FIXME: Not all first line style changes actually need layout.
773         if (*firstLineStyle != *otherFirstLineStyle)
774             return true;
775     }
776
777     return false;
778 }
779
780 bool RenderStyle::changeRequiresPositionedLayoutOnly(const RenderStyle& other, unsigned&) const
781 {
782     if (position() == StaticPosition)
783         return false;
784
785     if (surround->offset != other.surround->offset) {
786         // Optimize for the case where a positioned layer is moving but not changing size.
787         if (position() == AbsolutePosition && positionChangeIsMovementOnly(surround->offset, other.surround->offset, m_box->width()))
788             return true;
789     }
790     
791     return false;
792 }
793
794 bool RenderStyle::changeRequiresLayerRepaint(const RenderStyle& other, unsigned& changedContextSensitiveProperties) const
795 {
796     // StyleResolver has ensured that zIndex is non-auto only if it's applicable.
797     if (m_box->zIndex() != other.m_box->zIndex() || m_box->hasAutoZIndex() != other.m_box->hasAutoZIndex())
798         return true;
799
800     if (position() != StaticPosition) {
801         if (visual->clip != other.visual->clip || visual->hasClip != other.visual->hasClip) {
802             changedContextSensitiveProperties |= ContextSensitivePropertyClipRect;
803             return true;
804         }
805     }
806
807 #if ENABLE(CSS_COMPOSITING)
808     if (rareNonInheritedData->m_effectiveBlendMode != other.rareNonInheritedData->m_effectiveBlendMode)
809         return true;
810 #endif
811
812     if (rareNonInheritedData->m_opacity != other.rareNonInheritedData->m_opacity) {
813         changedContextSensitiveProperties |= ContextSensitivePropertyOpacity;
814         // Don't return; keep looking for another change.
815     }
816
817     if (rareNonInheritedData->m_filter != other.rareNonInheritedData->m_filter) {
818         changedContextSensitiveProperties |= ContextSensitivePropertyFilter;
819         // Don't return; keep looking for another change.
820     }
821
822 #if ENABLE(FILTERS_LEVEL_2)
823     if (rareNonInheritedData->m_backdropFilter != other.rareNonInheritedData->m_backdropFilter) {
824         changedContextSensitiveProperties |= ContextSensitivePropertyFilter;
825         // Don't return; keep looking for another change.
826     }
827 #endif
828
829     if (rareNonInheritedData->m_mask != other.rareNonInheritedData->m_mask
830         || rareNonInheritedData->m_maskBoxImage != other.rareNonInheritedData->m_maskBoxImage)
831         return true;
832
833     return false;
834 }
835
836 bool RenderStyle::changeRequiresRepaint(const RenderStyle& other, unsigned& changedContextSensitiveProperties) const
837 {
838     if (inherited_flags._visibility != other.inherited_flags._visibility
839         || inherited_flags.m_printColorAdjust != other.inherited_flags.m_printColorAdjust
840         || inherited_flags._insideLink != other.inherited_flags._insideLink
841         || inherited_flags._insideDefaultButton != other.inherited_flags._insideDefaultButton
842         || surround->border != other.surround->border
843         || !m_background->isEquivalentForPainting(*other.m_background)
844         || rareInheritedData->userModify != other.rareInheritedData->userModify
845         || rareInheritedData->userSelect != other.rareInheritedData->userSelect
846         || rareNonInheritedData->userDrag != other.rareNonInheritedData->userDrag
847         || rareNonInheritedData->m_borderFit != other.rareNonInheritedData->m_borderFit
848         || rareNonInheritedData->m_objectFit != other.rareNonInheritedData->m_objectFit
849         || rareNonInheritedData->m_objectPosition != other.rareNonInheritedData->m_objectPosition
850         || rareInheritedData->m_imageRendering != other.rareInheritedData->m_imageRendering)
851         return true;
852
853     if (rareNonInheritedData->m_shapeOutside != other.rareNonInheritedData->m_shapeOutside)
854         return true;
855
856     // FIXME: this should probably be moved to changeRequiresLayerRepaint().
857     if (rareNonInheritedData->m_clipPath != other.rareNonInheritedData->m_clipPath) {
858         changedContextSensitiveProperties |= ContextSensitivePropertyClipPath;
859         // Don't return; keep looking for another change.
860     }
861
862     return false;
863 }
864
865 bool RenderStyle::changeRequiresRepaintIfTextOrBorderOrOutline(const RenderStyle& other, unsigned&) const
866 {
867     if (inherited->color != other.inherited->color
868         || inherited_flags._text_decorations != other.inherited_flags._text_decorations
869         || visual->textDecoration != other.visual->textDecoration
870         || rareNonInheritedData->m_textDecorationStyle != other.rareNonInheritedData->m_textDecorationStyle
871         || rareNonInheritedData->m_textDecorationColor != other.rareNonInheritedData->m_textDecorationColor
872         || rareInheritedData->m_textDecorationSkip != other.rareInheritedData->m_textDecorationSkip
873         || rareInheritedData->textFillColor != other.rareInheritedData->textFillColor
874         || rareInheritedData->textStrokeColor != other.rareInheritedData->textStrokeColor
875         || rareInheritedData->textEmphasisColor != other.rareInheritedData->textEmphasisColor
876         || rareInheritedData->textEmphasisFill != other.rareInheritedData->textEmphasisFill)
877         return true;
878
879     return false;
880 }
881
882 bool RenderStyle::changeRequiresRecompositeLayer(const RenderStyle& other, unsigned&) const
883 {
884     if (rareNonInheritedData.get() != other.rareNonInheritedData.get()) {
885         if (rareNonInheritedData->m_transformStyle3D != other.rareNonInheritedData->m_transformStyle3D
886             || rareNonInheritedData->m_backfaceVisibility != other.rareNonInheritedData->m_backfaceVisibility
887             || rareNonInheritedData->m_perspective != other.rareNonInheritedData->m_perspective
888             || rareNonInheritedData->m_perspectiveOriginX != other.rareNonInheritedData->m_perspectiveOriginX
889             || rareNonInheritedData->m_perspectiveOriginY != other.rareNonInheritedData->m_perspectiveOriginY)
890             return true;
891     }
892
893     return false;
894 }
895
896 StyleDifference RenderStyle::diff(const RenderStyle& other, unsigned& changedContextSensitiveProperties) const
897 {
898     changedContextSensitiveProperties = ContextSensitivePropertyNone;
899
900     StyleDifference svgChange = StyleDifferenceEqual;
901     if (m_svgStyle != other.m_svgStyle) {
902         svgChange = m_svgStyle->diff(other.m_svgStyle.get());
903         if (svgChange == StyleDifferenceLayout)
904             return svgChange;
905     }
906
907     if (changeRequiresLayout(other, changedContextSensitiveProperties))
908         return StyleDifferenceLayout;
909
910     // SVGRenderStyle::diff() might have returned StyleDifferenceRepaint, eg. if fill changes.
911     // If eg. the font-size changed at the same time, we're not allowed to return StyleDifferenceRepaint,
912     // but have to return StyleDifferenceLayout, that's why  this if branch comes after all branches
913     // that are relevant for SVG and might return StyleDifferenceLayout.
914     if (svgChange != StyleDifferenceEqual)
915         return svgChange;
916
917     if (changeRequiresPositionedLayoutOnly(other, changedContextSensitiveProperties))
918         return StyleDifferenceLayoutPositionedMovementOnly;
919
920     if (changeRequiresLayerRepaint(other, changedContextSensitiveProperties))
921         return StyleDifferenceRepaintLayer;
922
923     if (changeRequiresRepaint(other, changedContextSensitiveProperties))
924         return StyleDifferenceRepaint;
925
926     if (changeRequiresRecompositeLayer(other, changedContextSensitiveProperties))
927         return StyleDifferenceRecompositeLayer;
928
929     if (changeRequiresRepaintIfTextOrBorderOrOutline(other, changedContextSensitiveProperties))
930         return StyleDifferenceRepaintIfTextOrBorderOrOutline;
931
932     // Cursors are not checked, since they will be set appropriately in response to mouse events,
933     // so they don't need to cause any repaint or layout.
934
935     // Animations don't need to be checked either.  We always set the new style on the RenderObject, so we will get a chance to fire off
936     // the resulting transition properly.
937     return StyleDifferenceEqual;
938 }
939
940 bool RenderStyle::diffRequiresLayerRepaint(const RenderStyle& style, bool isComposited) const
941 {
942     unsigned changedContextSensitiveProperties = 0;
943
944     if (changeRequiresRepaint(style, changedContextSensitiveProperties))
945         return true;
946
947     if (isComposited && changeRequiresLayerRepaint(style, changedContextSensitiveProperties))
948         return changedContextSensitiveProperties & ContextSensitivePropertyClipRect;
949
950     return false;
951 }
952
953 void RenderStyle::setClip(Length top, Length right, Length bottom, Length left)
954 {
955     StyleVisualData* data = visual.access();
956     data->clip.top() = top;
957     data->clip.right() = right;
958     data->clip.bottom() = bottom;
959     data->clip.left() = left;
960 }
961
962 void RenderStyle::addCursor(RefPtr<StyleImage>&& image, const IntPoint& hotSpot)
963 {
964     if (!rareInheritedData.access()->cursorData)
965         rareInheritedData.access()->cursorData = CursorList::create();
966     rareInheritedData.access()->cursorData->append(CursorData(WTFMove(image), hotSpot));
967 }
968
969 void RenderStyle::setCursorList(RefPtr<CursorList>&& list)
970 {
971     rareInheritedData.access()->cursorData = WTFMove(list);
972 }
973
974 void RenderStyle::setQuotes(RefPtr<QuotesData>&& q)
975 {
976     if (rareInheritedData->quotes == q || (rareInheritedData->quotes && q && *rareInheritedData->quotes == *q))
977         return;
978
979     rareInheritedData.access()->quotes = WTFMove(q);
980 }
981
982 void RenderStyle::setWillChange(RefPtr<WillChangeData>&& willChangeData)
983 {
984     if (arePointingToEqualData(rareNonInheritedData->m_willChange.get(), willChangeData.get()))
985         return;
986
987     rareNonInheritedData.access()->m_willChange = WTFMove(willChangeData);
988 }
989
990 void RenderStyle::clearCursorList()
991 {
992     if (rareInheritedData->cursorData)
993         rareInheritedData.access()->cursorData = nullptr;
994 }
995
996 void RenderStyle::clearContent()
997 {
998     if (rareNonInheritedData->m_content)
999         rareNonInheritedData.access()->m_content = nullptr;
1000 }
1001
1002 void RenderStyle::appendContent(std::unique_ptr<ContentData> contentData)
1003 {
1004     auto& content = rareNonInheritedData.access()->m_content;
1005     ContentData* lastContent = content.get();
1006     while (lastContent && lastContent->next())
1007         lastContent = lastContent->next();
1008
1009     if (lastContent)
1010         lastContent->setNext(WTFMove(contentData));
1011     else
1012         content = WTFMove(contentData);
1013 }
1014
1015 void RenderStyle::setContent(RefPtr<StyleImage>&& image, bool add)
1016 {
1017     if (!image)
1018         return;
1019         
1020     if (add) {
1021         appendContent(std::make_unique<ImageContentData>(image));
1022         return;
1023     }
1024
1025     rareNonInheritedData.access()->m_content = std::make_unique<ImageContentData>(WTFMove(image));
1026     if (!rareNonInheritedData.access()->m_altText.isNull())
1027         rareNonInheritedData.access()->m_content->setAltText(rareNonInheritedData.access()->m_altText);
1028 }
1029
1030 void RenderStyle::setContent(const String& string, bool add)
1031 {
1032     auto& content = rareNonInheritedData.access()->m_content;
1033     if (add) {
1034         ContentData* lastContent = content.get();
1035         while (lastContent && lastContent->next())
1036             lastContent = lastContent->next();
1037
1038         if (lastContent) {
1039             // We attempt to merge with the last ContentData if possible.
1040             if (is<TextContentData>(*lastContent)) {
1041                 TextContentData& textContent = downcast<TextContentData>(*lastContent);
1042                 textContent.setText(textContent.text() + string);
1043             } else
1044                 lastContent->setNext(std::make_unique<TextContentData>(string));
1045
1046             if (!rareNonInheritedData.access()->m_altText.isNull())
1047                 lastContent->setAltText(rareNonInheritedData.access()->m_altText);
1048             return;
1049         }
1050     }
1051
1052     content = std::make_unique<TextContentData>(string);
1053     if (!rareNonInheritedData.access()->m_altText.isNull())
1054         content->setAltText(rareNonInheritedData.access()->m_altText);
1055 }
1056
1057 void RenderStyle::setContent(std::unique_ptr<CounterContent> counter, bool add)
1058 {
1059     if (!counter)
1060         return;
1061
1062     if (add) {
1063         appendContent(std::make_unique<CounterContentData>(WTFMove(counter)));
1064         return;
1065     }
1066
1067     rareNonInheritedData.access()->m_content = std::make_unique<CounterContentData>(WTFMove(counter));
1068 }
1069
1070 void RenderStyle::setContent(QuoteType quote, bool add)
1071 {
1072     if (add) {
1073         appendContent(std::make_unique<QuoteContentData>(quote));
1074         return;
1075     }
1076
1077     rareNonInheritedData.access()->m_content = std::make_unique<QuoteContentData>(quote);
1078 }
1079
1080 void RenderStyle::setContentAltText(const String& string)
1081 {
1082     rareNonInheritedData.access()->m_altText = string;
1083     
1084     if (rareNonInheritedData.access()->m_content)
1085         rareNonInheritedData.access()->m_content->setAltText(string);
1086 }
1087
1088 const String& RenderStyle::contentAltText() const
1089 {
1090     return rareNonInheritedData->m_altText;
1091 }
1092
1093 void RenderStyle::setHasAttrContent()
1094 {
1095     setUnique();
1096     SET_VAR(rareNonInheritedData, m_hasAttrContent, true);
1097 }
1098
1099 // FIXME: use affectedByTransformOrigin().
1100 static inline bool requireTransformOrigin(const Vector<RefPtr<TransformOperation>>& transformOperations, RenderStyle::ApplyTransformOrigin applyOrigin)
1101 {
1102     // transform-origin brackets the transform with translate operations.
1103     // Optimize for the case where the only transform is a translation, since the transform-origin is irrelevant
1104     // in that case.
1105     if (applyOrigin != RenderStyle::IncludeTransformOrigin)
1106         return false;
1107
1108     for (auto& operation : transformOperations) {
1109         TransformOperation::OperationType type = operation->type();
1110         if (type != TransformOperation::TRANSLATE_X
1111             && type != TransformOperation::TRANSLATE_Y
1112             && type != TransformOperation::TRANSLATE 
1113             && type != TransformOperation::TRANSLATE_Z
1114             && type != TransformOperation::TRANSLATE_3D)
1115             return true;
1116     }
1117
1118     return false;
1119 }
1120
1121 void RenderStyle::applyTransform(TransformationMatrix& transform, const FloatRect& boundingBox, ApplyTransformOrigin applyOrigin) const
1122 {
1123     auto& operations = rareNonInheritedData->m_transform->m_operations.operations();
1124     bool applyTransformOrigin = requireTransformOrigin(operations, applyOrigin);
1125
1126     float offsetX = transformOriginX().isPercent() ? boundingBox.x() : 0;
1127     float offsetY = transformOriginY().isPercent() ? boundingBox.y() : 0;
1128
1129     if (applyTransformOrigin) {
1130         transform.translate3d(floatValueForLength(transformOriginX(), boundingBox.width()) + offsetX,
1131                               floatValueForLength(transformOriginY(), boundingBox.height()) + offsetY,
1132                               transformOriginZ());
1133     }
1134
1135     for (auto& operation : operations)
1136         operation->apply(transform, boundingBox.size());
1137
1138     if (applyTransformOrigin) {
1139         transform.translate3d(-floatValueForLength(transformOriginX(), boundingBox.width()) - offsetX,
1140                               -floatValueForLength(transformOriginY(), boundingBox.height()) - offsetY,
1141                               -transformOriginZ());
1142     }
1143 }
1144
1145 void RenderStyle::setPageScaleTransform(float scale)
1146 {
1147     if (scale == 1)
1148         return;
1149     TransformOperations transform;
1150     transform.operations().append(ScaleTransformOperation::create(scale, scale, ScaleTransformOperation::SCALE));
1151     setTransform(transform);
1152     setTransformOriginX(Length(0, Fixed));
1153     setTransformOriginY(Length(0, Fixed));
1154 }
1155
1156 void RenderStyle::setTextShadow(std::unique_ptr<ShadowData> shadowData, bool add)
1157 {
1158     ASSERT(!shadowData || (!shadowData->spread() && shadowData->style() == Normal));
1159
1160     StyleRareInheritedData* rareData = rareInheritedData.access();
1161     if (!add) {
1162         rareData->textShadow = WTFMove(shadowData);
1163         return;
1164     }
1165
1166     shadowData->setNext(WTFMove(rareData->textShadow));
1167     rareData->textShadow = WTFMove(shadowData);
1168 }
1169
1170 void RenderStyle::setBoxShadow(std::unique_ptr<ShadowData> shadowData, bool add)
1171 {
1172     StyleRareNonInheritedData* rareData = rareNonInheritedData.access();
1173     if (!add) {
1174         rareData->m_boxShadow = WTFMove(shadowData);
1175         return;
1176     }
1177
1178     shadowData->setNext(WTFMove(rareData->m_boxShadow));
1179     rareData->m_boxShadow = WTFMove(shadowData);
1180 }
1181
1182 static RoundedRect::Radii calcRadiiFor(const BorderData& border, const LayoutSize& size)
1183 {
1184     return RoundedRect::Radii(
1185         LayoutSize(valueForLength(border.topLeft().width(), size.width()),
1186             valueForLength(border.topLeft().height(), size.height())),
1187         LayoutSize(valueForLength(border.topRight().width(), size.width()),
1188             valueForLength(border.topRight().height(), size.height())),
1189         LayoutSize(valueForLength(border.bottomLeft().width(), size.width()),
1190             valueForLength(border.bottomLeft().height(), size.height())),
1191         LayoutSize(valueForLength(border.bottomRight().width(), size.width()),
1192             valueForLength(border.bottomRight().height(), size.height())));
1193 }
1194
1195 StyleImage* RenderStyle::listStyleImage() const { return rareInheritedData->listStyleImage.get(); }
1196 void RenderStyle::setListStyleImage(RefPtr<StyleImage>&& v)
1197 {
1198     if (rareInheritedData->listStyleImage != v)
1199         rareInheritedData.access()->listStyleImage = WTFMove(v);
1200 }
1201
1202 const Color& RenderStyle::color() const
1203 {
1204     return inherited->color;
1205 }
1206
1207 const Color& RenderStyle::visitedLinkColor() const
1208 {
1209     return inherited->visitedLinkColor;
1210 }
1211
1212 void RenderStyle::setColor(const Color& v)
1213 {
1214     SET_VAR(inherited, color, v);
1215 }
1216
1217 void RenderStyle::setVisitedLinkColor(const Color& v)
1218 {
1219     SET_VAR(inherited, visitedLinkColor, v);
1220 }
1221
1222 float RenderStyle::horizontalBorderSpacing() const { return inherited->horizontal_border_spacing; }
1223 float RenderStyle::verticalBorderSpacing() const { return inherited->vertical_border_spacing; }
1224 void RenderStyle::setHorizontalBorderSpacing(float v) { SET_VAR(inherited, horizontal_border_spacing, v); }
1225 void RenderStyle::setVerticalBorderSpacing(float v) { SET_VAR(inherited, vertical_border_spacing, v); }
1226
1227 RoundedRect RenderStyle::getRoundedBorderFor(const LayoutRect& borderRect, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
1228 {
1229     RoundedRect roundedRect(borderRect);
1230     if (hasBorderRadius()) {
1231         RoundedRect::Radii radii = calcRadiiFor(surround->border, borderRect.size());
1232         radii.scale(calcBorderRadiiConstraintScaleFor(borderRect, radii));
1233         roundedRect.includeLogicalEdges(radii, isHorizontalWritingMode(), includeLogicalLeftEdge, includeLogicalRightEdge);
1234     }
1235     return roundedRect;
1236 }
1237
1238 RoundedRect RenderStyle::getRoundedInnerBorderFor(const LayoutRect& borderRect, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
1239 {
1240     bool horizontal = isHorizontalWritingMode();
1241
1242     LayoutUnit leftWidth = (!horizontal || includeLogicalLeftEdge) ? borderLeftWidth() : 0;
1243     LayoutUnit rightWidth = (!horizontal || includeLogicalRightEdge) ? borderRightWidth() : 0;
1244     LayoutUnit topWidth = (horizontal || includeLogicalLeftEdge) ? borderTopWidth() : 0;
1245     LayoutUnit bottomWidth = (horizontal || includeLogicalRightEdge) ? borderBottomWidth() : 0;
1246
1247     return getRoundedInnerBorderFor(borderRect, topWidth, bottomWidth, leftWidth, rightWidth, includeLogicalLeftEdge, includeLogicalRightEdge);
1248 }
1249
1250 RoundedRect RenderStyle::getRoundedInnerBorderFor(const LayoutRect& borderRect, LayoutUnit topWidth, LayoutUnit bottomWidth,
1251     LayoutUnit leftWidth, LayoutUnit rightWidth, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
1252 {
1253     LayoutRect innerRect(borderRect.x() + leftWidth, 
1254                borderRect.y() + topWidth, 
1255                borderRect.width() - leftWidth - rightWidth, 
1256                borderRect.height() - topWidth - bottomWidth);
1257
1258     RoundedRect roundedRect(innerRect);
1259
1260     if (hasBorderRadius()) {
1261         RoundedRect::Radii radii = getRoundedBorderFor(borderRect).radii();
1262         radii.shrink(topWidth, bottomWidth, leftWidth, rightWidth);
1263         roundedRect.includeLogicalEdges(radii, isHorizontalWritingMode(), includeLogicalLeftEdge, includeLogicalRightEdge);
1264     }
1265     return roundedRect;
1266 }
1267
1268 static bool allLayersAreFixed(const FillLayer* layer)
1269 {
1270     bool allFixed = true;
1271     
1272     for (const FillLayer* currLayer = layer; currLayer; currLayer = currLayer->next())
1273         allFixed &= (currLayer->image() && currLayer->attachment() == FixedBackgroundAttachment);
1274
1275     return layer && allFixed;
1276 }
1277
1278 bool RenderStyle::hasEntirelyFixedBackground() const
1279 {
1280     return allLayersAreFixed(backgroundLayers());
1281 }
1282
1283 const CounterDirectiveMap* RenderStyle::counterDirectives() const
1284 {
1285     return rareNonInheritedData->m_counterDirectives.get();
1286 }
1287
1288 CounterDirectiveMap& RenderStyle::accessCounterDirectives()
1289 {
1290     auto& map = rareNonInheritedData.access()->m_counterDirectives;
1291     if (!map)
1292         map = std::make_unique<CounterDirectiveMap>();
1293     return *map;
1294 }
1295
1296 const CounterDirectives RenderStyle::getCounterDirectives(const AtomicString& identifier) const
1297 {
1298     if (const CounterDirectiveMap* directives = counterDirectives())
1299         return directives->get(identifier);
1300     return CounterDirectives();
1301 }
1302
1303 const AtomicString& RenderStyle::hyphenString() const
1304 {
1305     ASSERT(hyphens() != HyphensNone);
1306
1307     const AtomicString& hyphenationString = rareInheritedData.get()->hyphenationString;
1308     if (!hyphenationString.isNull())
1309         return hyphenationString;
1310
1311     // FIXME: This should depend on locale.
1312     static NeverDestroyed<AtomicString> hyphenMinusString(&hyphenMinus, 1);
1313     static NeverDestroyed<AtomicString> hyphenString(&hyphen, 1);
1314     return fontCascade().primaryFont().glyphForCharacter(hyphen) ? hyphenString : hyphenMinusString;
1315 }
1316
1317 const AtomicString& RenderStyle::textEmphasisMarkString() const
1318 {
1319     switch (textEmphasisMark()) {
1320     case TextEmphasisMarkNone:
1321         return nullAtom;
1322     case TextEmphasisMarkCustom:
1323         return textEmphasisCustomMark();
1324     case TextEmphasisMarkDot: {
1325         static NeverDestroyed<AtomicString> filledDotString(&bullet, 1);
1326         static NeverDestroyed<AtomicString> openDotString(&whiteBullet, 1);
1327         return textEmphasisFill() == TextEmphasisFillFilled ? filledDotString : openDotString;
1328     }
1329     case TextEmphasisMarkCircle: {
1330         static NeverDestroyed<AtomicString> filledCircleString(&blackCircle, 1);
1331         static NeverDestroyed<AtomicString> openCircleString(&whiteCircle, 1);
1332         return textEmphasisFill() == TextEmphasisFillFilled ? filledCircleString : openCircleString;
1333     }
1334     case TextEmphasisMarkDoubleCircle: {
1335         static NeverDestroyed<AtomicString> filledDoubleCircleString(&fisheye, 1);
1336         static NeverDestroyed<AtomicString> openDoubleCircleString(&bullseye, 1);
1337         return textEmphasisFill() == TextEmphasisFillFilled ? filledDoubleCircleString : openDoubleCircleString;
1338     }
1339     case TextEmphasisMarkTriangle: {
1340         static NeverDestroyed<AtomicString> filledTriangleString(&blackUpPointingTriangle, 1);
1341         static NeverDestroyed<AtomicString> openTriangleString(&whiteUpPointingTriangle, 1);
1342         return textEmphasisFill() == TextEmphasisFillFilled ? filledTriangleString : openTriangleString;
1343     }
1344     case TextEmphasisMarkSesame: {
1345         static NeverDestroyed<AtomicString> filledSesameString(&sesameDot, 1);
1346         static NeverDestroyed<AtomicString> openSesameString(&whiteSesameDot, 1);
1347         return textEmphasisFill() == TextEmphasisFillFilled ? filledSesameString : openSesameString;
1348     }
1349     case TextEmphasisMarkAuto:
1350         ASSERT_NOT_REACHED();
1351         return nullAtom;
1352     }
1353
1354     ASSERT_NOT_REACHED();
1355     return nullAtom;
1356 }
1357
1358 #if ENABLE(DASHBOARD_SUPPORT)
1359 const Vector<StyleDashboardRegion>& RenderStyle::initialDashboardRegions()
1360 {
1361     static NeverDestroyed<Vector<StyleDashboardRegion>> emptyList;
1362     return emptyList;
1363 }
1364
1365 const Vector<StyleDashboardRegion>& RenderStyle::noneDashboardRegions()
1366 {
1367     static NeverDestroyed<Vector<StyleDashboardRegion>> noneList;
1368     static bool noneListInitialized = false;
1369
1370     if (!noneListInitialized) {
1371         StyleDashboardRegion region;
1372         region.label = emptyString();
1373         region.offset.top()  = Length();
1374         region.offset.right() = Length();
1375         region.offset.bottom() = Length();
1376         region.offset.left() = Length();
1377         region.type = StyleDashboardRegion::None;
1378         noneList.get().append(region);
1379         noneListInitialized = true;
1380     }
1381     return noneList;
1382 }
1383 #endif
1384
1385 void RenderStyle::adjustAnimations()
1386 {
1387     AnimationList* animationList = rareNonInheritedData->m_animations.get();
1388     if (!animationList)
1389         return;
1390
1391     // Get rid of empty animations and anything beyond them
1392     for (size_t i = 0; i < animationList->size(); ++i) {
1393         if (animationList->animation(i).isEmpty()) {
1394             animationList->resize(i);
1395             break;
1396         }
1397     }
1398
1399     if (animationList->isEmpty()) {
1400         clearAnimations();
1401         return;
1402     }
1403
1404     // Repeat patterns into layers that don't have some properties set.
1405     animationList->fillUnsetProperties();
1406 }
1407
1408 void RenderStyle::adjustTransitions()
1409 {
1410     AnimationList* transitionList = rareNonInheritedData->m_transitions.get();
1411     if (!transitionList)
1412         return;
1413
1414     // Get rid of empty transitions and anything beyond them
1415     for (size_t i = 0; i < transitionList->size(); ++i) {
1416         if (transitionList->animation(i).isEmpty()) {
1417             transitionList->resize(i);
1418             break;
1419         }
1420     }
1421
1422     if (transitionList->isEmpty()) {
1423         clearTransitions();
1424         return;
1425     }
1426
1427     // Repeat patterns into layers that don't have some properties set.
1428     transitionList->fillUnsetProperties();
1429
1430     // Make sure there are no duplicate properties. This is an O(n^2) algorithm
1431     // but the lists tend to be very short, so it is probably ok
1432     for (size_t i = 0; i < transitionList->size(); ++i) {
1433         for (size_t j = i+1; j < transitionList->size(); ++j) {
1434             if (transitionList->animation(i).property() == transitionList->animation(j).property()) {
1435                 // toss i
1436                 transitionList->remove(i);
1437                 j = i;
1438             }
1439         }
1440     }
1441 }
1442
1443 AnimationList& RenderStyle::ensureAnimations()
1444 {
1445     if (!rareNonInheritedData.access()->m_animations)
1446         rareNonInheritedData.access()->m_animations = std::make_unique<AnimationList>();
1447     return *rareNonInheritedData->m_animations;
1448 }
1449
1450 AnimationList& RenderStyle::ensureTransitions()
1451 {
1452     if (!rareNonInheritedData.access()->m_transitions)
1453         rareNonInheritedData.access()->m_transitions = std::make_unique<AnimationList>();
1454     return *rareNonInheritedData->m_transitions;
1455 }
1456
1457 const Animation* RenderStyle::transitionForProperty(CSSPropertyID property) const
1458 {
1459     if (transitions()) {
1460         for (size_t i = 0; i < transitions()->size(); ++i) {
1461             const Animation& p = transitions()->animation(i);
1462             if (p.animationMode() == Animation::AnimateAll || p.property() == property) {
1463                 return &p;
1464             }
1465         }
1466     }
1467     return 0;
1468 }
1469
1470 const FontCascade& RenderStyle::fontCascade() const { return inherited->fontCascade; }
1471 const FontMetrics& RenderStyle::fontMetrics() const { return inherited->fontCascade.fontMetrics(); }
1472 const FontCascadeDescription& RenderStyle::fontDescription() const { return inherited->fontCascade.fontDescription(); }
1473 float RenderStyle::specifiedFontSize() const { return fontDescription().specifiedSize(); }
1474 float RenderStyle::computedFontSize() const { return fontDescription().computedSize(); }
1475 int RenderStyle::fontSize() const { return inherited->fontCascade.pixelSize(); }
1476
1477 const Length& RenderStyle::wordSpacing() const { return rareInheritedData->wordSpacing; }
1478 float RenderStyle::letterSpacing() const { return inherited->fontCascade.letterSpacing(); }
1479
1480 bool RenderStyle::setFontDescription(const FontCascadeDescription& v)
1481 {
1482     if (inherited->fontCascade.fontDescription() != v) {
1483         inherited.access()->fontCascade = FontCascade(v, inherited->fontCascade.letterSpacing(), inherited->fontCascade.wordSpacing());
1484         return true;
1485     }
1486     return false;
1487 }
1488
1489 #if ENABLE(TEXT_AUTOSIZING)
1490 const Length& RenderStyle::specifiedLineHeight() const { return inherited->specifiedLineHeight; }
1491 void RenderStyle::setSpecifiedLineHeight(Length v) { SET_VAR(inherited, specifiedLineHeight, v); }
1492 #else
1493 const Length& RenderStyle::specifiedLineHeight() const { return inherited->line_height; }
1494 #endif
1495
1496 Length RenderStyle::lineHeight() const
1497 {
1498     return inherited->line_height;
1499 }
1500 void RenderStyle::setLineHeight(Length specifiedLineHeight) { SET_VAR(inherited, line_height, specifiedLineHeight); }
1501
1502 int RenderStyle::computedLineHeight() const
1503 {
1504     const Length& lh = lineHeight();
1505
1506     // Negative value means the line height is not set. Use the font's built-in spacing.
1507     if (lh.isNegative())
1508         return fontMetrics().lineSpacing();
1509
1510     if (lh.isPercentOrCalculated())
1511         return minimumValueForLength(lh, fontSize());
1512
1513     return clampTo<int>(lh.value());
1514 }
1515
1516 void RenderStyle::setWordSpacing(Length value)
1517 {
1518     float fontWordSpacing;
1519     switch (value.type()) {
1520     case Auto:
1521         fontWordSpacing = 0;
1522         break;
1523     case Percent:
1524         fontWordSpacing = value.percent() * fontCascade().spaceWidth() / 100;
1525         break;
1526     case Fixed:
1527         fontWordSpacing = value.value();
1528         break;
1529     case Calculated:
1530         fontWordSpacing = value.nonNanCalculatedValue(maxValueForCssLength);
1531         break;
1532     default:
1533         ASSERT_NOT_REACHED();
1534         fontWordSpacing = 0;
1535         break;
1536     }
1537     inherited.access()->fontCascade.setWordSpacing(fontWordSpacing);
1538     rareInheritedData.access()->wordSpacing = WTFMove(value);
1539 }
1540
1541 void RenderStyle::setLetterSpacing(float v) { inherited.access()->fontCascade.setLetterSpacing(v); }
1542
1543 void RenderStyle::setFontSize(float size)
1544 {
1545     // size must be specifiedSize if Text Autosizing is enabled, but computedSize if text
1546     // zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
1547
1548     ASSERT(std::isfinite(size));
1549     if (!std::isfinite(size) || size < 0)
1550         size = 0;
1551     else
1552         size = std::min(maximumAllowedFontSize, size);
1553
1554     FontSelector* currentFontSelector = fontCascade().fontSelector();
1555     auto description = fontDescription();
1556     description.setSpecifiedSize(size);
1557     description.setComputedSize(size);
1558
1559     setFontDescription(description);
1560     fontCascade().update(currentFontSelector);
1561 }
1562
1563 #if ENABLE(VARIATION_FONTS)
1564 void RenderStyle::setFontVariationSettings(FontVariationSettings settings)
1565 {
1566     FontSelector* currentFontSelector = fontCascade().fontSelector();
1567     auto description = fontDescription();
1568     description.setVariationSettings(WTFMove(settings));
1569
1570     setFontDescription(description);
1571     fontCascade().update(currentFontSelector);
1572 }
1573 #endif
1574
1575 void RenderStyle::getShadowExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &right, LayoutUnit &bottom, LayoutUnit &left) const
1576 {
1577     top = 0;
1578     right = 0;
1579     bottom = 0;
1580     left = 0;
1581
1582     for ( ; shadow; shadow = shadow->next()) {
1583         if (shadow->style() == Inset)
1584             continue;
1585
1586         int extentAndSpread = shadow->paintingExtent() + shadow->spread();
1587         top = std::min<LayoutUnit>(top, shadow->y() - extentAndSpread);
1588         right = std::max<LayoutUnit>(right, shadow->x() + extentAndSpread);
1589         bottom = std::max<LayoutUnit>(bottom, shadow->y() + extentAndSpread);
1590         left = std::min<LayoutUnit>(left, shadow->x() - extentAndSpread);
1591     }
1592 }
1593
1594 LayoutBoxExtent RenderStyle::getShadowInsetExtent(const ShadowData* shadow) const
1595 {
1596     LayoutUnit top = 0;
1597     LayoutUnit right = 0;
1598     LayoutUnit bottom = 0;
1599     LayoutUnit left = 0;
1600
1601     for ( ; shadow; shadow = shadow->next()) {
1602         if (shadow->style() == Normal)
1603             continue;
1604
1605         int extentAndSpread = shadow->paintingExtent() + shadow->spread();
1606         top = std::max<LayoutUnit>(top, shadow->y() + extentAndSpread);
1607         right = std::min<LayoutUnit>(right, shadow->x() - extentAndSpread);
1608         bottom = std::min<LayoutUnit>(bottom, shadow->y() - extentAndSpread);
1609         left = std::max<LayoutUnit>(left, shadow->x() + extentAndSpread);
1610     }
1611
1612     return LayoutBoxExtent(top, right, bottom, left);
1613 }
1614
1615 void RenderStyle::getShadowHorizontalExtent(const ShadowData* shadow, LayoutUnit &left, LayoutUnit &right) const
1616 {
1617     left = 0;
1618     right = 0;
1619
1620     for ( ; shadow; shadow = shadow->next()) {
1621         if (shadow->style() == Inset)
1622             continue;
1623
1624         int extentAndSpread = shadow->paintingExtent() + shadow->spread();
1625         left = std::min<LayoutUnit>(left, shadow->x() - extentAndSpread);
1626         right = std::max<LayoutUnit>(right, shadow->x() + extentAndSpread);
1627     }
1628 }
1629
1630 void RenderStyle::getShadowVerticalExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &bottom) const
1631 {
1632     top = 0;
1633     bottom = 0;
1634
1635     for ( ; shadow; shadow = shadow->next()) {
1636         if (shadow->style() == Inset)
1637             continue;
1638
1639         int extentAndSpread = shadow->paintingExtent() + shadow->spread();
1640         top = std::min<LayoutUnit>(top, shadow->y() - extentAndSpread);
1641         bottom = std::max<LayoutUnit>(bottom, shadow->y() + extentAndSpread);
1642     }
1643 }
1644
1645 Color RenderStyle::colorIncludingFallback(int colorProperty, bool visitedLink) const
1646 {
1647     Color result;
1648     EBorderStyle borderStyle = BNONE;
1649     switch (colorProperty) {
1650     case CSSPropertyBackgroundColor:
1651         return visitedLink ? visitedLinkBackgroundColor() : backgroundColor(); // Background color doesn't fall back.
1652     case CSSPropertyBorderLeftColor:
1653         result = visitedLink ? visitedLinkBorderLeftColor() : borderLeftColor();
1654         borderStyle = borderLeftStyle();
1655         break;
1656     case CSSPropertyBorderRightColor:
1657         result = visitedLink ? visitedLinkBorderRightColor() : borderRightColor();
1658         borderStyle = borderRightStyle();
1659         break;
1660     case CSSPropertyBorderTopColor:
1661         result = visitedLink ? visitedLinkBorderTopColor() : borderTopColor();
1662         borderStyle = borderTopStyle();
1663         break;
1664     case CSSPropertyBorderBottomColor:
1665         result = visitedLink ? visitedLinkBorderBottomColor() : borderBottomColor();
1666         borderStyle = borderBottomStyle();
1667         break;
1668     case CSSPropertyColor:
1669         result = visitedLink ? visitedLinkColor() : color();
1670         break;
1671     case CSSPropertyOutlineColor:
1672         result = visitedLink ? visitedLinkOutlineColor() : outlineColor();
1673         break;
1674     case CSSPropertyColumnRuleColor:
1675         result = visitedLink ? visitedLinkColumnRuleColor() : columnRuleColor();
1676         break;
1677     case CSSPropertyWebkitTextDecorationColor:
1678         // Text decoration color fallback is handled in RenderObject::decorationColor.
1679         return visitedLink ? visitedLinkTextDecorationColor() : textDecorationColor();
1680     case CSSPropertyWebkitTextEmphasisColor:
1681         result = visitedLink ? visitedLinkTextEmphasisColor() : textEmphasisColor();
1682         break;
1683     case CSSPropertyWebkitTextFillColor:
1684         result = visitedLink ? visitedLinkTextFillColor() : textFillColor();
1685         break;
1686     case CSSPropertyWebkitTextStrokeColor:
1687         result = visitedLink ? visitedLinkTextStrokeColor() : textStrokeColor();
1688         break;
1689     default:
1690         ASSERT_NOT_REACHED();
1691         break;
1692     }
1693
1694     if (!result.isValid()) {
1695         if (!visitedLink && (borderStyle == INSET || borderStyle == OUTSET || borderStyle == RIDGE || borderStyle == GROOVE))
1696             result = Color(238, 238, 238);
1697         else
1698             result = visitedLink ? visitedLinkColor() : color();
1699     }
1700     return result;
1701 }
1702
1703 Color RenderStyle::visitedDependentColor(int colorProperty) const
1704 {
1705     Color unvisitedColor = colorIncludingFallback(colorProperty, false);
1706     if (insideLink() != InsideVisitedLink)
1707         return unvisitedColor;
1708
1709     Color visitedColor = colorIncludingFallback(colorProperty, true);
1710
1711     // Text decoration color validity is preserved (checked in RenderObject::decorationColor).
1712     if (colorProperty == CSSPropertyWebkitTextDecorationColor)
1713         return visitedColor;
1714
1715     // FIXME: Technically someone could explicitly specify the color transparent, but for now we'll just
1716     // assume that if the background color is transparent that it wasn't set. Note that it's weird that
1717     // we're returning unvisited info for a visited link, but given our restriction that the alpha values
1718     // have to match, it makes more sense to return the unvisited background color if specified than it
1719     // does to return black. This behavior matches what Firefox 4 does as well.
1720     if (colorProperty == CSSPropertyBackgroundColor && visitedColor == Color::transparent)
1721         return unvisitedColor;
1722
1723     // Take the alpha from the unvisited color, but get the RGB values from the visited color.
1724     return visitedColor.colorWithAlpha(unvisitedColor.alphaAsFloat());
1725 }
1726
1727 const BorderValue& RenderStyle::borderBefore() const
1728 {
1729     switch (writingMode()) {
1730     case TopToBottomWritingMode:
1731         return borderTop();
1732     case BottomToTopWritingMode:
1733         return borderBottom();
1734     case LeftToRightWritingMode:
1735         return borderLeft();
1736     case RightToLeftWritingMode:
1737         return borderRight();
1738     }
1739     ASSERT_NOT_REACHED();
1740     return borderTop();
1741 }
1742
1743 const BorderValue& RenderStyle::borderAfter() const
1744 {
1745     switch (writingMode()) {
1746     case TopToBottomWritingMode:
1747         return borderBottom();
1748     case BottomToTopWritingMode:
1749         return borderTop();
1750     case LeftToRightWritingMode:
1751         return borderRight();
1752     case RightToLeftWritingMode:
1753         return borderLeft();
1754     }
1755     ASSERT_NOT_REACHED();
1756     return borderBottom();
1757 }
1758
1759 const BorderValue& RenderStyle::borderStart() const
1760 {
1761     if (isHorizontalWritingMode())
1762         return isLeftToRightDirection() ? borderLeft() : borderRight();
1763     return isLeftToRightDirection() ? borderTop() : borderBottom();
1764 }
1765
1766 const BorderValue& RenderStyle::borderEnd() const
1767 {
1768     if (isHorizontalWritingMode())
1769         return isLeftToRightDirection() ? borderRight() : borderLeft();
1770     return isLeftToRightDirection() ? borderBottom() : borderTop();
1771 }
1772
1773 float RenderStyle::borderBeforeWidth() const
1774 {
1775     switch (writingMode()) {
1776     case TopToBottomWritingMode:
1777         return borderTopWidth();
1778     case BottomToTopWritingMode:
1779         return borderBottomWidth();
1780     case LeftToRightWritingMode:
1781         return borderLeftWidth();
1782     case RightToLeftWritingMode:
1783         return borderRightWidth();
1784     }
1785     ASSERT_NOT_REACHED();
1786     return borderTopWidth();
1787 }
1788
1789 float RenderStyle::borderAfterWidth() const
1790 {
1791     switch (writingMode()) {
1792     case TopToBottomWritingMode:
1793         return borderBottomWidth();
1794     case BottomToTopWritingMode:
1795         return borderTopWidth();
1796     case LeftToRightWritingMode:
1797         return borderRightWidth();
1798     case RightToLeftWritingMode:
1799         return borderLeftWidth();
1800     }
1801     ASSERT_NOT_REACHED();
1802     return borderBottomWidth();
1803 }
1804
1805 float RenderStyle::borderStartWidth() const
1806 {
1807     if (isHorizontalWritingMode())
1808         return isLeftToRightDirection() ? borderLeftWidth() : borderRightWidth();
1809     return isLeftToRightDirection() ? borderTopWidth() : borderBottomWidth();
1810 }
1811
1812 float RenderStyle::borderEndWidth() const
1813 {
1814     if (isHorizontalWritingMode())
1815         return isLeftToRightDirection() ? borderRightWidth() : borderLeftWidth();
1816     return isLeftToRightDirection() ? borderBottomWidth() : borderTopWidth();
1817 }
1818
1819 void RenderStyle::setMarginStart(Length margin)
1820 {
1821     if (isHorizontalWritingMode()) {
1822         if (isLeftToRightDirection())
1823             setMarginLeft(margin);
1824         else
1825             setMarginRight(margin);
1826     } else {
1827         if (isLeftToRightDirection())
1828             setMarginTop(margin);
1829         else
1830             setMarginBottom(margin);
1831     }
1832 }
1833
1834 void RenderStyle::setMarginEnd(Length margin)
1835 {
1836     if (isHorizontalWritingMode()) {
1837         if (isLeftToRightDirection())
1838             setMarginRight(margin);
1839         else
1840             setMarginLeft(margin);
1841     } else {
1842         if (isLeftToRightDirection())
1843             setMarginBottom(margin);
1844         else
1845             setMarginTop(margin);
1846     }
1847 }
1848
1849 TextEmphasisMark RenderStyle::textEmphasisMark() const
1850 {
1851     TextEmphasisMark mark = static_cast<TextEmphasisMark>(rareInheritedData->textEmphasisMark);
1852     if (mark != TextEmphasisMarkAuto)
1853         return mark;
1854
1855     if (isHorizontalWritingMode())
1856         return TextEmphasisMarkDot;
1857
1858     return TextEmphasisMarkSesame;
1859 }
1860
1861 #if ENABLE(TOUCH_EVENTS)
1862 Color RenderStyle::initialTapHighlightColor()
1863 {
1864     return RenderTheme::tapHighlightColor();
1865 }
1866 #endif
1867
1868 LayoutBoxExtent RenderStyle::imageOutsets(const NinePieceImage& image) const
1869 {
1870     return LayoutBoxExtent(NinePieceImage::computeOutset(image.outset().top(), borderTopWidth()),
1871                            NinePieceImage::computeOutset(image.outset().right(), borderRightWidth()),
1872                            NinePieceImage::computeOutset(image.outset().bottom(), borderBottomWidth()),
1873                            NinePieceImage::computeOutset(image.outset().left(), borderLeftWidth()));
1874 }
1875
1876 std::pair<FontOrientation, NonCJKGlyphOrientation> RenderStyle::fontAndGlyphOrientation()
1877 {
1878     // FIXME: TextOrientationSideways should map to sideways-left in vertical-lr, which is not supported yet.
1879
1880     if (isHorizontalWritingMode())
1881         return { Horizontal, NonCJKGlyphOrientation::Mixed };
1882
1883     switch (textOrientation()) {
1884     case TextOrientation::Mixed:
1885         return { Vertical, NonCJKGlyphOrientation::Mixed };
1886     case TextOrientation::Upright:
1887         return { Vertical, NonCJKGlyphOrientation::Upright };
1888     case TextOrientation::Sideways:
1889         return { Horizontal, NonCJKGlyphOrientation::Mixed };
1890     default:
1891         ASSERT_NOT_REACHED();
1892         return { Horizontal, NonCJKGlyphOrientation::Mixed };
1893     }
1894 }
1895
1896 void RenderStyle::setBorderImageSource(RefPtr<StyleImage>&& image)
1897 {
1898     if (surround->border.m_image.image() == image.get())
1899         return;
1900     surround.access()->border.m_image.setImage(WTFMove(image));
1901 }
1902
1903 void RenderStyle::setBorderImageSlices(LengthBox slices)
1904 {
1905     if (surround->border.m_image.imageSlices() == slices)
1906         return;
1907     surround.access()->border.m_image.setImageSlices(slices);
1908 }
1909
1910 void RenderStyle::setBorderImageWidth(LengthBox slices)
1911 {
1912     if (surround->border.m_image.borderSlices() == slices)
1913         return;
1914     surround.access()->border.m_image.setBorderSlices(slices);
1915 }
1916
1917 void RenderStyle::setBorderImageOutset(LengthBox outset)
1918 {
1919     if (surround->border.m_image.outset() == outset)
1920         return;
1921     surround.access()->border.m_image.setOutset(outset);
1922 }
1923
1924 void RenderStyle::setColumnStylesFromPaginationMode(const Pagination::Mode& paginationMode)
1925 {
1926     if (paginationMode == Pagination::Unpaginated)
1927         return;
1928     
1929     setColumnFill(ColumnFillAuto);
1930     
1931     switch (paginationMode) {
1932     case Pagination::LeftToRightPaginated:
1933         setColumnAxis(HorizontalColumnAxis);
1934         if (isHorizontalWritingMode())
1935             setColumnProgression(isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1936         else
1937             setColumnProgression(isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1938         break;
1939     case Pagination::RightToLeftPaginated:
1940         setColumnAxis(HorizontalColumnAxis);
1941         if (isHorizontalWritingMode())
1942             setColumnProgression(isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1943         else
1944             setColumnProgression(isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1945         break;
1946     case Pagination::TopToBottomPaginated:
1947         setColumnAxis(VerticalColumnAxis);
1948         if (isHorizontalWritingMode())
1949             setColumnProgression(isFlippedBlocksWritingMode() ? ReverseColumnProgression : NormalColumnProgression);
1950         else
1951             setColumnProgression(isLeftToRightDirection() ? NormalColumnProgression : ReverseColumnProgression);
1952         break;
1953     case Pagination::BottomToTopPaginated:
1954         setColumnAxis(VerticalColumnAxis);
1955         if (isHorizontalWritingMode())
1956             setColumnProgression(isFlippedBlocksWritingMode() ? NormalColumnProgression : ReverseColumnProgression);
1957         else
1958             setColumnProgression(isLeftToRightDirection() ? ReverseColumnProgression : NormalColumnProgression);
1959         break;
1960     case Pagination::Unpaginated:
1961         ASSERT_NOT_REACHED();
1962         break;
1963     }
1964 }
1965
1966 #if ENABLE(CSS_SCROLL_SNAP)
1967 LengthSize RenderStyle::initialScrollSnapDestination()
1968 {
1969     return defaultScrollSnapDestination();
1970 }
1971
1972 Vector<LengthSize> RenderStyle::initialScrollSnapCoordinates()
1973 {
1974     return Vector<LengthSize>();
1975 }
1976
1977 const ScrollSnapPoints* RenderStyle::scrollSnapPointsX() const
1978 {
1979     return rareNonInheritedData->m_scrollSnapPoints->xPoints.get();
1980 }
1981
1982 const ScrollSnapPoints* RenderStyle::scrollSnapPointsY() const
1983 {
1984     return rareNonInheritedData->m_scrollSnapPoints->yPoints.get();
1985 }
1986
1987 const LengthSize& RenderStyle::scrollSnapDestination() const
1988 {
1989     return rareNonInheritedData->m_scrollSnapPoints->destination;
1990 }
1991
1992 const Vector<LengthSize>& RenderStyle::scrollSnapCoordinates() const
1993 {
1994     return rareNonInheritedData->m_scrollSnapPoints->coordinates;
1995 }
1996
1997 void RenderStyle::setScrollSnapPointsX(std::unique_ptr<ScrollSnapPoints> points)
1998 {
1999     if (rareNonInheritedData->m_scrollSnapPoints->xPoints.get() == points.get())
2000         return;
2001     rareNonInheritedData.access()->m_scrollSnapPoints.access()->xPoints = WTFMove(points);
2002 }
2003
2004 void RenderStyle::setScrollSnapPointsY(std::unique_ptr<ScrollSnapPoints> points)
2005 {
2006     if (rareNonInheritedData->m_scrollSnapPoints->yPoints.get() == points.get())
2007         return;
2008     rareNonInheritedData.access()->m_scrollSnapPoints.access()->yPoints = WTFMove(points);
2009 }
2010
2011 void RenderStyle::setScrollSnapDestination(LengthSize destination)
2012 {
2013     if (rareNonInheritedData->m_scrollSnapPoints->destination == destination)
2014         return;
2015     rareNonInheritedData.access()->m_scrollSnapPoints.access()->destination = WTFMove(destination);
2016 }
2017
2018 void RenderStyle::setScrollSnapCoordinates(Vector<LengthSize> coordinates)
2019 {
2020     if (rareNonInheritedData->m_scrollSnapPoints->coordinates == coordinates)
2021         return;
2022     rareNonInheritedData.access()->m_scrollSnapPoints.access()->coordinates = WTFMove(coordinates);
2023 }
2024
2025 #endif
2026
2027 bool RenderStyle::hasReferenceFilterOnly() const
2028 {
2029     if (!hasFilter())
2030         return false;
2031
2032     const FilterOperations& filterOperations = rareNonInheritedData->m_filter->m_operations;
2033     if (filterOperations.size() != 1)
2034         return false;
2035
2036     const FilterOperation& filterOperation = *filterOperations.at(0);
2037     if (filterOperation.type() != FilterOperation::REFERENCE)
2038         return false;
2039
2040     return true;
2041 }
2042
2043 void RenderStyle::checkVariablesInCustomProperties()
2044 {
2045     if (!rareInheritedData->m_customProperties->containsVariables())
2046         return;
2047     
2048     // Our first pass checks the variables for validity and replaces any properties that became
2049     // invalid with empty values.
2050     auto& customProperties = rareInheritedData.access()->m_customProperties.access()->values();
2051     HashSet<AtomicString> invalidProperties;
2052     for (auto entry : customProperties) {
2053         if (!entry.value->containsVariables())
2054             continue;
2055         HashSet<AtomicString> seenProperties;
2056         entry.value->checkVariablesForCycles(entry.key, customProperties, seenProperties, invalidProperties);
2057     }
2058     
2059     // Now insert invalid values.
2060     if (!invalidProperties.isEmpty()) {
2061         auto invalidValue = CSSCustomPropertyValue::createInvalid();
2062         for (auto& property : invalidProperties)
2063             customProperties.set(property, invalidValue.copyRef());
2064     }
2065
2066     // Now that all of the properties have been tested for validity and replaced with
2067     // invalid values if they failed, we can perform variable substitution on the valid values.
2068     Vector<Ref<CSSCustomPropertyValue>> resolvedValues;
2069     for (auto entry : customProperties) {
2070         if (!entry.value->containsVariables())
2071             continue;
2072         entry.value->resolveVariableReferences(customProperties, resolvedValues);
2073     }
2074     
2075     // With all results computed, we can now mutate our table to eliminate the variables and
2076     // hold the final values. This way when we inherit, we don't end up resubstituting variables, etc.
2077     for (auto& resolvedValue : resolvedValues)
2078         customProperties.set(resolvedValue->name(), resolvedValue.copyRef());
2079
2080     rareInheritedData.access()->m_customProperties.access()->setContainsVariables(false);
2081 }
2082
2083 float RenderStyle::outlineWidth() const
2084 {
2085     if (m_background->outline().style() == BNONE)
2086         return 0;
2087     if (outlineStyleIsAuto())
2088         return std::max(m_background->outline().width(), RenderTheme::platformFocusRingWidth());
2089     return m_background->outline().width();
2090 }
2091
2092 float RenderStyle::outlineOffset() const
2093 {
2094     if (m_background->outline().style() == BNONE)
2095         return 0;
2096     if (outlineStyleIsAuto())
2097         return (m_background->outline().offset() + RenderTheme::platformFocusRingOffset(outlineWidth()));
2098     return m_background->outline().offset();
2099 }
2100
2101 bool RenderStyle::shouldPlaceBlockDirectionScrollbarOnLeft() const
2102 {
2103     return !isLeftToRightDirection() && isHorizontalWritingMode();
2104 }
2105
2106 } // namespace WebCore