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