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