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