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