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