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