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