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