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