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