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