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