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