RenderFlowThread's containing block cache should be invalidated before calling styleD...
[WebKit-https.git] / Source / WebCore / rendering / RenderElement.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013, 2015 Apple Inc. All rights reserved.
7  * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "RenderElement.h"
27
28 #include "AXObjectCache.h"
29 #include "ContentData.h"
30 #include "CursorList.h"
31 #include "ElementChildIterator.h"
32 #include "EventHandler.h"
33 #include "FlowThreadController.h"
34 #include "FocusController.h"
35 #include "Frame.h"
36 #include "FrameSelection.h"
37 #include "HTMLAnchorElement.h"
38 #include "HTMLBodyElement.h"
39 #include "HTMLHtmlElement.h"
40 #include "HTMLImageElement.h"
41 #include "HTMLNames.h"
42 #include "Logging.h"
43 #include "Page.h"
44 #include "PathUtilities.h"
45 #include "RenderBlock.h"
46 #include "RenderChildIterator.h"
47 #include "RenderCounter.h"
48 #include "RenderDeprecatedFlexibleBox.h"
49 #include "RenderFlexibleBox.h"
50 #include "RenderImage.h"
51 #include "RenderImageResourceStyleImage.h"
52 #include "RenderInline.h"
53 #include "RenderIterator.h"
54 #include "RenderLayer.h"
55 #include "RenderLayerCompositor.h"
56 #include "RenderLineBreak.h"
57 #include "RenderListItem.h"
58 #include "RenderNamedFlowThread.h"
59 #include "RenderRegion.h"
60 #include "RenderTableCaption.h"
61 #include "RenderTableCell.h"
62 #include "RenderTableCol.h"
63 #include "RenderTableRow.h"
64 #include "RenderText.h"
65 #include "RenderTheme.h"
66 #include "RenderView.h"
67 #include "SVGRenderSupport.h"
68 #include "Settings.h"
69 #include "ShadowRoot.h"
70 #include "StylePendingResources.h"
71 #include "StyleResolver.h"
72 #include <wtf/MathExtras.h>
73 #include <wtf/StackStats.h>
74
75 #if ENABLE(CSS_GRID_LAYOUT)
76 #include "RenderGrid.h"
77 #endif
78
79 namespace WebCore {
80
81 struct SameSizeAsRenderElement : public RenderObject {
82     uint8_t bitfields0;
83     uint8_t bitfields1;
84     uint8_t bitfields2;
85     void* firstChild;
86     void* lastChild;
87     RenderStyle style;
88 };
89
90 static_assert(sizeof(RenderElement) == sizeof(SameSizeAsRenderElement), "RenderElement should stay small");
91
92 bool RenderElement::s_affectsParentBlock = false;
93 bool RenderElement::s_noLongerAffectsParentBlock = false;
94     
95 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
96     : RenderObject(elementOrDocument)
97     , m_baseTypeFlags(baseTypeFlags)
98     , m_ancestorLineBoxDirty(false)
99     , m_hasInitializedStyle(false)
100     , m_renderInlineAlwaysCreatesLineBoxes(false)
101     , m_renderBoxNeedsLazyRepaint(false)
102     , m_hasPausedImageAnimations(false)
103     , m_hasCounterNodeMap(false)
104     , m_isCSSAnimating(false)
105     , m_hasContinuation(false)
106     , m_renderBlockHasMarginBeforeQuirk(false)
107     , m_renderBlockHasMarginAfterQuirk(false)
108     , m_renderBlockShouldForceRelayoutChildren(false)
109     , m_renderBlockFlowHasMarkupTruncation(false)
110     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
111     , m_firstChild(nullptr)
112     , m_lastChild(nullptr)
113     , m_style(WTFMove(style))
114 {
115 }
116
117 RenderElement::RenderElement(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
118     : RenderElement(static_cast<ContainerNode&>(element), WTFMove(style), baseTypeFlags)
119 {
120 }
121
122 RenderElement::RenderElement(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
123     : RenderElement(static_cast<ContainerNode&>(document), WTFMove(style), baseTypeFlags)
124 {
125 }
126
127 RenderElement::~RenderElement()
128 {
129     if (hasInitializedStyle()) {
130         for (const FillLayer* bgLayer = m_style.backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
131             if (StyleImage* backgroundImage = bgLayer->image())
132                 backgroundImage->removeClient(this);
133         }
134
135         for (const FillLayer* maskLayer = m_style.maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
136             if (StyleImage* maskImage = maskLayer->image())
137                 maskImage->removeClient(this);
138         }
139
140         if (StyleImage* borderImage = m_style.borderImage().image())
141             borderImage->removeClient(this);
142
143         if (StyleImage* maskBoxImage = m_style.maskBoxImage().image())
144             maskBoxImage->removeClient(this);
145
146         if (auto shapeValue = m_style.shapeOutside()) {
147             if (auto shapeImage = shapeValue->image())
148                 shapeImage->removeClient(this);
149         }
150     }
151     if (m_hasPausedImageAnimations)
152         view().removeRendererWithPausedImageAnimations(*this);
153     if (isRegisteredForVisibleInViewportCallback())
154         view().unregisterForVisibleInViewportCallback(*this);
155 }
156
157 RenderPtr<RenderElement> RenderElement::createFor(Element& element, RenderStyle&& style)
158 {
159     // Minimal support for content properties replacing an entire element.
160     // Works only if we have exactly one piece of content and it's a URL.
161     // Otherwise acts as if we didn't support this feature.
162     const ContentData* contentData = style.contentData();
163     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
164         Style::loadPendingResources(style, element.document(), &element);
165         auto& styleImage = downcast<ImageContentData>(*contentData).image();
166         auto image = createRenderer<RenderImage>(element, WTFMove(style), const_cast<StyleImage*>(&styleImage));
167         image->setIsGeneratedContent();
168         return WTFMove(image);
169     }
170
171     switch (style.display()) {
172     case NONE:
173     case CONTENTS:
174         return nullptr;
175     case INLINE:
176         return createRenderer<RenderInline>(element, WTFMove(style));
177     case BLOCK:
178     case INLINE_BLOCK:
179     case COMPACT:
180         return createRenderer<RenderBlockFlow>(element, WTFMove(style));
181     case LIST_ITEM:
182         return createRenderer<RenderListItem>(element, WTFMove(style));
183     case TABLE:
184     case INLINE_TABLE:
185         return createRenderer<RenderTable>(element, WTFMove(style));
186     case TABLE_ROW_GROUP:
187     case TABLE_HEADER_GROUP:
188     case TABLE_FOOTER_GROUP:
189         return createRenderer<RenderTableSection>(element, WTFMove(style));
190     case TABLE_ROW:
191         return createRenderer<RenderTableRow>(element, WTFMove(style));
192     case TABLE_COLUMN_GROUP:
193     case TABLE_COLUMN:
194         return createRenderer<RenderTableCol>(element, WTFMove(style));
195     case TABLE_CELL:
196         return createRenderer<RenderTableCell>(element, WTFMove(style));
197     case TABLE_CAPTION:
198         return createRenderer<RenderTableCaption>(element, WTFMove(style));
199     case BOX:
200     case INLINE_BOX:
201         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTFMove(style));
202     case FLEX:
203     case INLINE_FLEX:
204     case WEBKIT_FLEX:
205     case WEBKIT_INLINE_FLEX:
206         return createRenderer<RenderFlexibleBox>(element, WTFMove(style));
207 #if ENABLE(CSS_GRID_LAYOUT)
208     case GRID:
209     case INLINE_GRID:
210         return createRenderer<RenderGrid>(element, WTFMove(style));
211 #endif
212     }
213     ASSERT_NOT_REACHED();
214     return nullptr;
215 }
216
217 std::unique_ptr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
218 {
219     if (!view().usesFirstLineRules())
220         return nullptr;
221
222     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
223
224     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
225         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock())
226             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == this ? style : nullptr);
227     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
228         auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
229         if (&parentStyle != &rendererForFirstLineStyle.parent()->style())
230             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
231     }
232     return nullptr;
233 }
234
235 const RenderStyle* RenderElement::cachedFirstLineStyle() const
236 {
237     ASSERT(view().usesFirstLineRules());
238
239     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
240
241     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
242         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock())
243             return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, &style());
244     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
245         auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
246         if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
247             // A first-line style is in effect. Cache a first-line style for ourselves.
248             rendererForFirstLineStyle.m_style.setHasPseudoStyle(FIRST_LINE_INHERITED);
249             return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
250         }
251     }
252
253     return &style();
254 }
255
256 const RenderStyle& RenderElement::firstLineStyle() const
257 {
258     return view().usesFirstLineRules() ? *cachedFirstLineStyle() : style();
259 }
260
261 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
262 {
263     // If transform changed, and we are not composited, need to do a layout.
264     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
265         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
266         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
267             if (!hasLayer())
268                 diff = std::max(diff, StyleDifferenceLayout);
269             else {
270                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
271                 // then we actually need SimplifiedLayoutAndPositionedMovement.
272                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
273             }
274         
275         } else
276             diff = std::max(diff, StyleDifferenceRecompositeLayer);
277     }
278
279     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
280         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
281             diff = std::max(diff, StyleDifferenceRepaintLayer);
282         else
283             diff = std::max(diff, StyleDifferenceRecompositeLayer);
284     }
285
286     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
287         if (hasLayer()
288             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
289             && hasClipPath()
290             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
291             diff = std::max(diff, StyleDifferenceRecompositeLayer);
292         else
293             diff = std::max(diff, StyleDifferenceRepaint);
294     }
295     
296     if (contextSensitiveProperties & ContextSensitivePropertyWillChange) {
297         if (style().willChange() && style().willChange()->canTriggerCompositing())
298             diff = std::max(diff, StyleDifferenceRecompositeLayer);
299     }
300     
301     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
302         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
303         if (!layer->isComposited() || layer->paintsWithFilters())
304             diff = std::max(diff, StyleDifferenceRepaintLayer);
305         else
306             diff = std::max(diff, StyleDifferenceRecompositeLayer);
307     }
308     
309     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
310     // style changing, since it depends on whether we decide to composite these elements. When the
311     // layer status of one of these elements changes, we need to force a layout.
312     if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
313         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
314             diff = StyleDifferenceLayout;
315     }
316
317     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
318     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
319         diff = StyleDifferenceRepaint;
320
321     return diff;
322 }
323
324 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
325 {
326     for (auto& child : childrenOfType<RenderObject>(*this)) {
327         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
328             return true;
329         if (child.style().hasOutline() || child.style().hasBorder())
330             return true;
331     }
332     return false;
333 }
334
335 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
336 {
337     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
338 }
339
340 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
341 {
342     // Optimize the common case
343     if (FillLayer::imagesIdentical(oldLayers, newLayers))
344         return;
345     
346     // Go through the new layers and addClients first, to avoid removing all clients of an image.
347     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
348         if (currNew->image())
349             currNew->image()->addClient(this);
350     }
351
352     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
353         if (currOld->image())
354             currOld->image()->removeClient(this);
355     }
356 }
357
358 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
359 {
360     if (oldImage == newImage)
361         return;
362     if (oldImage)
363         oldImage->removeClient(this);
364     if (newImage)
365         newImage->addClient(this);
366 }
367
368 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
369 {
370     if (oldShapeValue || newShapeValue)
371         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
372 }
373
374 void RenderElement::initializeStyle()
375 {
376     Style::loadPendingResources(m_style, document(), element());
377
378     styleWillChange(StyleDifferenceNewStyle, style());
379     m_hasInitializedStyle = true;
380     styleDidChange(StyleDifferenceNewStyle, nullptr);
381
382     // We shouldn't have any text children that would need styleDidChange at this point.
383     ASSERT(!childrenOfType<RenderText>(*this).first());
384
385     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
386     // have their parent set before getting a call to initializeStyle() :|
387 }
388
389 void RenderElement::setStyle(RenderStyle&& style, StyleDifference minimalStyleDifference)
390 {
391     // FIXME: Should change RenderView so it can use initializeStyle too.
392     // If we do that, we can assert m_hasInitializedStyle unconditionally,
393     // and remove the check of m_hasInitializedStyle below too.
394     ASSERT(m_hasInitializedStyle || isRenderView());
395
396     StyleDifference diff = StyleDifferenceEqual;
397     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
398     if (m_hasInitializedStyle)
399         diff = m_style.diff(style, contextSensitiveProperties);
400
401     diff = std::max(diff, minimalStyleDifference);
402
403     diff = adjustStyleDifference(diff, contextSensitiveProperties);
404
405     Style::loadPendingResources(style, document(), element());
406
407     styleWillChange(diff, style);
408     auto oldStyle = WTFMove(m_style);
409     m_style = WTFMove(style);
410     bool detachedFromParent = !parent();
411
412     // Make sure we invalidate the containing block cache for flows when the contianing block context changes
413     // so that styleDidChange can safely use RenderBlock::locateFlowThreadContainingBlock()
414     if (is<RenderBlock>(*this) && oldStyle.position() != m_style.position())
415         downcast<RenderBlock>(*this).resetFlowThreadContainingBlockAndChildInfoIncludingDescendants();
416
417     styleDidChange(diff, &oldStyle);
418
419     // Text renderers use their parent style. Notify them about the change.
420     for (auto& child : childrenOfType<RenderText>(*this))
421         child.styleDidChange(diff, &oldStyle);
422
423     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
424     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
425     // we will safely bail out with the detachedFromParent flag. We might want to broaden this condition
426     // in the future as we move renderer changes out of layout and into style changes.
427     if (detachedFromParent)
428         return;
429
430     // Now that the layer (if any) has been updated, we need to adjust the diff again,
431     // check whether we should layout now, and decide if we need to repaint.
432     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
433     
434     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
435         if (updatedDiff == StyleDifferenceLayout)
436             setNeedsLayoutAndPrefWidthsRecalc();
437         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
438             setNeedsPositionedMovementLayout(&oldStyle);
439         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
440             setNeedsPositionedMovementLayout(&oldStyle);
441             setNeedsSimplifiedNormalFlowLayout();
442         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
443             setNeedsSimplifiedNormalFlowLayout();
444     }
445
446     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
447         // Do a repaint with the new style now, e.g., for example if we go from
448         // not having an outline to having an outline.
449         repaint();
450     }
451 }
452
453 bool RenderElement::childRequiresTable(const RenderObject& child) const
454 {
455     if (is<RenderTableCol>(child)) {
456         const RenderTableCol& newTableColumn = downcast<RenderTableCol>(child);
457         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
458         return !is<RenderTable>(*this) && !isColumnInColumnGroup;
459     }
460     if (is<RenderTableCaption>(child))
461         return !is<RenderTable>(*this);
462
463     if (is<RenderTableSection>(child))
464         return !is<RenderTable>(*this);
465
466     if (is<RenderTableRow>(child))
467         return !is<RenderTableSection>(*this);
468
469     if (is<RenderTableCell>(child))
470         return !is<RenderTableRow>(*this);
471
472     return false;
473 }
474
475 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
476 {
477     if (childRequiresTable(*newChild)) {
478         RenderTable* table;
479         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
480         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
481             table = downcast<RenderTable>(afterChild);
482         else {
483             table = RenderTable::createAnonymousWithParentRenderer(*this).release();
484             addChild(table, beforeChild);
485         }
486         table->addChild(newChild);
487     } else
488         insertChildInternal(newChild, beforeChild, NotifyChildren);
489
490     if (is<RenderText>(*newChild))
491         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
492
493     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
494     // <g>s to have renderers - at least that's how our implementation works. Consider:
495     // <g display="none"><foreignObject><body style="position: relative">FOO...
496     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
497     // - when the document is painted, both layers are painted. The <body> layer doesn't
498     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
499     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
500     // and stop creating layers at all for these cases - they're not used anyways.
501     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
502         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
503
504     SVGRenderSupport::childAdded(*this, *newChild);
505 }
506
507 void RenderElement::removeChild(RenderObject& oldChild)
508 {
509     removeChildInternal(oldChild, NotifyChildren);
510 }
511
512 void RenderElement::destroyLeftoverChildren()
513 {
514     while (m_firstChild) {
515         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
516             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
517         } else {
518             // Destroy any anonymous children remaining in the render tree, as well as implicit (shadow) DOM elements like those used in the engine-based text fields.
519             if (m_firstChild->node())
520                 m_firstChild->node()->setRenderer(nullptr);
521             m_firstChild->destroy();
522         }
523     }
524 }
525
526 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
527 {
528     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
529     ASSERT(!newChild->parent());
530     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
531
532     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
533         beforeChild = beforeChild->parent();
534
535     // This should never happen, but if it does prevent render tree corruption
536     // where child->parent() ends up being owner but child->nextSibling()->parent()
537     // is not owner.
538     if (beforeChild && beforeChild->parent() != this) {
539         ASSERT_NOT_REACHED();
540         return;
541     }
542
543     newChild->setParent(this);
544
545     if (m_firstChild == beforeChild)
546         m_firstChild = newChild;
547
548     if (beforeChild) {
549         RenderObject* previousSibling = beforeChild->previousSibling();
550         if (previousSibling)
551             previousSibling->setNextSibling(newChild);
552         newChild->setPreviousSibling(previousSibling);
553         newChild->setNextSibling(beforeChild);
554         beforeChild->setPreviousSibling(newChild);
555     } else {
556         if (lastChild())
557             lastChild()->setNextSibling(newChild);
558         newChild->setPreviousSibling(lastChild());
559         m_lastChild = newChild;
560     }
561
562     newChild->initializeFlowThreadStateOnInsertion();
563     if (!documentBeingDestroyed()) {
564         if (notifyChildren == NotifyChildren)
565             newChild->insertedIntoTree();
566         if (is<RenderElement>(*newChild))
567             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
568     }
569
570     newChild->setNeedsLayoutAndPrefWidthsRecalc();
571     setPreferredLogicalWidthsDirty(true);
572     if (!normalChildNeedsLayout())
573         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
574
575     if (AXObjectCache* cache = document().axObjectCache())
576         cache->childrenChanged(this, newChild);
577     if (is<RenderBlockFlow>(*this))
578         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
579     if (hasOutlineAutoAncestor() || outlineStyleForRepaint().outlineStyleIsAuto())
580         newChild->setHasOutlineAutoAncestor();
581 }
582
583 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
584 {
585     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
586     ASSERT(oldChild.parent() == this);
587
588     if (oldChild.isFloatingOrOutOfFlowPositioned())
589         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
590
591     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
592     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
593     // disappears gets repainted properly.
594     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
595         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
596         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
597         if (oldChild.isBody())
598             view().repaintRootContents();
599         else
600             oldChild.repaint();
601     }
602
603     // If we have a line box wrapper, delete it.
604     if (is<RenderBox>(oldChild))
605         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
606     else if (is<RenderLineBreak>(oldChild))
607         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
608
609     // If oldChild is the start or end of the selection, then clear the selection to
610     // avoid problems of invalid pointers.
611     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
612         frame().selection().setNeedsSelectionUpdate();
613
614     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
615         oldChild.willBeRemovedFromTree();
616
617     oldChild.resetFlowThreadStateOnRemoval();
618
619     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
620     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
621     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
622     
623     RenderObject* nextSibling = oldChild.nextSibling();
624
625     if (oldChild.previousSibling())
626         oldChild.previousSibling()->setNextSibling(nextSibling);
627     if (nextSibling)
628         nextSibling->setPreviousSibling(oldChild.previousSibling());
629
630     if (m_firstChild == &oldChild)
631         m_firstChild = nextSibling;
632     if (m_lastChild == &oldChild)
633         m_lastChild = oldChild.previousSibling();
634
635     oldChild.setPreviousSibling(nullptr);
636     oldChild.setNextSibling(nullptr);
637     oldChild.setParent(nullptr);
638
639     // rendererRemovedFromTree walks the whole subtree. We can improve performance
640     // by skipping this step when destroying the entire tree.
641     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
642         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
643
644     if (AXObjectCache* cache = document().existingAXObjectCache())
645         cache->childrenChanged(this);
646 }
647
648 RenderBlock* RenderElement::containingBlockForFixedPosition() const
649 {
650     auto* renderer = parent();
651     while (renderer && !renderer->canContainFixedPositionObjects())
652         renderer = renderer->parent();
653
654     ASSERT(!renderer || !renderer->isAnonymousBlock());
655     return downcast<RenderBlock>(renderer);
656 }
657
658 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
659 {
660     // A relatively positioned RenderInline forwards its absolute positioned descendants to
661     // its nearest non-anonymous containing block (to avoid having a positioned objects list in all RenderInlines).
662     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
663     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
664         renderer = renderer->parent();
665     // Make sure we only return non-anonymous RenderBlock as containing block.
666     while (renderer && (!is<RenderBlock>(*renderer) || renderer->isAnonymousBlock()))
667         renderer = renderer->containingBlock();
668     return downcast<RenderBlock>(renderer);
669 }
670
671 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
672 {
673     if (renderer.hasLayer()) {
674         if (!beforeChild && newObject) {
675             // We need to figure out the layer that follows newObject. We only do
676             // this the first time we find a child layer, and then we update the
677             // pointer values for newObject and beforeChild used by everyone else.
678             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
679             newObject = nullptr;
680         }
681         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
682         return;
683     }
684
685     for (auto& child : childrenOfType<RenderElement>(renderer))
686         addLayers(child, parentLayer, newObject, beforeChild);
687 }
688
689 void RenderElement::addLayers(RenderLayer* parentLayer)
690 {
691     if (!parentLayer)
692         return;
693
694     RenderElement* renderer = this;
695     RenderLayer* beforeChild = nullptr;
696     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
697 }
698
699 void RenderElement::removeLayers(RenderLayer* parentLayer)
700 {
701     if (!parentLayer)
702         return;
703
704     if (hasLayer()) {
705         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
706         return;
707     }
708
709     for (auto& child : childrenOfType<RenderElement>(*this))
710         child.removeLayers(parentLayer);
711 }
712
713 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
714 {
715     if (!newParent)
716         return;
717
718     if (hasLayer()) {
719         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
720         ASSERT(oldParent == layer->parent());
721         if (oldParent)
722             oldParent->removeChild(layer);
723         newParent->addChild(layer);
724         return;
725     }
726
727     for (auto& child : childrenOfType<RenderElement>(*this))
728         child.moveLayers(oldParent, newParent);
729 }
730
731 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
732 {
733     // Error check the parent layer passed in. If it's null, we can't find anything.
734     if (!parentLayer)
735         return nullptr;
736
737     // Step 1: If our layer is a child of the desired parent, then return our layer.
738     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
739     if (ourLayer && ourLayer->parent() == parentLayer)
740         return ourLayer;
741
742     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
743     // into our siblings trying to find the next layer whose parent is the desired parent.
744     if (!ourLayer || ourLayer == parentLayer) {
745         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
746             if (!is<RenderElement>(*child))
747                 continue;
748             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
749             if (nextLayer)
750                 return nextLayer;
751         }
752     }
753
754     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
755     // find anything.
756     if (parentLayer == ourLayer)
757         return nullptr;
758
759     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
760     // follow us to see if we can locate a layer.
761     if (checkParent && parent())
762         return parent()->findNextLayer(parentLayer, this, true);
763
764     return nullptr;
765 }
766
767 bool RenderElement::layerCreationAllowedForSubtree() const
768 {
769     RenderElement* parentRenderer = parent();
770     while (parentRenderer) {
771         if (parentRenderer->isSVGHiddenContainer())
772             return false;
773         parentRenderer = parentRenderer->parent();
774     }
775     
776     return true;
777 }
778
779 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
780 {
781     // FIXME: We could save this call when the change only affected non-inherited properties.
782     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
783         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
784             continue;
785
786         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
787             continue;
788
789 #if ENABLE(FULLSCREEN_API)
790         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
791             continue;
792 #endif
793
794         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
795         if (is<RenderFlowThread>(elementChild))
796             continue;
797
798         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style().display());
799         if (style().specifiesColumns()) {
800             if (elementChild.style().specifiesColumns())
801                 newStyle.inheritColumnPropertiesFrom(&style());
802             if (elementChild.style().columnSpan())
803                 newStyle.setColumnSpan(ColumnSpanAll);
804         }
805
806         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
807         // they contain block descendants of relative or sticky positioned inlines.
808         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
809             newStyle.setPosition(elementChild.style().position());
810
811         elementChild.setStyle(WTFMove(newStyle));
812     }
813 }
814
815 static inline bool rendererHasBackground(const RenderElement* renderer)
816 {
817     return renderer && renderer->hasBackground();
818 }
819
820 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
821 {
822     auto* oldStyle = hasInitializedStyle() ? &style() : nullptr;
823     if (oldStyle) {
824         // If our z-index changes value or our visibility changes,
825         // we need to dirty our stacking context's z-order list.
826         bool visibilityChanged = m_style.visibility() != newStyle.visibility()
827             || m_style.zIndex() != newStyle.zIndex()
828             || m_style.hasAutoZIndex() != newStyle.hasAutoZIndex();
829 #if ENABLE(DASHBOARD_SUPPORT)
830         if (visibilityChanged)
831             document().setAnnotatedRegionsDirty(true);
832 #endif
833 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
834         if (visibilityChanged)
835             document().dirtyTouchEventRects();
836 #endif
837         if (visibilityChanged) {
838             if (AXObjectCache* cache = document().existingAXObjectCache())
839                 cache->childrenChanged(parent(), this);
840         }
841
842         // Keep layer hierarchy visibility bits up to date if visibility changes.
843         if (m_style.visibility() != newStyle.visibility()) {
844             if (RenderLayer* layer = enclosingLayer()) {
845                 if (newStyle.visibility() == VISIBLE)
846                     layer->setHasVisibleContent();
847                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
848                     layer->dirtyVisibleContentStatus();
849                     if (diff > StyleDifferenceRepaintLayer)
850                         repaint();
851                 }
852             }
853         }
854
855         if (m_parent && (newStyle.outlineSize() < m_style.outlineSize() || shouldRepaintForStyleDifference(diff)))
856             repaint();
857         if (isFloating() && m_style.floating() != newStyle.floating()) {
858             // For changes in float styles, we need to conceivably remove ourselves
859             // from the floating objects list.
860             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
861         } else if (isOutOfFlowPositioned() && m_style.position() != newStyle.position()) {
862             // For changes in positioning styles, we need to conceivably remove ourselves
863             // from the positioned objects list.
864             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
865         }
866
867         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
868             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
869             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
870
871         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
872             && parent() && parent()->isRenderBlock();
873
874         // reset style flags
875         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
876             setFloating(false);
877             clearPositionedState();
878         }
879         setHorizontalWritingMode(true);
880         setHasVisibleBoxDecorations(false);
881         setHasOverflowClip(false);
882         setHasTransformRelatedProperty(false);
883         setHasReflection(false);
884     } else {
885         s_affectsParentBlock = false;
886         s_noLongerAffectsParentBlock = false;
887     }
888
889     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
890     bool oldStyleUsesFixedBackgrounds = m_style.hasFixedBackgroundImage();
891     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
892         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
893
894         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
895         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
896         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
897         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
898             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
899                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
900                     newStyleSlowScroll = false;
901
902                 if (oldStyleSlowScroll && m_style.hasEntirelyFixedBackground())
903                     oldStyleSlowScroll = false;
904             }
905         }
906
907         if (oldStyleSlowScroll != newStyleSlowScroll) {
908             if (oldStyleSlowScroll)
909                 view().frameView().removeSlowRepaintObject(this);
910
911             if (newStyleSlowScroll)
912                 view().frameView().addSlowRepaintObject(this);
913         }
914     }
915
916     if (isDocumentElementRenderer() || isBody())
917         view().frameView().updateExtendBackgroundIfNecessary();
918 }
919
920 void RenderElement::handleDynamicFloatPositionChange()
921 {
922     // We have gone from not affecting the inline status of the parent flow to suddenly
923     // having an impact.  See if there is a mismatch between the parent flow's
924     // childrenInline() state and our state.
925     setInline(style().isDisplayInlineType());
926     if (isInline() != parent()->childrenInline()) {
927         if (!isInline())
928             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
929         else {
930             // An anonymous block must be made to wrap this inline.
931             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
932             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
933             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
934             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
935         }
936     }
937 }
938
939 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
940 {
941     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
942     if (!parentBlock.canDropAnonymousBlockChild())
943         return;
944
945     // We have changed to floated or out-of-flow positioning so maybe all our parent's
946     // children can be inline now. Bail if there are any block children left on the line,
947     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
948     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
949     // if we find a continuation.
950     RenderObject* current = parent()->firstChild();
951     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
952         current = current->nextSibling();
953
954     if (current)
955         return;
956
957     RenderObject* next;
958     for (current = parent()->firstChild(); current; current = next) {
959         next = current->nextSibling();
960         if (current->isAnonymousBlock())
961             parentBlock.dropAnonymousBoxChild(parentBlock, downcast<RenderBlock>(*current));
962     }
963 }
964
965 #if !PLATFORM(IOS)
966 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
967 {
968     ASSERT(a->cursors() != b->cursors());
969     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
970 }
971
972 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
973 {
974     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
975 }
976 #endif
977
978 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
979 {
980     updateFillImages(oldStyle ? oldStyle->backgroundLayers() : nullptr, m_style.backgroundLayers());
981     updateFillImages(oldStyle ? oldStyle->maskLayers() : nullptr, m_style.maskLayers());
982     updateImage(oldStyle ? oldStyle->borderImage().image() : nullptr, m_style.borderImage().image());
983     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : nullptr, m_style.maskBoxImage().image());
984     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : nullptr, m_style.shapeOutside());
985
986     if (s_affectsParentBlock)
987         handleDynamicFloatPositionChange();
988
989     if (s_noLongerAffectsParentBlock) {
990         removeAnonymousWrappersForInlinesIfNecessary();
991         // Fresh floats need to be reparented if they actually belong to the previous anonymous block.
992         // It copies the logic of RenderBlock::addChildIgnoringContinuation
993         if (style().isFloating() && previousSibling() && previousSibling()->isAnonymousBlock())
994             downcast<RenderBoxModelObject>(*parent()).moveChildTo(&downcast<RenderBoxModelObject>(*previousSibling()), this);
995     }
996
997     SVGRenderSupport::styleChanged(*this, oldStyle);
998
999     if (!m_parent)
1000         return;
1001     
1002     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1003         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style);
1004
1005         // If the object already needs layout, then setNeedsLayout won't do
1006         // any work. But if the containing block has changed, then we may need
1007         // to mark the new containing blocks for layout. The change that can
1008         // directly affect the containing block of this object is a change to
1009         // the position style.
1010         if (needsLayout() && oldStyle->position() != m_style.position())
1011             markContainingBlocksForLayout();
1012
1013         if (diff == StyleDifferenceLayout)
1014             setNeedsLayoutAndPrefWidthsRecalc();
1015         else
1016             setNeedsSimplifiedNormalFlowLayout();
1017     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1018         setNeedsPositionedMovementLayout(oldStyle);
1019         setNeedsSimplifiedNormalFlowLayout();
1020     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1021         setNeedsPositionedMovementLayout(oldStyle);
1022
1023     // Don't check for repaint here; we need to wait until the layer has been
1024     // updated by subclasses before we know if we have to repaint (in setStyle()).
1025
1026 #if !PLATFORM(IOS)
1027     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1028         frame().eventHandler().scheduleCursorUpdate();
1029 #endif
1030     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
1031     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
1032     if (hasOutlineAuto != hadOutlineAuto) {
1033         updateOutlineAutoAncestor(hasOutlineAuto);
1034         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
1035     }
1036 }
1037
1038 void RenderElement::insertedIntoTree()
1039 {
1040     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1041     // and don't have a layer attached to ourselves.
1042     RenderLayer* layer = nullptr;
1043     if (firstChild() || hasLayer()) {
1044         layer = parent()->enclosingLayer();
1045         addLayers(layer);
1046     }
1047
1048     // If |this| is visible but this object was not, tell the layer it has some visible content
1049     // that needs to be drawn and layer visibility optimization can't be used
1050     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1051         if (!layer)
1052             layer = parent()->enclosingLayer();
1053         if (layer)
1054             layer->setHasVisibleContent();
1055     }
1056
1057     RenderObject::insertedIntoTree();
1058 }
1059
1060 void RenderElement::willBeRemovedFromTree()
1061 {
1062     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1063     RenderLayer* layer = nullptr;
1064     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1065         if ((layer = parent()->enclosingLayer()))
1066             layer->dirtyVisibleContentStatus();
1067     }
1068     // Keep our layer hierarchy updated.
1069     if (firstChild() || hasLayer()) {
1070         if (!layer)
1071             layer = parent()->enclosingLayer();
1072         removeLayers(layer);
1073     }
1074
1075     if (m_style.hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1076         view().frameView().removeSlowRepaintObject(this);
1077
1078     if (isOutOfFlowPositioned() && parent()->childrenInline())
1079         parent()->dirtyLinesFromChangedChild(*this);
1080
1081     RenderObject::willBeRemovedFromTree();
1082 }
1083
1084 inline void RenderElement::clearLayoutRootIfNeeded() const
1085 {
1086     if (documentBeingDestroyed())
1087         return;
1088
1089     if (view().frameView().layoutRoot() != this)
1090         return;
1091
1092     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1093     // which ensures that this renderer is no longer the layout root.
1094     ASSERT_NOT_REACHED();
1095     
1096     // This indicates a failure to layout the child, which is why
1097     // the layout root is still set to |this|. Make sure to clear it
1098     // since we are getting destroyed.
1099     view().frameView().clearLayoutRoot();
1100 }
1101
1102 void RenderElement::willBeDestroyed()
1103 {
1104     animation().cancelAnimations(*this);
1105
1106     destroyLeftoverChildren();
1107
1108     if (hasCounterNodeMap())
1109         RenderCounter::destroyCounterNodes(*this);
1110
1111     RenderObject::willBeDestroyed();
1112
1113 #if !ASSERT_DISABLED
1114     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1115         // After remove, the object and the associated information should not be in any flow thread.
1116         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1117             ASSERT(!flowThread->hasChildInfo(this));
1118         }
1119     }
1120 #endif
1121     clearLayoutRootIfNeeded();
1122 }
1123
1124 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1125 {
1126     ASSERT(!isSetNeedsLayoutForbidden());
1127     if (needsPositionedMovementLayout())
1128         return;
1129     setNeedsPositionedMovementLayoutBit(true);
1130     markContainingBlocksForLayout();
1131     if (hasLayer()) {
1132         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1133             setLayerNeedsFullRepaint();
1134         else
1135             setLayerNeedsFullRepaintForPositionedMovementLayout();
1136     }
1137 }
1138
1139 void RenderElement::clearChildNeedsLayout()
1140 {
1141     setNormalChildNeedsLayoutBit(false);
1142     setPosChildNeedsLayoutBit(false);
1143     setNeedsSimplifiedNormalFlowLayoutBit(false);
1144     setNormalChildNeedsLayoutBit(false);
1145     setNeedsPositionedMovementLayoutBit(false);
1146 }
1147
1148 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1149 {
1150     ASSERT(!isSetNeedsLayoutForbidden());
1151     if (needsSimplifiedNormalFlowLayout())
1152         return;
1153     setNeedsSimplifiedNormalFlowLayoutBit(true);
1154     markContainingBlocksForLayout();
1155     if (hasLayer())
1156         setLayerNeedsFullRepaint();
1157 }
1158
1159 RenderElement& RenderElement::rendererForRootBackground()
1160 {
1161     ASSERT(isDocumentElementRenderer());
1162     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1163         // Locate the <body> element using the DOM. This is easier than trying
1164         // to crawl around a render tree with potential :before/:after content and
1165         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1166         // render object very easily via the DOM.
1167         if (auto* body = document().body()) {
1168             if (auto* renderer = body->renderer())
1169                 return *renderer;
1170         }
1171     }
1172     return *this;
1173 }
1174
1175 RenderElement* RenderElement::hoverAncestor() const
1176 {
1177     // When searching for the hover ancestor and encountering a named flow thread,
1178     // the search will continue with the DOM ancestor of the top-most element
1179     // in the named flow thread.
1180     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1181     RenderElement* hoverAncestor = parent();
1182
1183     // Skip anonymous blocks directly flowed into flow threads as it would
1184     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1185     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1186         hoverAncestor = hoverAncestor->parent();
1187
1188     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1189         hoverAncestor = nullptr;
1190         if (Element* element = this->element()) {
1191             if (auto parent = element->parentNode())
1192                 hoverAncestor = parent->renderer();
1193         }
1194     }
1195
1196     return hoverAncestor;
1197 }
1198
1199 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1200 {
1201     paintInfo.phase = phase;
1202     element.paint(paintInfo, childPoint);
1203 }
1204
1205 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1206 {
1207     // Paint all phases atomically, as though the element established its own stacking context.
1208     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1209     // This is also used by other elements (e.g. flex items and grid items).
1210     if (paintInfo.phase == PaintPhaseSelection) {
1211         paint(paintInfo, childPoint);
1212     } else if (paintInfo.phase == PaintPhaseForeground) {
1213         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1214         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1215         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1216         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1217         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1218
1219         // Reset |paintInfo| to the original phase.
1220         paintInfo.phase = PaintPhaseForeground;
1221     }
1222 }
1223
1224 void RenderElement::layout()
1225 {
1226     StackStats::LayoutCheckPoint layoutCheckPoint;
1227     ASSERT(needsLayout());
1228     RenderObject* child = firstChild();
1229     while (child) {
1230         if (child->needsLayout())
1231             downcast<RenderElement>(*child).layout();
1232         ASSERT(!child->needsLayout());
1233         child = child->nextSibling();
1234     }
1235     clearNeedsLayout();
1236 }
1237
1238 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1239 {
1240     // Nobody will use multiple layers without wanting fancy positioning.
1241     if (layer->next())
1242         return true;
1243
1244     // Make sure we have a valid image.
1245     StyleImage* image = layer->image();
1246     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1247         return false;
1248
1249     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1250         return true;
1251
1252     EFillSizeType sizeType = layer->sizeType();
1253
1254     if (sizeType == Contain || sizeType == Cover)
1255         return true;
1256
1257     if (sizeType == SizeLength) {
1258         LengthSize size = layer->sizeLength();
1259         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1260             return true;
1261         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1262         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1263             return true;
1264     } else if (image->usesImageContainerSize())
1265         return true;
1266
1267     return false;
1268 }
1269
1270 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1271 {
1272     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1273         return true;
1274
1275     // If we don't have a background/border/mask, then nothing to do.
1276     if (!renderer.hasVisibleBoxDecorations())
1277         return false;
1278
1279     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1280         return true;
1281
1282     // Our fill layers are ok. Let's check border.
1283     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1284         return true;
1285
1286     return false;
1287 }
1288
1289 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1290 {
1291     if (view().printing())
1292         return false; // Don't repaint if we're printing.
1293
1294     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1295     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1296     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1297     LayoutRect newOutlineBox;
1298
1299     bool fullRepaint = selfNeedsLayout();
1300     // Presumably a background or a border exists if border-fit:lines was specified.
1301     if (!fullRepaint && style().borderFit() == BorderFitLines)
1302         fullRepaint = true;
1303     if (!fullRepaint) {
1304         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1305         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1306         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1307         fullRepaint = (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)));
1308     }
1309
1310     if (!repaintContainer)
1311         repaintContainer = &view();
1312
1313     if (fullRepaint) {
1314         repaintUsingContainer(repaintContainer, oldBounds);
1315         if (newBounds != oldBounds)
1316             repaintUsingContainer(repaintContainer, newBounds);
1317         return true;
1318     }
1319
1320     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1321         return false;
1322
1323     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1324     if (deltaLeft > 0)
1325         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1326     else if (deltaLeft < 0)
1327         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1328
1329     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1330     if (deltaRight > 0)
1331         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1332     else if (deltaRight < 0)
1333         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1334
1335     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1336     if (deltaTop > 0)
1337         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1338     else if (deltaTop < 0)
1339         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1340
1341     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1342     if (deltaBottom > 0)
1343         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1344     else if (deltaBottom < 0)
1345         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1346
1347     if (newOutlineBox == oldOutlineBox)
1348         return false;
1349
1350     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1351     // two rectangles (but typically only one).
1352     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1353     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1354     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1355     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1356     if (width) {
1357         LayoutUnit shadowLeft;
1358         LayoutUnit shadowRight;
1359         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1360         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1361         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1362         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1363         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1364         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1365         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1366             newOutlineBox.y(),
1367             width + decorationsWidth,
1368             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1369         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1370         if (rightRect.x() < right) {
1371             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1372             repaintUsingContainer(repaintContainer, rightRect);
1373         }
1374     }
1375     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1376     if (height) {
1377         LayoutUnit shadowTop;
1378         LayoutUnit shadowBottom;
1379         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1380         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1381         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1382         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1383         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1384             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1385         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1386         LayoutRect bottomRect(newOutlineBox.x(),
1387             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1388             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1389             height + decorationsHeight);
1390         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1391         if (bottomRect.y() < bottom) {
1392             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1393             repaintUsingContainer(repaintContainer, bottomRect);
1394         }
1395     }
1396     return false;
1397 }
1398
1399 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1400 {
1401     ASSERT(style().hasBorder());
1402
1403     StyleImage* borderImage = style().borderImage().image();
1404     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1405 }
1406
1407 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1408 {
1409     auto& frameView = view().frameView();
1410     if (frameView.isOffscreen())
1411         return false;
1412
1413     if (!hasOverflowClip()) {
1414         // FIXME: Computing the overflow rect is expensive if any descendant has
1415         // its own self-painting layer. As a result, we prefer to abort early in
1416         // this case and assume it may cause us to repaint inside the viewport.
1417         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1418             return true;
1419     }
1420
1421     // Compute viewport rect if it was not provided.
1422     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1423     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1424 }
1425
1426 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1427 {
1428     const Document& document = renderer.document();
1429     if (document.pageCacheState() != Document::NotInPageCache)
1430         return false;
1431     if (document.activeDOMObjectsAreSuspended())
1432         return false;
1433     if (renderer.style().visibility() != VISIBLE)
1434         return false;
1435     if (renderer.view().frameView().isOffscreen())
1436         return false;
1437
1438     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1439     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1440     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1441     // can no longer check if it is a background image.
1442     bool backgroundIsPaintedByRoot = renderer.isDocumentElementRenderer();
1443     if (renderer.isBody()) {
1444         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1445         ASSERT(rootRenderer.isDocumentElementRenderer());
1446         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1447         // FIXME: Should share body background propagation code.
1448         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1449
1450     }
1451     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect() : renderer.absoluteClippedOverflowRect();
1452     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1453         return false;
1454
1455     return true;
1456 }
1457
1458 void RenderElement::registerForVisibleInViewportCallback()
1459 {
1460     if (isRegisteredForVisibleInViewportCallback())
1461         return;
1462     setIsRegisteredForVisibleInViewportCallback(true);
1463
1464     view().registerForVisibleInViewportCallback(*this);
1465 }
1466
1467 void RenderElement::unregisterForVisibleInViewportCallback()
1468 {
1469     if (!isRegisteredForVisibleInViewportCallback())
1470         return;
1471     setIsRegisteredForVisibleInViewportCallback(false);
1472
1473     view().unregisterForVisibleInViewportCallback(*this);
1474 }
1475
1476 void RenderElement::visibleInViewportStateChanged(VisibleInViewportState state)
1477 {
1478     if (state == visibleInViewportState())
1479         return;
1480     setVisibleInViewportState(state);
1481
1482     if (element())
1483         element()->isVisibleInViewportChanged();
1484 }
1485
1486 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1487 {
1488     if (document().pageCacheState() != Document::NotInPageCache)
1489         return;
1490     auto& frameView = view().frameView();
1491     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1492     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1493         // FIXME: It would be better to pass the image along with the renderer
1494         // so that we can be smarter about detecting if the image is inside the
1495         // viewport in repaintForPausedImageAnimationsIfNeeded().
1496         view().addRendererWithPausedImageAnimations(*this);
1497         return;
1498     }
1499     imageChanged(&image);
1500 }
1501
1502 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1503 {
1504     ASSERT(m_hasPausedImageAnimations);
1505     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1506         return false;
1507
1508     repaint();
1509
1510     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1511     if (is<RenderBoxModelObject>(*this))
1512         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1513
1514     return true;
1515 }
1516
1517 const RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle) const
1518 {
1519     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1520         return nullptr;
1521
1522     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1523     if (cachedStyle)
1524         return cachedStyle;
1525
1526     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1527     if (result)
1528         return const_cast<RenderStyle&>(m_style).addCachedPseudoStyle(WTFMove(result));
1529     return nullptr;
1530 }
1531
1532 RenderStyle* RenderElement::getMutableCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle)
1533 {
1534     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1535         return nullptr;
1536
1537     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1538     if (cachedStyle)
1539         return cachedStyle;
1540
1541     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1542     if (result)
1543         return m_style.addCachedPseudoStyle(WTFMove(result));
1544     return nullptr;
1545 }
1546
1547 std::unique_ptr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, const RenderStyle* parentStyle, const RenderStyle* ownStyle) const
1548 {
1549     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1550         return nullptr;
1551
1552     if (!parentStyle) {
1553         ASSERT(!ownStyle);
1554         parentStyle = &style();
1555     }
1556
1557     if (isAnonymous())
1558         return nullptr;
1559
1560     auto& styleResolver = element()->styleResolver();
1561
1562     std::unique_ptr<RenderStyle> style;
1563     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1564         style = styleResolver.styleForElement(*element(), parentStyle).renderStyle;
1565         style->setStyleType(FIRST_LINE_INHERITED);
1566     } else
1567         style = styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1568
1569     if (style)
1570         Style::loadPendingResources(*style, document(), element());
1571
1572     return style;
1573 }
1574
1575 Color RenderElement::selectionColor(int colorProperty) const
1576 {
1577     // If the element is unselectable, or we are only painting the selection,
1578     // don't override the foreground color with the selection foreground color.
1579     if (style().userSelect() == SELECT_NONE
1580         || (view().frameView().paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorSelectionAndBackgroundsOnly)))
1581         return Color();
1582
1583     if (std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1584         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1585         if (!color.isValid())
1586             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1587         return color;
1588     }
1589
1590     if (frame().selection().isFocusedAndActive())
1591         return theme().activeSelectionForegroundColor();
1592     return theme().inactiveSelectionForegroundColor();
1593 }
1594
1595 std::unique_ptr<RenderStyle> RenderElement::selectionPseudoStyle() const
1596 {
1597     if (isAnonymous())
1598         return nullptr;
1599
1600     if (ShadowRoot* root = element()->containingShadowRoot()) {
1601         if (root->mode() == ShadowRootMode::UserAgent) {
1602             if (Element* shadowHost = element()->shadowHost())
1603                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1604         }
1605     }
1606
1607     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1608 }
1609
1610 Color RenderElement::selectionForegroundColor() const
1611 {
1612     return selectionColor(CSSPropertyWebkitTextFillColor);
1613 }
1614
1615 Color RenderElement::selectionEmphasisMarkColor() const
1616 {
1617     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1618 }
1619
1620 Color RenderElement::selectionBackgroundColor() const
1621 {
1622     if (style().userSelect() == SELECT_NONE)
1623         return Color();
1624
1625     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1626         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1627
1628     std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1629     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1630         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1631
1632     if (frame().selection().isFocusedAndActive())
1633         return theme().activeSelectionBackgroundColor();
1634     return theme().inactiveSelectionBackgroundColor();
1635 }
1636
1637 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1638 {
1639     if (!isInline() || isReplaced()) {
1640         point = localToAbsolute(FloatPoint(), UseTransforms);
1641         return true;
1642     }
1643
1644     // find the next text/image child, to get a position
1645     const RenderObject* o = this;
1646     while (o) {
1647         const RenderObject* p = o;
1648         if (RenderObject* child = o->firstChildSlow())
1649             o = child;
1650         else if (o->nextSibling())
1651             o = o->nextSibling();
1652         else {
1653             RenderObject* next = 0;
1654             while (!next && o->parent()) {
1655                 o = o->parent();
1656                 next = o->nextSibling();
1657             }
1658             o = next;
1659
1660             if (!o)
1661                 break;
1662         }
1663         ASSERT(o);
1664
1665         if (!o->isInline() || o->isReplaced()) {
1666             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1667             return true;
1668         }
1669
1670         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1671             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1672         } else if (is<RenderText>(*o) || o->isReplaced()) {
1673             point = FloatPoint();
1674             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1675                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1676             else if (is<RenderBox>(*o))
1677                 point.moveBy(downcast<RenderBox>(*o).location());
1678             point = o->container()->localToAbsolute(point, UseTransforms);
1679             return true;
1680         }
1681     }
1682     
1683     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1684     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1685     if (!o && document().view()) {
1686         point = FloatPoint(0, document().view()->contentsHeight());
1687         return true;
1688     }
1689     return false;
1690 }
1691
1692 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1693 {
1694     if (!isInline() || isReplaced()) {
1695         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1696         return true;
1697     }
1698
1699     // find the last text/image child, to get a position
1700     const RenderObject* o = this;
1701     while (o) {
1702         if (RenderObject* child = o->lastChildSlow())
1703             o = child;
1704         else if (o->previousSibling())
1705             o = o->previousSibling();
1706         else {
1707             RenderObject* prev = 0;
1708             while (!prev) {
1709                 o = o->parent();
1710                 if (!o)
1711                     return false;
1712                 prev = o->previousSibling();
1713             }
1714             o = prev;
1715         }
1716         ASSERT(o);
1717         if (is<RenderText>(*o) || o->isReplaced()) {
1718             point = FloatPoint();
1719             if (is<RenderText>(*o)) {
1720                 LayoutRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1721                 if (!linesBox.maxX() && !linesBox.maxY())
1722                     continue;
1723                 point.moveBy(linesBox.maxXMaxYCorner());
1724             } else
1725                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1726             point = o->container()->localToAbsolute(point, UseTransforms);
1727             return true;
1728         }
1729     }
1730     return true;
1731 }
1732
1733 LayoutRect RenderElement::anchorRect() const
1734 {
1735     FloatPoint leading, trailing;
1736     getLeadingCorner(leading);
1737     getTrailingCorner(trailing);
1738
1739     FloatPoint upperLeft = leading;
1740     FloatPoint lowerRight = trailing;
1741
1742     // Vertical writing modes might mean the leading point is not in the top left
1743     if (!isInline() || isReplaced()) {
1744         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1745         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1746     } // Otherwise, it's not obvious what to do.
1747
1748     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1749 }
1750
1751 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1752 {
1753     const RenderElement* current = this;
1754     do {
1755         if (current->isRenderBlock())
1756             return current;
1757         if (!current->isRenderInline() || current->isRubyText())
1758             return nullptr;
1759         
1760         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1761         if (styleToUse.textDecoration() & textDecoration)
1762             return current;
1763         current = current->parent();
1764     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1765
1766     return current;
1767 }
1768
1769 void RenderElement::drawLineForBoxSide(GraphicsContext& graphicsContext, const FloatRect& rect, BoxSide side, Color color, EBorderStyle borderStyle, float adjacentWidth1, float adjacentWidth2, bool antialias) const
1770 {
1771     auto drawBorderRect = [&graphicsContext] (const FloatRect& rect)
1772     {
1773         if (rect.isEmpty())
1774             return;
1775         graphicsContext.drawRect(rect);
1776     };
1777
1778     auto drawLineFor = [this, &graphicsContext, color, antialias] (const FloatRect& rect, BoxSide side, EBorderStyle borderStyle, const FloatSize& adjacent)
1779     {
1780         if (rect.isEmpty())
1781             return;
1782         drawLineForBoxSide(graphicsContext, rect, side, color, borderStyle, adjacent.width(), adjacent.height(), antialias);
1783     };
1784
1785     float x1 = rect.x();
1786     float x2 = rect.maxX();
1787     float y1 = rect.y();
1788     float y2 = rect.maxY();
1789     float thickness;
1790     float length;
1791     if (side == BSTop || side == BSBottom) {
1792         thickness = y2 - y1;
1793         length = x2 - x1;
1794     } else {
1795         thickness = x2 - x1;
1796         length = y2 - y1;
1797     }
1798     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
1799     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
1800     if (!thickness || !length)
1801         return;
1802
1803     float deviceScaleFactor = document().deviceScaleFactor();
1804     if (borderStyle == DOUBLE && (thickness * deviceScaleFactor) < 3)
1805         borderStyle = SOLID;
1806
1807     switch (borderStyle) {
1808     case BNONE:
1809     case BHIDDEN:
1810         return;
1811     case DOTTED:
1812     case DASHED: {
1813         bool wasAntialiased = graphicsContext.shouldAntialias();
1814         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1815         graphicsContext.setShouldAntialias(antialias);
1816         graphicsContext.setStrokeColor(color);
1817         graphicsContext.setStrokeThickness(thickness);
1818         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1819         graphicsContext.drawLine(roundPointToDevicePixels(LayoutPoint(x1, y1), deviceScaleFactor), roundPointToDevicePixels(LayoutPoint(x2, y2), deviceScaleFactor));
1820         graphicsContext.setShouldAntialias(wasAntialiased);
1821         graphicsContext.setStrokeStyle(oldStrokeStyle);
1822         break;
1823     }
1824     case DOUBLE: {
1825         float thirdOfThickness = ceilToDevicePixel(thickness / 3, deviceScaleFactor);
1826         ASSERT(thirdOfThickness);
1827
1828         if (!adjacentWidth1 && !adjacentWidth2) {
1829             StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1830             graphicsContext.setStrokeStyle(NoStroke);
1831             graphicsContext.setFillColor(color);
1832
1833             bool wasAntialiased = graphicsContext.shouldAntialias();
1834             graphicsContext.setShouldAntialias(antialias);
1835
1836             switch (side) {
1837             case BSTop:
1838             case BSBottom:
1839                 drawBorderRect(snapRectToDevicePixels(x1, y1, length, thirdOfThickness, deviceScaleFactor));
1840                 drawBorderRect(snapRectToDevicePixels(x1, y2 - thirdOfThickness, length, thirdOfThickness, deviceScaleFactor));
1841                 break;
1842             case BSLeft:
1843             case BSRight:
1844                 drawBorderRect(snapRectToDevicePixels(x1, y1, thirdOfThickness, length, deviceScaleFactor));
1845                 drawBorderRect(snapRectToDevicePixels(x2 - thirdOfThickness, y1, thirdOfThickness, length, deviceScaleFactor));
1846                 break;
1847             }
1848
1849             graphicsContext.setShouldAntialias(wasAntialiased);
1850             graphicsContext.setStrokeStyle(oldStrokeStyle);
1851         } else {
1852             float adjacent1BigThird = ceilToDevicePixel(adjacentWidth1 / 3, deviceScaleFactor);
1853             float adjacent2BigThird = ceilToDevicePixel(adjacentWidth2 / 3, deviceScaleFactor);
1854
1855             float offset1 = floorToDevicePixel(fabs(adjacentWidth1) * 2 / 3, deviceScaleFactor);
1856             float offset2 = floorToDevicePixel(fabs(adjacentWidth2) * 2 / 3, deviceScaleFactor);
1857
1858             float mitreOffset1 = adjacentWidth1 < 0 ? offset1 : 0;
1859             float mitreOffset2 = adjacentWidth1 > 0 ? offset1 : 0;
1860             float mitreOffset3 = adjacentWidth2 < 0 ? offset2 : 0;
1861             float mitreOffset4 = adjacentWidth2 > 0 ? offset2 : 0;
1862
1863             FloatRect paintBorderRect;
1864             switch (side) {
1865             case BSTop:
1866                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y1, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1867                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1868
1869                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y2 - thirdOfThickness, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1870                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1871                 break;
1872             case BSLeft:
1873                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1874                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1875
1876                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1877                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1878                 break;
1879             case BSBottom:
1880                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y1, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1881                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1882
1883                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y2 - thirdOfThickness, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1884                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1885                 break;
1886             case BSRight:
1887                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1888                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1889
1890                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1891                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1892                 break;
1893             default:
1894                 break;
1895             }
1896         }
1897         break;
1898     }
1899     case RIDGE:
1900     case GROOVE: {
1901         EBorderStyle s1;
1902         EBorderStyle s2;
1903         if (borderStyle == GROOVE) {
1904             s1 = INSET;
1905             s2 = OUTSET;
1906         } else {
1907             s1 = OUTSET;
1908             s2 = INSET;
1909         }
1910
1911         float adjacent1BigHalf = ceilToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1912         float adjacent2BigHalf = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1913
1914         float adjacent1SmallHalf = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1915         float adjacent2SmallHalf = floorToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1916
1917         float offset1 = 0;
1918         float offset2 = 0;
1919         float offset3 = 0;
1920         float offset4 = 0;
1921
1922         if (((side == BSTop || side == BSLeft) && adjacentWidth1 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 > 0))
1923             offset1 = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1924
1925         if (((side == BSTop || side == BSLeft) && adjacentWidth2 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 > 0))
1926             offset2 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1927
1928         if (((side == BSTop || side == BSLeft) && adjacentWidth1 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 < 0))
1929             offset3 = floorToDevicePixel(fabs(adjacentWidth1) / 2, deviceScaleFactor);
1930
1931         if (((side == BSTop || side == BSLeft) && adjacentWidth2 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 < 0))
1932             offset4 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1933
1934         float adjustedX = ceilToDevicePixel((x1 + x2) / 2, deviceScaleFactor);
1935         float adjustedY = ceilToDevicePixel((y1 + y2) / 2, deviceScaleFactor);
1936         // Quads can't use the default snapping rect functions.
1937         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1938         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1939         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1940         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1941
1942         switch (side) {
1943         case BSTop:
1944             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1945             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1946             break;
1947         case BSLeft:
1948             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1949             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1950             break;
1951         case BSBottom:
1952             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1953             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1954             break;
1955         case BSRight:
1956             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1957             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1958             break;
1959         }
1960         break;
1961     }
1962     case INSET:
1963     case OUTSET:
1964         calculateBorderStyleColor(borderStyle, side, color);
1965         FALLTHROUGH;
1966     case SOLID: {
1967         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1968         ASSERT(x2 >= x1);
1969         ASSERT(y2 >= y1);
1970         if (!adjacentWidth1 && !adjacentWidth2) {
1971             graphicsContext.setStrokeStyle(NoStroke);
1972             graphicsContext.setFillColor(color);
1973             bool wasAntialiased = graphicsContext.shouldAntialias();
1974             graphicsContext.setShouldAntialias(antialias);
1975             drawBorderRect(snapRectToDevicePixels(x1, y1, x2 - x1, y2 - y1, deviceScaleFactor));
1976             graphicsContext.setShouldAntialias(wasAntialiased);
1977             graphicsContext.setStrokeStyle(oldStrokeStyle);
1978             return;
1979         }
1980
1981         // FIXME: These roundings should be replaced by ASSERT(device pixel positioned) when all the callers have transitioned to device pixels.
1982         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1983         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1984         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1985         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1986
1987         Vector<FloatPoint> quad;
1988         quad.reserveInitialCapacity(4);
1989         switch (side) {
1990         case BSTop:
1991             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y1 });
1992             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y2 });
1993             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y2 });
1994             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y1 });
1995             break;
1996         case BSBottom:
1997             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y1 });
1998             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y2 });
1999             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y2 });
2000             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y1 });
2001             break;
2002         case BSLeft:
2003             quad.uncheckedAppend({ x1, y1 + std::max<float>(-adjacentWidth1, 0) });
2004             quad.uncheckedAppend({ x1, y2 - std::max<float>(-adjacentWidth2, 0) });
2005             quad.uncheckedAppend({ x2, y2 - std::max<float>( adjacentWidth2, 0) });
2006             quad.uncheckedAppend({ x2, y1 + std::max<float>( adjacentWidth1, 0) });
2007             break;
2008         case BSRight:
2009             quad.uncheckedAppend({ x1, y1 + std::max<float>( adjacentWidth1, 0) });
2010             quad.uncheckedAppend({ x1, y2 - std::max<float>( adjacentWidth2, 0) });
2011             quad.uncheckedAppend({ x2, y2 - std::max<float>(-adjacentWidth2, 0) });
2012             quad.uncheckedAppend({ x2, y1 + std::max<float>(-adjacentWidth1, 0) });
2013             break;
2014         }
2015
2016         graphicsContext.setStrokeStyle(NoStroke);
2017         graphicsContext.setFillColor(color);
2018         bool wasAntialiased = graphicsContext.shouldAntialias();
2019         graphicsContext.setShouldAntialias(antialias);
2020         graphicsContext.fillPath(Path::polygonPathFromPoints(quad));
2021         graphicsContext.setShouldAntialias(wasAntialiased);
2022
2023         graphicsContext.setStrokeStyle(oldStrokeStyle);
2024         break;
2025     }
2026     }
2027 }
2028
2029 void RenderElement::paintFocusRing(PaintInfo& paintInfo, const RenderStyle& style, const Vector<LayoutRect>& focusRingRects)
2030 {
2031     ASSERT(style.outlineStyleIsAuto());
2032     float outlineOffset = style.outlineOffset();
2033     Vector<FloatRect> pixelSnappedFocusRingRects;
2034     float deviceScaleFactor = document().deviceScaleFactor();
2035     for (auto rect : focusRingRects) {
2036         rect.inflate(outlineOffset);
2037         pixelSnappedFocusRingRects.append(snapRectToDevicePixels(rect, deviceScaleFactor));
2038     }
2039 #if PLATFORM(MAC)
2040     bool needsRepaint;
2041     if (style.hasBorderRadius()) {
2042         Path path = PathUtilities::pathWithShrinkWrappedRectsForOutline(pixelSnappedFocusRingRects, style.border(), outlineOffset, style.direction(), style.writingMode(),
2043             document().deviceScaleFactor());
2044         if (path.isEmpty()) {
2045             for (auto rect : pixelSnappedFocusRingRects)
2046                 path.addRect(rect);
2047         }
2048         paintInfo.context().drawFocusRing(path, document().page()->focusController().timeSinceFocusWasSet(), needsRepaint);
2049     } else
2050         paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, document().page()->focusController().timeSinceFocusWasSet(), needsRepaint);
2051     if (needsRepaint)
2052         document().page()->focusController().setFocusedElementNeedsRepaint();
2053 #else
2054     paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, style.outlineWidth(), style.outlineOffset(), style.visitedDependentColor(CSSPropertyOutlineColor));
2055 #endif
2056 }
2057
2058 void RenderElement::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
2059 {
2060     GraphicsContext& graphicsContext = paintInfo.context();
2061     if (graphicsContext.paintingDisabled())
2062         return;
2063
2064     if (!hasOutline())
2065         return;
2066
2067     auto& styleToUse = style();
2068     float outlineWidth = floorToDevicePixel(styleToUse.outlineWidth(), document().deviceScaleFactor());
2069     float outlineOffset = floorToDevicePixel(styleToUse.outlineOffset(), document().deviceScaleFactor());
2070
2071     // Only paint the focus ring by hand if the theme isn't able to draw it.
2072     if (styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse)) {
2073         Vector<LayoutRect> focusRingRects;
2074         addFocusRingRects(focusRingRects, paintRect.location(), paintInfo.paintContainer);
2075         paintFocusRing(paintInfo, styleToUse, focusRingRects);
2076     }
2077
2078     if (hasOutlineAnnotation() && !styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2079         addPDFURLRect(paintInfo, paintRect.location());
2080
2081     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
2082         return;
2083
2084     FloatRect outer = paintRect;
2085     outer.inflate(outlineOffset + outlineWidth);
2086     FloatRect inner = outer;
2087     inner.inflate(-outlineWidth);
2088
2089     // FIXME: This prevents outlines from painting inside the object. See bug 12042
2090     if (outer.isEmpty())
2091         return;
2092
2093     EBorderStyle outlineStyle = styleToUse.outlineStyle();
2094     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
2095
2096     bool useTransparencyLayer = !outlineColor.isOpaque();
2097     if (useTransparencyLayer) {
2098         if (outlineStyle == SOLID) {
2099             Path path;
2100             path.addRect(outer);
2101             path.addRect(inner);
2102             graphicsContext.setFillRule(RULE_EVENODD);
2103             graphicsContext.setFillColor(outlineColor);
2104             graphicsContext.fillPath(path);
2105             return;
2106         }
2107         graphicsContext.beginTransparencyLayer(outlineColor.alphaAsFloat());
2108         outlineColor = outlineColor.opaqueColor();
2109     }
2110
2111     float leftOuter = outer.x();
2112     float leftInner = inner.x();
2113     float rightOuter = outer.maxX();
2114     float rightInner = std::min(inner.maxX(), rightOuter);
2115     float topOuter = outer.y();
2116     float topInner = inner.y();
2117     float bottomOuter = outer.maxY();
2118     float bottomInner = std::min(inner.maxY(), bottomOuter);
2119
2120     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(leftInner, bottomOuter)), BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2121     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(rightOuter, topInner)), BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2122     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(rightInner, topOuter), FloatPoint(rightOuter, bottomOuter)), BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2123     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, bottomInner), FloatPoint(rightOuter, bottomOuter)), BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2124
2125     if (useTransparencyLayer)
2126         graphicsContext.endTransparencyLayer();
2127 }
2128
2129 void RenderElement::issueRepaintForOutlineAuto(float outlineSize)
2130 {
2131     LayoutRect repaintRect;
2132     Vector<LayoutRect> focusRingRects;
2133     addFocusRingRects(focusRingRects, LayoutPoint(), containerForRepaint());
2134     for (auto rect : focusRingRects) {
2135         rect.inflate(outlineSize);
2136         repaintRect.unite(rect);
2137     }
2138     repaintRectangle(repaintRect);
2139 }
2140
2141 void RenderElement::updateOutlineAutoAncestor(bool hasOutlineAuto)
2142 {
2143     for (auto& child : childrenOfType<RenderObject>(*this)) {
2144         if (hasOutlineAuto == child.hasOutlineAutoAncestor())
2145             continue;
2146         child.setHasOutlineAutoAncestor(hasOutlineAuto);
2147         bool childHasOutlineAuto = child.outlineStyleForRepaint().outlineStyleIsAuto();
2148         if (childHasOutlineAuto)
2149             continue;
2150         if (!is<RenderElement>(child))
2151             continue;
2152         downcast<RenderElement>(child).updateOutlineAutoAncestor(hasOutlineAuto);
2153     }
2154     if (hasContinuation())
2155         downcast<RenderBoxModelObject>(*this).continuation()->updateOutlineAutoAncestor(hasOutlineAuto);
2156 }
2157
2158 bool RenderElement::hasOutlineAnnotation() const
2159 {
2160     return element() && element()->isLink() && document().printing();
2161 }
2162
2163 bool RenderElement::hasSelfPaintingLayer() const
2164 {
2165     if (!hasLayer())
2166         return false;
2167     auto& layerModelObject = downcast<RenderLayerModelObject>(*this);
2168     return layerModelObject.hasSelfPaintingLayer();
2169 }
2170
2171 bool RenderElement::checkForRepaintDuringLayout() const
2172 {
2173     return !document().view()->needsFullRepaint() && everHadLayout() && !hasSelfPaintingLayer();
2174 }
2175
2176 RespectImageOrientationEnum RenderElement::shouldRespectImageOrientation() const
2177 {
2178 #if USE(CG) || USE(CAIRO)
2179     // This can only be enabled for ports which honor the orientation flag in their drawing code.
2180     if (document().isImageDocument())
2181         return RespectImageOrientation;
2182 #endif
2183     // Respect the image's orientation if it's being used as a full-page image or it's
2184     // an <img> and the setting to respect it everywhere is set.
2185     return (frame().settings().shouldRespectImageOrientation() && is<HTMLImageElement>(element())) ? RespectImageOrientation : DoNotRespectImageOrientation;
2186 }
2187
2188 void RenderElement::removeFromRenderFlowThread()
2189 {
2190     ASSERT(flowThreadState() != NotInsideFlowThread);
2191     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2192     // It's only until later when we actually destroy it and remove all the children from it.
2193     // Currently, that happens for firstLetter elements and list markers.
2194     // Pass in the flow thread so that we don't have to look it up for all the children.
2195     removeFromRenderFlowThreadIncludingDescendants(true);
2196 }
2197
2198 void RenderElement::removeFromRenderFlowThreadIncludingDescendants(bool shouldUpdateState)
2199 {
2200     // Once we reach another flow thread we don't need to update the flow thread state
2201     // but we have to continue cleanup the flow thread info.
2202     if (isRenderFlowThread())
2203         shouldUpdateState = false;
2204
2205     for (auto& child : childrenOfType<RenderObject>(*this)) {
2206         if (is<RenderElement>(child)) {
2207             downcast<RenderElement>(child).removeFromRenderFlowThreadIncludingDescendants(shouldUpdateState);
2208             continue;
2209         }
2210         if (shouldUpdateState)
2211             child.setFlowThreadState(NotInsideFlowThread);
2212     }
2213
2214     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
2215     RenderFlowThread* flowThreadContainingBlock = this->flowThreadContainingBlock();
2216     while (flowThreadContainingBlock) {
2217         flowThreadContainingBlock->removeFlowChildInfo(*this);
2218
2219         if (flowThreadContainingBlock->flowThreadState() == NotInsideFlowThread)
2220             break;
2221         auto* parent = flowThreadContainingBlock->parent();
2222         if (!parent)
2223             break;
2224         flowThreadContainingBlock = parent->flowThreadContainingBlock();
2225     }
2226     if (is<RenderBlock>(*this))
2227         downcast<RenderBlock>(*this).setCachedFlowThreadContainingBlockNeedsUpdate();
2228
2229     if (shouldUpdateState)
2230         setFlowThreadState(NotInsideFlowThread);
2231 }
2232
2233 #if ENABLE(TEXT_AUTOSIZING)
2234 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject& renderer)
2235 {
2236     const RenderStyle& style = renderer.style();
2237     if (style.height().type() == Fixed) {
2238         if (is<RenderBlock>(renderer)) {
2239             // For fixed height styles, if the overflow size of the element spills out of the specified
2240             // height, assume we can apply text auto-sizing.
2241             if (style.overflowY() == OVISIBLE
2242                 && style.height().value() < downcast<RenderBlock>(renderer).layoutOverflowRect().maxY())
2243                 return RenderObject::OverflowHeight;
2244         }
2245         return RenderObject::FixedHeight;
2246     }
2247     return RenderObject::FlexibleHeight;
2248 }
2249
2250 void RenderElement::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
2251 {
2252     Document* document = view().frameView().frame().document();
2253     if (!document)
2254         return;
2255
2256     Vector<int> depthStack;
2257     int currentDepth = 0;
2258     int newFixedDepth = 0;
2259
2260     // We don't apply autosizing to nodes with fixed height normally.
2261     // But we apply it to nodes which are located deep enough
2262     // (nesting depth is greater than some const) inside of a parent block
2263     // which has fixed height but its content overflows intentionally.
2264     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2265         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2266             depthStack.remove(depthStack.size() - 1);
2267         if (newFixedDepth)
2268             depthStack.append(newFixedDepth);
2269
2270         int stackSize = depthStack.size();
2271         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2272             downcast<RenderBlockFlow>(*descendent).adjustComputedFontSizes(size, visibleWidth);
2273         newFixedDepth = 0;
2274     }
2275
2276     // Remove style from auto-sizing table that are no longer valid.
2277     document->updateAutoSizedNodes();
2278 }
2279
2280 void RenderElement::resetTextAutosizing()
2281 {
2282     Document* document = view().frameView().frame().document();
2283     if (!document)
2284         return;
2285
2286     LOG(TextAutosizing, "RenderElement::resetTextAutosizing()");
2287
2288     document->clearAutoSizedNodes();
2289
2290     Vector<int> depthStack;
2291     int currentDepth = 0;
2292     int newFixedDepth = 0;
2293
2294     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2295         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2296             depthStack.remove(depthStack.size() - 1);
2297         if (newFixedDepth)
2298             depthStack.append(newFixedDepth);
2299
2300         int stackSize = depthStack.size();
2301         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2302             downcast<RenderBlockFlow>(*descendent).resetComputedFontSize();
2303         newFixedDepth = 0;
2304     }
2305 }
2306 #endif // ENABLE(TEXT_AUTOSIZING)
2307
2308 }