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