[RenderTreeBuilder] Move RenderElement::takeChild() to RenderTreeBuilder
[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 void RenderElement::removeAndDestroyChild(RenderTreeBuilder& builder, RenderObject& oldChild)
485 {
486     if (is<RenderElement>(oldChild)) {
487         auto& child = downcast<RenderElement>(oldChild);
488         while (child.firstChild()) {
489             auto& firstChild = *child.firstChild();
490             if (auto* node = firstChild.node())
491                 node->setRenderer(nullptr);
492             child.removeAndDestroyChild(builder, firstChild);
493         }
494     }
495     auto toDestroy = builder.takeChild(*this, oldChild);
496 }
497
498 RenderObject* RenderElement::attachRendererInternal(RenderPtr<RenderObject> child, RenderObject* beforeChild)
499 {
500     child->setParent(this);
501
502     if (m_firstChild == beforeChild)
503         m_firstChild = child.get();
504
505     if (beforeChild) {
506         auto* previousSibling = beforeChild->previousSibling();
507         if (previousSibling)
508             previousSibling->setNextSibling(child.get());
509         child->setPreviousSibling(previousSibling);
510         child->setNextSibling(beforeChild);
511         beforeChild->setPreviousSibling(child.get());
512         return child.release();
513     }
514     if (m_lastChild)
515         m_lastChild->setNextSibling(child.get());
516     child->setPreviousSibling(m_lastChild);
517     m_lastChild = child.get();
518     return child.release();
519 }
520
521 RenderPtr<RenderObject> RenderElement::detachRendererInternal(RenderObject& renderer)
522 {
523     auto* parent = renderer.parent();
524     ASSERT(parent);
525     auto* nextSibling = renderer.nextSibling();
526
527     if (renderer.previousSibling())
528         renderer.previousSibling()->setNextSibling(nextSibling);
529     if (nextSibling)
530         nextSibling->setPreviousSibling(renderer.previousSibling());
531
532     if (parent->firstChild() == &renderer)
533         parent->m_firstChild = nextSibling;
534     if (parent->lastChild() == &renderer)
535         parent->m_lastChild = renderer.previousSibling();
536
537     renderer.setPreviousSibling(nullptr);
538     renderer.setNextSibling(nullptr);
539     renderer.setParent(nullptr);
540     return RenderPtr<RenderObject>(&renderer);
541 }
542
543 void RenderElement::insertChildInternal(RenderPtr<RenderObject> newChildPtr, RenderObject* beforeChild)
544 {
545     RELEASE_ASSERT_WITH_MESSAGE(!view().frameView().layoutContext().layoutState(), "Layout must not mutate render tree");
546
547     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
548     ASSERT(!newChildPtr->parent());
549     ASSERT(!isRenderBlockFlow() || (!newChildPtr->isTableSection() && !newChildPtr->isTableRow() && !newChildPtr->isTableCell()));
550
551     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
552         beforeChild = beforeChild->parent();
553
554     ASSERT(!beforeChild || beforeChild->parent() == this);
555     ASSERT(!is<RenderText>(beforeChild) || !downcast<RenderText>(*beforeChild).inlineWrapperForDisplayContents());
556
557     // Take the ownership.
558     auto* newChild = attachRendererInternal(WTFMove(newChildPtr), beforeChild);
559
560     newChild->initializeFragmentedFlowStateOnInsertion();
561     if (!renderTreeBeingDestroyed()) {
562         newChild->insertedIntoTree();
563         if (is<RenderElement>(*newChild))
564             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
565     }
566
567     newChild->setNeedsLayoutAndPrefWidthsRecalc();
568     setPreferredLogicalWidthsDirty(true);
569     if (!normalChildNeedsLayout())
570         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
571
572     if (AXObjectCache* cache = document().axObjectCache())
573         cache->childrenChanged(this, newChild);
574     if (is<RenderBlockFlow>(*this))
575         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
576     if (hasOutlineAutoAncestor() || outlineStyleForRepaint().outlineStyleIsAuto())
577         newChild->setHasOutlineAutoAncestor();
578 }
579
580 RenderBlock* RenderElement::containingBlockForFixedPosition() const
581 {
582     auto* renderer = parent();
583     while (renderer && !renderer->canContainFixedPositionObjects())
584         renderer = renderer->parent();
585
586     ASSERT(!renderer || !renderer->isAnonymousBlock());
587     return downcast<RenderBlock>(renderer);
588 }
589
590 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
591 {
592     // A relatively positioned RenderInline forwards its absolute positioned descendants to
593     // its nearest non-anonymous containing block (to avoid having a positioned objects list in all RenderInlines).
594     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
595     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
596         renderer = renderer->parent();
597     // Make sure we only return non-anonymous RenderBlock as containing block.
598     while (renderer && (!is<RenderBlock>(*renderer) || renderer->isAnonymousBlock()))
599         renderer = renderer->containingBlock();
600     return downcast<RenderBlock>(renderer);
601 }
602
603 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
604 {
605     if (renderer.hasLayer()) {
606         if (!beforeChild && newObject) {
607             // We need to figure out the layer that follows newObject. We only do
608             // this the first time we find a child layer, and then we update the
609             // pointer values for newObject and beforeChild used by everyone else.
610             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
611             newObject = nullptr;
612         }
613         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
614         return;
615     }
616
617     for (auto& child : childrenOfType<RenderElement>(renderer))
618         addLayers(child, parentLayer, newObject, beforeChild);
619 }
620
621 void RenderElement::addLayers(RenderLayer* parentLayer)
622 {
623     if (!parentLayer)
624         return;
625
626     RenderElement* renderer = this;
627     RenderLayer* beforeChild = nullptr;
628     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
629 }
630
631 void RenderElement::removeLayers(RenderLayer* parentLayer)
632 {
633     if (!parentLayer)
634         return;
635
636     if (hasLayer()) {
637         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
638         return;
639     }
640
641     for (auto& child : childrenOfType<RenderElement>(*this))
642         child.removeLayers(parentLayer);
643 }
644
645 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
646 {
647     if (!newParent)
648         return;
649
650     if (hasLayer()) {
651         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
652         ASSERT(oldParent == layer->parent());
653         if (oldParent)
654             oldParent->removeChild(layer);
655         newParent->addChild(layer);
656         return;
657     }
658
659     for (auto& child : childrenOfType<RenderElement>(*this))
660         child.moveLayers(oldParent, newParent);
661 }
662
663 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
664 {
665     // Error check the parent layer passed in. If it's null, we can't find anything.
666     if (!parentLayer)
667         return nullptr;
668
669     // Step 1: If our layer is a child of the desired parent, then return our layer.
670     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
671     if (ourLayer && ourLayer->parent() == parentLayer)
672         return ourLayer;
673
674     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
675     // into our siblings trying to find the next layer whose parent is the desired parent.
676     if (!ourLayer || ourLayer == parentLayer) {
677         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
678             if (!is<RenderElement>(*child))
679                 continue;
680             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
681             if (nextLayer)
682                 return nextLayer;
683         }
684     }
685
686     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
687     // find anything.
688     if (parentLayer == ourLayer)
689         return nullptr;
690
691     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
692     // follow us to see if we can locate a layer.
693     if (checkParent && parent())
694         return parent()->findNextLayer(parentLayer, this, true);
695
696     return nullptr;
697 }
698
699 bool RenderElement::layerCreationAllowedForSubtree() const
700 {
701     RenderElement* parentRenderer = parent();
702     while (parentRenderer) {
703         if (parentRenderer->isSVGHiddenContainer())
704             return false;
705         parentRenderer = parentRenderer->parent();
706     }
707     
708     return true;
709 }
710
711 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
712 {
713     // FIXME: We could save this call when the change only affected non-inherited properties.
714     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
715         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
716             continue;
717
718         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
719             continue;
720
721 #if ENABLE(FULLSCREEN_API)
722         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
723             continue;
724 #endif
725
726         // RenderFragmentedFlows are updated through the RenderView::styleDidChange function.
727         if (is<RenderFragmentedFlow>(elementChild))
728             continue;
729
730         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style().display());
731         if (style().specifiesColumns()) {
732             if (elementChild.style().specifiesColumns())
733                 newStyle.inheritColumnPropertiesFrom(style());
734             if (elementChild.style().columnSpan())
735                 newStyle.setColumnSpan(ColumnSpanAll);
736         }
737
738         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
739         // they contain block descendants of relative or sticky positioned inlines.
740         if (elementChild.isInFlowPositioned() && elementChild.isContinuation())
741             newStyle.setPosition(elementChild.style().position());
742
743         updateAnonymousChildStyle(newStyle);
744         
745         elementChild.setStyle(WTFMove(newStyle));
746     }
747 }
748
749 static inline bool rendererHasBackground(const RenderElement* renderer)
750 {
751     return renderer && renderer->hasBackground();
752 }
753
754 void RenderElement::invalidateCachedFirstLineStyle()
755 {
756     if (!m_hasValidCachedFirstLineStyle)
757         return;
758     m_hasValidCachedFirstLineStyle = false;
759     // Invalidate the subtree as descendant's first line style may depend on ancestor's.
760     for (auto& descendant : descendantsOfType<RenderElement>(*this))
761         descendant.m_hasValidCachedFirstLineStyle = false;
762 }
763
764 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
765 {
766     auto* oldStyle = hasInitializedStyle() ? &style() : nullptr;
767     if (oldStyle) {
768         // If our z-index changes value or our visibility changes,
769         // we need to dirty our stacking context's z-order list.
770         bool visibilityChanged = m_style.visibility() != newStyle.visibility()
771             || m_style.zIndex() != newStyle.zIndex()
772             || m_style.hasAutoZIndex() != newStyle.hasAutoZIndex();
773 #if ENABLE(DASHBOARD_SUPPORT)
774         if (visibilityChanged)
775             document().setAnnotatedRegionsDirty(true);
776 #endif
777 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
778         if (visibilityChanged)
779             document().setTouchEventRegionsNeedUpdate();
780 #endif
781         if (visibilityChanged) {
782             if (AXObjectCache* cache = document().existingAXObjectCache())
783                 cache->childrenChanged(parent(), this);
784         }
785
786         // Keep layer hierarchy visibility bits up to date if visibility changes.
787         if (m_style.visibility() != newStyle.visibility()) {
788             if (RenderLayer* layer = enclosingLayer()) {
789                 if (newStyle.visibility() == VISIBLE)
790                     layer->setHasVisibleContent();
791                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
792                     layer->dirtyVisibleContentStatus();
793                     if (diff > StyleDifferenceRepaintLayer)
794                         repaint();
795                 }
796             }
797         }
798
799         if (m_parent && (newStyle.outlineSize() < m_style.outlineSize() || shouldRepaintForStyleDifference(diff)))
800             repaint();
801         if (isFloating() && m_style.floating() != newStyle.floating()) {
802             // For changes in float styles, we need to conceivably remove ourselves
803             // from the floating objects list.
804             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
805         } else if (isOutOfFlowPositioned() && m_style.position() != newStyle.position()) {
806             // For changes in positioning styles, we need to conceivably remove ourselves
807             // from the positioned objects list.
808             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
809         }
810
811         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
812             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
813             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
814
815         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
816             && parent() && parent()->isRenderBlock();
817
818         // reset style flags
819         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
820             setFloating(false);
821             clearPositionedState();
822         }
823         if (newStyle.hasPseudoStyle(FIRST_LINE) || oldStyle->hasPseudoStyle(FIRST_LINE))
824             invalidateCachedFirstLineStyle();
825
826         setHorizontalWritingMode(true);
827         setHasVisibleBoxDecorations(false);
828         setHasOverflowClip(false);
829         setHasTransformRelatedProperty(false);
830         setHasReflection(false);
831     } else {
832         s_affectsParentBlock = false;
833         s_noLongerAffectsParentBlock = false;
834     }
835
836     bool newStyleSlowScroll = false;
837     if (newStyle.hasFixedBackgroundImage() && !settings().fixedBackgroundsPaintRelativeToDocument()) {
838         newStyleSlowScroll = true;
839         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
840         if (drawsRootBackground && newStyle.hasEntirelyFixedBackground() && view().compositor().supportsFixedRootBackgroundCompositing())
841             newStyleSlowScroll = false;
842     }
843
844     if (view().frameView().hasSlowRepaintObject(*this)) {
845         if (!newStyleSlowScroll)
846             view().frameView().removeSlowRepaintObject(*this);
847     } else if (newStyleSlowScroll)
848         view().frameView().addSlowRepaintObject(*this);
849
850     if (isDocumentElementRenderer() || isBody())
851         view().frameView().updateExtendBackgroundIfNecessary();
852 }
853
854 #if !PLATFORM(IOS)
855 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
856 {
857     ASSERT(a->cursors() != b->cursors());
858     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
859 }
860
861 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
862 {
863     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
864 }
865 #endif
866
867 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
868 {
869     updateFillImages(oldStyle ? &oldStyle->backgroundLayers() : nullptr, m_style.backgroundLayers());
870     updateFillImages(oldStyle ? &oldStyle->maskLayers() : nullptr, m_style.maskLayers());
871     updateImage(oldStyle ? oldStyle->borderImage().image() : nullptr, m_style.borderImage().image());
872     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : nullptr, m_style.maskBoxImage().image());
873     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : nullptr, m_style.shapeOutside());
874
875     if (s_affectsParentBlock) {
876         // We have gone from not affecting the inline status of the parent flow to suddenly
877         // having an impact. See if there is a mismatch between the parent flow's
878         // childrenInline() state and our state.
879         setInline(style().isDisplayInlineType());
880         if (isInline() != parent()->childrenInline())
881             RenderTreeBuilder::current()->childFlowStateChangesAndAffectsParentBlock(*this);
882     }
883
884     if (s_noLongerAffectsParentBlock)
885         RenderTreeBuilder::current()->childFlowStateChangesAndNoLongerAffectsParentBlock(*this);
886
887     SVGRenderSupport::styleChanged(*this, oldStyle);
888
889     if (!m_parent)
890         return;
891     
892     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
893         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style);
894
895         // If the object already needs layout, then setNeedsLayout won't do
896         // any work. But if the containing block has changed, then we may need
897         // to mark the new containing blocks for layout. The change that can
898         // directly affect the containing block of this object is a change to
899         // the position style.
900         if (needsLayout() && oldStyle->position() != m_style.position())
901             markContainingBlocksForLayout();
902
903         if (diff == StyleDifferenceLayout)
904             setNeedsLayoutAndPrefWidthsRecalc();
905         else
906             setNeedsSimplifiedNormalFlowLayout();
907     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
908         setNeedsPositionedMovementLayout(oldStyle);
909         setNeedsSimplifiedNormalFlowLayout();
910     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
911         setNeedsPositionedMovementLayout(oldStyle);
912
913     // Don't check for repaint here; we need to wait until the layer has been
914     // updated by subclasses before we know if we have to repaint (in setStyle()).
915
916 #if !PLATFORM(IOS)
917     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
918         frame().eventHandler().scheduleCursorUpdate();
919 #endif
920     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
921     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
922     if (hasOutlineAuto != hadOutlineAuto) {
923         updateOutlineAutoAncestor(hasOutlineAuto);
924         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
925     }
926 }
927
928 void RenderElement::insertedIntoTree()
929 {
930     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
931     // and don't have a layer attached to ourselves.
932     RenderLayer* layer = nullptr;
933     if (firstChild() || hasLayer()) {
934         layer = parent()->enclosingLayer();
935         addLayers(layer);
936     }
937
938     // If |this| is visible but this object was not, tell the layer it has some visible content
939     // that needs to be drawn and layer visibility optimization can't be used
940     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
941         if (!layer)
942             layer = parent()->enclosingLayer();
943         if (layer)
944             layer->setHasVisibleContent();
945     }
946
947     RenderObject::insertedIntoTree();
948 }
949
950 void RenderElement::willBeRemovedFromTree()
951 {
952     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
953     RenderLayer* layer = nullptr;
954     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
955         if ((layer = parent()->enclosingLayer()))
956             layer->dirtyVisibleContentStatus();
957     }
958     // Keep our layer hierarchy updated.
959     if (firstChild() || hasLayer()) {
960         if (!layer)
961             layer = parent()->enclosingLayer();
962         removeLayers(layer);
963     }
964
965     if (isOutOfFlowPositioned() && parent()->childrenInline())
966         parent()->dirtyLinesFromChangedChild(*this);
967
968     RenderObject::willBeRemovedFromTree();
969 }
970
971 inline void RenderElement::clearSubtreeLayoutRootIfNeeded() const
972 {
973     if (renderTreeBeingDestroyed())
974         return;
975
976     if (view().frameView().layoutContext().subtreeLayoutRoot() != this)
977         return;
978
979     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
980     // which ensures that this renderer is no longer the layout root.
981     ASSERT_NOT_REACHED();
982     
983     // This indicates a failure to layout the child, which is why
984     // the layout root is still set to |this|. Make sure to clear it
985     // since we are getting destroyed.
986     view().frameView().layoutContext().clearSubtreeLayoutRoot();
987 }
988
989 void RenderElement::willBeDestroyed(RenderTreeBuilder& builder)
990 {
991     if (m_style.hasFixedBackgroundImage() && !settings().fixedBackgroundsPaintRelativeToDocument())
992         view().frameView().removeSlowRepaintObject(*this);
993
994     unregisterForVisibleInViewportCallback();
995
996     if (hasCounterNodeMap())
997         RenderCounter::destroyCounterNodes(*this);
998
999     RenderObject::willBeDestroyed(builder);
1000
1001     clearSubtreeLayoutRootIfNeeded();
1002
1003     if (hasInitializedStyle()) {
1004         for (auto* bgLayer = &m_style.backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
1005             if (auto* backgroundImage = bgLayer->image())
1006                 backgroundImage->removeClient(this);
1007         }
1008         for (auto* maskLayer = &m_style.maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1009             if (auto* maskImage = maskLayer->image())
1010                 maskImage->removeClient(this);
1011         }
1012         if (auto* borderImage = m_style.borderImage().image())
1013             borderImage->removeClient(this);
1014         if (auto* maskBoxImage = m_style.maskBoxImage().image())
1015             maskBoxImage->removeClient(this);
1016         if (auto shapeValue = m_style.shapeOutside()) {
1017             if (auto shapeImage = shapeValue->image())
1018                 shapeImage->removeClient(this);
1019         }
1020     }
1021     if (m_hasPausedImageAnimations)
1022         view().removeRendererWithPausedImageAnimations(*this);
1023 }
1024
1025 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1026 {
1027     ASSERT(!isSetNeedsLayoutForbidden());
1028     if (needsPositionedMovementLayout())
1029         return;
1030     setNeedsPositionedMovementLayoutBit(true);
1031     markContainingBlocksForLayout();
1032     if (hasLayer()) {
1033         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1034             setLayerNeedsFullRepaint();
1035         else
1036             setLayerNeedsFullRepaintForPositionedMovementLayout();
1037     }
1038 }
1039
1040 void RenderElement::clearChildNeedsLayout()
1041 {
1042     setNormalChildNeedsLayoutBit(false);
1043     setPosChildNeedsLayoutBit(false);
1044     setNeedsSimplifiedNormalFlowLayoutBit(false);
1045     setNormalChildNeedsLayoutBit(false);
1046     setNeedsPositionedMovementLayoutBit(false);
1047 }
1048
1049 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1050 {
1051     ASSERT(!isSetNeedsLayoutForbidden());
1052     if (needsSimplifiedNormalFlowLayout())
1053         return;
1054     setNeedsSimplifiedNormalFlowLayoutBit(true);
1055     markContainingBlocksForLayout();
1056     if (hasLayer())
1057         setLayerNeedsFullRepaint();
1058 }
1059
1060 RenderElement* RenderElement::hoverAncestor() const
1061 {
1062     return parent();
1063 }
1064
1065 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1066 {
1067     paintInfo.phase = phase;
1068     element.paint(paintInfo, childPoint);
1069 }
1070
1071 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1072 {
1073     // Paint all phases atomically, as though the element established its own stacking context.
1074     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1075     // This is also used by other elements (e.g. flex items and grid items).
1076     PaintPhase paintPhaseToUse = isExcludedAndPlacedInBorder() ? paintInfo.phase : PaintPhaseForeground;
1077     if (paintInfo.phase == PaintPhaseSelection)
1078         paint(paintInfo, childPoint);
1079     else if (paintInfo.phase == paintPhaseToUse) {
1080         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1081         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1082         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1083         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1084         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1085
1086         // Reset |paintInfo| to the original phase.
1087         paintInfo.phase = paintPhaseToUse;
1088     }
1089 }
1090
1091 void RenderElement::layout()
1092 {
1093     StackStats::LayoutCheckPoint layoutCheckPoint;
1094     ASSERT(needsLayout());
1095     for (auto* child = firstChild(); child; child = child->nextSibling()) {
1096         if (child->needsLayout())
1097             downcast<RenderElement>(*child).layout();
1098         ASSERT(!child->needsLayout());
1099     }
1100     clearNeedsLayout();
1101 }
1102
1103 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer& layer)
1104 {
1105     // Nobody will use multiple layers without wanting fancy positioning.
1106     if (layer.next())
1107         return true;
1108
1109     // Make sure we have a valid image.
1110     auto* image = layer.image();
1111     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1112         return false;
1113
1114     if (!layer.xPosition().isZero() || !layer.yPosition().isZero())
1115         return true;
1116
1117     auto sizeType = layer.sizeType();
1118
1119     if (sizeType == Contain || sizeType == Cover)
1120         return true;
1121
1122     if (sizeType == SizeLength) {
1123         auto size = layer.sizeLength();
1124         if (size.width.isPercentOrCalculated() || size.height.isPercentOrCalculated())
1125             return true;
1126         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1127         if ((size.width.isAuto() || size.height.isAuto()) && image->isGeneratedImage())
1128             return true;
1129     } else if (image->usesImageContainerSize())
1130         return true;
1131
1132     return false;
1133 }
1134
1135 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1136 {
1137     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1138         return true;
1139
1140     // If we don't have a background/border/mask, then nothing to do.
1141     if (!renderer.hasVisibleBoxDecorations())
1142         return false;
1143
1144     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1145         return true;
1146
1147     // Our fill layers are ok. Let's check border.
1148     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1149         return true;
1150
1151     return false;
1152 }
1153
1154 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1155 {
1156     if (view().printing())
1157         return false; // Don't repaint if we're printing.
1158
1159     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1160     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1161     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1162     LayoutRect newOutlineBox;
1163
1164     bool fullRepaint = selfNeedsLayout();
1165     // Presumably a background or a border exists if border-fit:lines was specified.
1166     if (!fullRepaint && style().borderFit() == BorderFitLines)
1167         fullRepaint = true;
1168     if (!fullRepaint) {
1169         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1170         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1171         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1172         fullRepaint = (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)));
1173     }
1174
1175     if (!repaintContainer)
1176         repaintContainer = &view();
1177
1178     if (fullRepaint) {
1179         repaintUsingContainer(repaintContainer, oldBounds);
1180         if (newBounds != oldBounds)
1181             repaintUsingContainer(repaintContainer, newBounds);
1182         return true;
1183     }
1184
1185     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1186         return false;
1187
1188     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1189     if (deltaLeft > 0)
1190         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1191     else if (deltaLeft < 0)
1192         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1193
1194     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1195     if (deltaRight > 0)
1196         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1197     else if (deltaRight < 0)
1198         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1199
1200     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1201     if (deltaTop > 0)
1202         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1203     else if (deltaTop < 0)
1204         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1205
1206     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1207     if (deltaBottom > 0)
1208         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1209     else if (deltaBottom < 0)
1210         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1211
1212     if (newOutlineBox == oldOutlineBox)
1213         return false;
1214
1215     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1216     // two rectangles (but typically only one).
1217     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1218     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1219     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1220     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1221     if (width) {
1222         LayoutUnit shadowLeft;
1223         LayoutUnit shadowRight;
1224         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1225         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1226         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1227         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min(newBounds.width(), oldBounds.width()));
1228         LayoutUnit borderWidth = std::max(borderRight, std::max(valueForLength(style().borderTopRightRadius().width, boxWidth), valueForLength(style().borderBottomRightRadius().width, boxWidth)));
1229         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max(outlineWidth, shadowRight);
1230         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1231             newOutlineBox.y(),
1232             width + decorationsWidth,
1233             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1234         LayoutUnit right = std::min(newBounds.maxX(), oldBounds.maxX());
1235         if (rightRect.x() < right) {
1236             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1237             repaintUsingContainer(repaintContainer, rightRect);
1238         }
1239     }
1240     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1241     if (height) {
1242         LayoutUnit shadowTop;
1243         LayoutUnit shadowBottom;
1244         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1245         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1246         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1247         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min(newBounds.height(), oldBounds.height()));
1248         LayoutUnit borderHeight = std::max(borderBottom, std::max(valueForLength(style().borderBottomLeftRadius().height, boxHeight),
1249             valueForLength(style().borderBottomRightRadius().height, boxHeight)));
1250         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max(outlineWidth, shadowBottom);
1251         LayoutRect bottomRect(newOutlineBox.x(),
1252             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1253             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1254             height + decorationsHeight);
1255         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1256         if (bottomRect.y() < bottom) {
1257             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1258             repaintUsingContainer(repaintContainer, bottomRect);
1259         }
1260     }
1261     return false;
1262 }
1263
1264 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1265 {
1266     ASSERT(style().hasBorder());
1267
1268     StyleImage* borderImage = style().borderImage().image();
1269     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1270 }
1271
1272 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1273 {
1274     auto& frameView = view().frameView();
1275     if (frameView.isOffscreen())
1276         return false;
1277
1278     if (!hasOverflowClip()) {
1279         // FIXME: Computing the overflow rect is expensive if any descendant has
1280         // its own self-painting layer. As a result, we prefer to abort early in
1281         // this case and assume it may cause us to repaint inside the viewport.
1282         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1283             return true;
1284     }
1285
1286     // Compute viewport rect if it was not provided.
1287     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1288     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1289 }
1290
1291 bool RenderElement::isVisibleInDocumentRect(const IntRect& documentRect) const
1292 {
1293     if (document().activeDOMObjectsAreSuspended())
1294         return false;
1295     if (style().visibility() != VISIBLE)
1296         return false;
1297     if (view().frameView().isOffscreen())
1298         return false;
1299
1300     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1301     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1302     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1303     // can no longer check if it is a background image.
1304     bool backgroundIsPaintedByRoot = isDocumentElementRenderer();
1305     if (isBody()) {
1306         auto& rootRenderer = *parent(); // If <body> has a renderer then <html> does too.
1307         ASSERT(rootRenderer.isDocumentElementRenderer());
1308         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1309         // FIXME: Should share body background propagation code.
1310         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1311
1312     }
1313
1314     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? view().backgroundRect() : absoluteClippedOverflowRect();
1315     if (!documentRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1316         return false;
1317
1318     return true;
1319 }
1320
1321 void RenderElement::registerForVisibleInViewportCallback()
1322 {
1323     if (m_isRegisteredForVisibleInViewportCallback)
1324         return;
1325     m_isRegisteredForVisibleInViewportCallback = true;
1326
1327     view().registerForVisibleInViewportCallback(*this);
1328 }
1329
1330 void RenderElement::unregisterForVisibleInViewportCallback()
1331 {
1332     if (!m_isRegisteredForVisibleInViewportCallback)
1333         return;
1334     m_isRegisteredForVisibleInViewportCallback = false;
1335
1336     view().unregisterForVisibleInViewportCallback(*this);
1337 }
1338
1339 void RenderElement::setVisibleInViewportState(VisibleInViewportState state)
1340 {
1341     if (state == visibleInViewportState())
1342         return;
1343     m_visibleInViewportState = static_cast<unsigned>(state);
1344     visibleInViewportStateChanged();
1345 }
1346
1347 void RenderElement::visibleInViewportStateChanged()
1348 {
1349     ASSERT_NOT_REACHED();
1350 }
1351
1352 bool RenderElement::isVisibleInViewport() const
1353 {
1354     auto& frameView = view().frameView();
1355     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1356     return isVisibleInDocumentRect(visibleRect);
1357 }
1358
1359 VisibleInViewportState RenderElement::imageFrameAvailable(CachedImage& image, ImageAnimatingState animatingState, const IntRect* changeRect)
1360 {
1361     bool isVisible = isVisibleInViewport();
1362
1363     if (!isVisible && animatingState == ImageAnimatingState::Yes)
1364         view().addRendererWithPausedImageAnimations(*this, image);
1365
1366     // Static images should repaint even if they are outside the viewport rectangle
1367     // because they should be inside the TileCoverageRect.
1368     if (isVisible || animatingState == ImageAnimatingState::No)
1369         imageChanged(&image, changeRect);
1370
1371     if (element() && image.image()->isBitmapImage())
1372         element()->dispatchWebKitImageReadyEventForTesting();
1373
1374     return isVisible ? VisibleInViewportState::Yes : VisibleInViewportState::No;
1375 }
1376
1377 void RenderElement::didRemoveCachedImageClient(CachedImage& cachedImage)
1378 {
1379     if (hasPausedImageAnimations())
1380         view().removeRendererWithPausedImageAnimations(*this, cachedImage);
1381 }
1382
1383 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect, CachedImage& cachedImage)
1384 {
1385     ASSERT(m_hasPausedImageAnimations);
1386     if (!isVisibleInDocumentRect(visibleRect))
1387         return false;
1388
1389     repaint();
1390
1391     if (auto* image = cachedImage.image()) {
1392         if (is<SVGImage>(image))
1393             downcast<SVGImage>(image)->scheduleStartAnimation();
1394         else
1395             image->startAnimation();
1396     }
1397
1398     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1399     if (is<RenderBoxModelObject>(*this))
1400         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1401
1402     return true;
1403 }
1404
1405 const RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle) const
1406 {
1407     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1408         return nullptr;
1409
1410     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1411     if (cachedStyle)
1412         return cachedStyle;
1413
1414     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1415     if (result)
1416         return const_cast<RenderStyle&>(m_style).addCachedPseudoStyle(WTFMove(result));
1417     return nullptr;
1418 }
1419
1420 std::unique_ptr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, const RenderStyle* parentStyle, const RenderStyle* ownStyle) const
1421 {
1422     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1423         return nullptr;
1424
1425     if (!parentStyle) {
1426         ASSERT(!ownStyle);
1427         parentStyle = &style();
1428     }
1429
1430     if (isAnonymous())
1431         return nullptr;
1432
1433     auto& styleResolver = element()->styleResolver();
1434
1435     std::unique_ptr<RenderStyle> style = styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1436
1437     if (style)
1438         Style::loadPendingResources(*style, document(), element());
1439
1440     return style;
1441 }
1442
1443 Color RenderElement::selectionColor(int colorProperty) const
1444 {
1445     // If the element is unselectable, or we are only painting the selection,
1446     // don't override the foreground color with the selection foreground color.
1447     if (style().userSelect() == SELECT_NONE
1448         || (view().frameView().paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorSelectionAndBackgroundsOnly)))
1449         return Color();
1450
1451     if (std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1452         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1453         if (!color.isValid())
1454             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1455         return color;
1456     }
1457
1458     if (frame().selection().isFocusedAndActive())
1459         return theme().activeSelectionForegroundColor();
1460     return theme().inactiveSelectionForegroundColor();
1461 }
1462
1463 std::unique_ptr<RenderStyle> RenderElement::selectionPseudoStyle() const
1464 {
1465     if (isAnonymous())
1466         return nullptr;
1467
1468     if (ShadowRoot* root = element()->containingShadowRoot()) {
1469         if (root->mode() == ShadowRootMode::UserAgent) {
1470             if (Element* shadowHost = element()->shadowHost())
1471                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1472         }
1473     }
1474
1475     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1476 }
1477
1478 Color RenderElement::selectionForegroundColor() const
1479 {
1480     return selectionColor(CSSPropertyWebkitTextFillColor);
1481 }
1482
1483 Color RenderElement::selectionEmphasisMarkColor() const
1484 {
1485     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1486 }
1487
1488 Color RenderElement::selectionBackgroundColor() const
1489 {
1490     if (style().userSelect() == SELECT_NONE)
1491         return Color();
1492
1493     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1494         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1495
1496     std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1497     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1498         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1499
1500     if (frame().selection().isFocusedAndActive())
1501         return theme().activeSelectionBackgroundColor();
1502     return theme().inactiveSelectionBackgroundColor();
1503 }
1504
1505 bool RenderElement::getLeadingCorner(FloatPoint& point, bool& insideFixed) const
1506 {
1507     if (!isInline() || isReplaced()) {
1508         point = localToAbsolute(FloatPoint(), UseTransforms, &insideFixed);
1509         return true;
1510     }
1511
1512     // find the next text/image child, to get a position
1513     const RenderObject* o = this;
1514     while (o) {
1515         const RenderObject* p = o;
1516         if (RenderObject* child = o->firstChildSlow())
1517             o = child;
1518         else if (o->nextSibling())
1519             o = o->nextSibling();
1520         else {
1521             RenderObject* next = 0;
1522             while (!next && o->parent()) {
1523                 o = o->parent();
1524                 next = o->nextSibling();
1525             }
1526             o = next;
1527
1528             if (!o)
1529                 break;
1530         }
1531         ASSERT(o);
1532
1533         if (!o->isInline() || o->isReplaced()) {
1534             point = o->localToAbsolute(FloatPoint(), UseTransforms, &insideFixed);
1535             return true;
1536         }
1537
1538         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1539             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1540         } else if (is<RenderText>(*o) || o->isReplaced()) {
1541             point = FloatPoint();
1542             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1543                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1544             else if (is<RenderBox>(*o))
1545                 point.moveBy(downcast<RenderBox>(*o).location());
1546             point = o->container()->localToAbsolute(point, UseTransforms, &insideFixed);
1547             return true;
1548         }
1549     }
1550     
1551     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1552     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1553     if (!o && document().view()) {
1554         point = FloatPoint(0, document().view()->contentsHeight());
1555         return true;
1556     }
1557     return false;
1558 }
1559
1560 bool RenderElement::getTrailingCorner(FloatPoint& point, bool& insideFixed) const
1561 {
1562     if (!isInline() || isReplaced()) {
1563         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms, &insideFixed);
1564         return true;
1565     }
1566
1567     // find the last text/image child, to get a position
1568     const RenderObject* o = this;
1569     while (o) {
1570         if (RenderObject* child = o->lastChildSlow())
1571             o = child;
1572         else if (o->previousSibling())
1573             o = o->previousSibling();
1574         else {
1575             RenderObject* prev = 0;
1576             while (!prev) {
1577                 o = o->parent();
1578                 if (!o)
1579                     return false;
1580                 prev = o->previousSibling();
1581             }
1582             o = prev;
1583         }
1584         ASSERT(o);
1585         if (is<RenderText>(*o) || o->isReplaced()) {
1586             point = FloatPoint();
1587             if (is<RenderText>(*o)) {
1588                 LayoutRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1589                 if (!linesBox.maxX() && !linesBox.maxY())
1590                     continue;
1591                 point.moveBy(linesBox.maxXMaxYCorner());
1592             } else
1593                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1594             point = o->container()->localToAbsolute(point, UseTransforms, &insideFixed);
1595             return true;
1596         }
1597     }
1598     return true;
1599 }
1600
1601 LayoutRect RenderElement::absoluteAnchorRect(bool* insideFixed) const
1602 {
1603     FloatPoint leading, trailing;
1604     bool leadingInFixed = false;
1605     bool trailingInFixed = false;
1606     getLeadingCorner(leading, leadingInFixed);
1607     getTrailingCorner(trailing, trailingInFixed);
1608
1609     FloatPoint upperLeft = leading;
1610     FloatPoint lowerRight = trailing;
1611
1612     // Vertical writing modes might mean the leading point is not in the top left
1613     if (!isInline() || isReplaced()) {
1614         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1615         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1616     } // Otherwise, it's not obvious what to do.
1617
1618     if (insideFixed) {
1619         // For now, just look at the leading corner. Handling one inside fixed and one not would be tricky.
1620         *insideFixed = leadingInFixed;
1621     }
1622
1623     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1624 }
1625
1626 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1627 {
1628     const RenderElement* current = this;
1629     do {
1630         if (current->isRenderBlock())
1631             return current;
1632         if (!current->isRenderInline() || current->isRubyText())
1633             return nullptr;
1634         
1635         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1636         if (styleToUse.textDecoration() & textDecoration)
1637             return current;
1638         current = current->parent();
1639     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1640
1641     return current;
1642 }
1643
1644 void RenderElement::drawLineForBoxSide(GraphicsContext& graphicsContext, const FloatRect& rect, BoxSide side, Color color, EBorderStyle borderStyle, float adjacentWidth1, float adjacentWidth2, bool antialias) const
1645 {
1646     auto drawBorderRect = [&graphicsContext] (const FloatRect& rect)
1647     {
1648         if (rect.isEmpty())
1649             return;
1650         graphicsContext.drawRect(rect);
1651     };
1652
1653     auto drawLineFor = [this, &graphicsContext, color, antialias] (const FloatRect& rect, BoxSide side, EBorderStyle borderStyle, const FloatSize& adjacent)
1654     {
1655         if (rect.isEmpty())
1656             return;
1657         drawLineForBoxSide(graphicsContext, rect, side, color, borderStyle, adjacent.width(), adjacent.height(), antialias);
1658     };
1659
1660     float x1 = rect.x();
1661     float x2 = rect.maxX();
1662     float y1 = rect.y();
1663     float y2 = rect.maxY();
1664     float thickness;
1665     float length;
1666     if (side == BSTop || side == BSBottom) {
1667         thickness = y2 - y1;
1668         length = x2 - x1;
1669     } else {
1670         thickness = x2 - x1;
1671         length = y2 - y1;
1672     }
1673     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
1674     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
1675     if (!thickness || !length)
1676         return;
1677
1678     float deviceScaleFactor = document().deviceScaleFactor();
1679     if (borderStyle == DOUBLE && (thickness * deviceScaleFactor) < 3)
1680         borderStyle = SOLID;
1681
1682     switch (borderStyle) {
1683     case BNONE:
1684     case BHIDDEN:
1685         return;
1686     case DOTTED:
1687     case DASHED: {
1688         bool wasAntialiased = graphicsContext.shouldAntialias();
1689         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1690         graphicsContext.setShouldAntialias(antialias);
1691         graphicsContext.setStrokeColor(color);
1692         graphicsContext.setStrokeThickness(thickness);
1693         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1694         graphicsContext.drawLine(roundPointToDevicePixels(LayoutPoint(x1, y1), deviceScaleFactor), roundPointToDevicePixels(LayoutPoint(x2, y2), deviceScaleFactor));
1695         graphicsContext.setShouldAntialias(wasAntialiased);
1696         graphicsContext.setStrokeStyle(oldStrokeStyle);
1697         break;
1698     }
1699     case DOUBLE: {
1700         float thirdOfThickness = ceilToDevicePixel(thickness / 3, deviceScaleFactor);
1701         ASSERT(thirdOfThickness);
1702
1703         if (!adjacentWidth1 && !adjacentWidth2) {
1704             StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1705             graphicsContext.setStrokeStyle(NoStroke);
1706             graphicsContext.setFillColor(color);
1707
1708             bool wasAntialiased = graphicsContext.shouldAntialias();
1709             graphicsContext.setShouldAntialias(antialias);
1710
1711             switch (side) {
1712             case BSTop:
1713             case BSBottom:
1714                 drawBorderRect(snapRectToDevicePixels(x1, y1, length, thirdOfThickness, deviceScaleFactor));
1715                 drawBorderRect(snapRectToDevicePixels(x1, y2 - thirdOfThickness, length, thirdOfThickness, deviceScaleFactor));
1716                 break;
1717             case BSLeft:
1718             case BSRight:
1719                 drawBorderRect(snapRectToDevicePixels(x1, y1, thirdOfThickness, length, deviceScaleFactor));
1720                 drawBorderRect(snapRectToDevicePixels(x2 - thirdOfThickness, y1, thirdOfThickness, length, deviceScaleFactor));
1721                 break;
1722             }
1723
1724             graphicsContext.setShouldAntialias(wasAntialiased);
1725             graphicsContext.setStrokeStyle(oldStrokeStyle);
1726         } else {
1727             float adjacent1BigThird = ceilToDevicePixel(adjacentWidth1 / 3, deviceScaleFactor);
1728             float adjacent2BigThird = ceilToDevicePixel(adjacentWidth2 / 3, deviceScaleFactor);
1729
1730             float offset1 = floorToDevicePixel(fabs(adjacentWidth1) * 2 / 3, deviceScaleFactor);
1731             float offset2 = floorToDevicePixel(fabs(adjacentWidth2) * 2 / 3, deviceScaleFactor);
1732
1733             float mitreOffset1 = adjacentWidth1 < 0 ? offset1 : 0;
1734             float mitreOffset2 = adjacentWidth1 > 0 ? offset1 : 0;
1735             float mitreOffset3 = adjacentWidth2 < 0 ? offset2 : 0;
1736             float mitreOffset4 = adjacentWidth2 > 0 ? offset2 : 0;
1737
1738             FloatRect paintBorderRect;
1739             switch (side) {
1740             case BSTop:
1741                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y1, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1742                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1743
1744                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y2 - thirdOfThickness, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1745                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1746                 break;
1747             case BSLeft:
1748                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1749                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1750
1751                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1752                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1753                 break;
1754             case BSBottom:
1755                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y1, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1756                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1757
1758                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y2 - thirdOfThickness, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1759                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1760                 break;
1761             case BSRight:
1762                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1763                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1764
1765                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1766                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1767                 break;
1768             default:
1769                 break;
1770             }
1771         }
1772         break;
1773     }
1774     case RIDGE:
1775     case GROOVE: {
1776         EBorderStyle s1;
1777         EBorderStyle s2;
1778         if (borderStyle == GROOVE) {
1779             s1 = INSET;
1780             s2 = OUTSET;
1781         } else {
1782             s1 = OUTSET;
1783             s2 = INSET;
1784         }
1785
1786         float adjacent1BigHalf = ceilToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1787         float adjacent2BigHalf = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1788
1789         float adjacent1SmallHalf = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1790         float adjacent2SmallHalf = floorToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1791
1792         float offset1 = 0;
1793         float offset2 = 0;
1794         float offset3 = 0;
1795         float offset4 = 0;
1796
1797         if (((side == BSTop || side == BSLeft) && adjacentWidth1 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 > 0))
1798             offset1 = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1799
1800         if (((side == BSTop || side == BSLeft) && adjacentWidth2 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 > 0))
1801             offset2 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1802
1803         if (((side == BSTop || side == BSLeft) && adjacentWidth1 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 < 0))
1804             offset3 = floorToDevicePixel(fabs(adjacentWidth1) / 2, deviceScaleFactor);
1805
1806         if (((side == BSTop || side == BSLeft) && adjacentWidth2 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 < 0))
1807             offset4 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1808
1809         float adjustedX = ceilToDevicePixel((x1 + x2) / 2, deviceScaleFactor);
1810         float adjustedY = ceilToDevicePixel((y1 + y2) / 2, deviceScaleFactor);
1811         // Quads can't use the default snapping rect functions.
1812         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1813         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1814         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1815         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1816
1817         switch (side) {
1818         case BSTop:
1819             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1820             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1821             break;
1822         case BSLeft:
1823             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1824             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1825             break;
1826         case BSBottom:
1827             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1828             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1829             break;
1830         case BSRight:
1831             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1832             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1833             break;
1834         }
1835         break;
1836     }
1837     case INSET:
1838     case OUTSET:
1839         calculateBorderStyleColor(borderStyle, side, color);
1840         FALLTHROUGH;
1841     case SOLID: {
1842         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1843         ASSERT(x2 >= x1);
1844         ASSERT(y2 >= y1);
1845         if (!adjacentWidth1 && !adjacentWidth2) {
1846             graphicsContext.setStrokeStyle(NoStroke);
1847             graphicsContext.setFillColor(color);
1848             bool wasAntialiased = graphicsContext.shouldAntialias();
1849             graphicsContext.setShouldAntialias(antialias);
1850             drawBorderRect(snapRectToDevicePixels(x1, y1, x2 - x1, y2 - y1, deviceScaleFactor));
1851             graphicsContext.setShouldAntialias(wasAntialiased);
1852             graphicsContext.setStrokeStyle(oldStrokeStyle);
1853             return;
1854         }
1855
1856         // FIXME: These roundings should be replaced by ASSERT(device pixel positioned) when all the callers have transitioned to device pixels.
1857         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1858         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1859         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1860         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1861
1862         Vector<FloatPoint> quad;
1863         quad.reserveInitialCapacity(4);
1864         switch (side) {
1865         case BSTop:
1866             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y1 });
1867             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y2 });
1868             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y2 });
1869             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y1 });
1870             break;
1871         case BSBottom:
1872             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y1 });
1873             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y2 });
1874             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y2 });
1875             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y1 });
1876             break;
1877         case BSLeft:
1878             quad.uncheckedAppend({ x1, y1 + std::max<float>(-adjacentWidth1, 0) });
1879             quad.uncheckedAppend({ x1, y2 - std::max<float>(-adjacentWidth2, 0) });
1880             quad.uncheckedAppend({ x2, y2 - std::max<float>( adjacentWidth2, 0) });
1881             quad.uncheckedAppend({ x2, y1 + std::max<float>( adjacentWidth1, 0) });
1882             break;
1883         case BSRight:
1884             quad.uncheckedAppend({ x1, y1 + std::max<float>( adjacentWidth1, 0) });
1885             quad.uncheckedAppend({ x1, y2 - std::max<float>( adjacentWidth2, 0) });
1886             quad.uncheckedAppend({ x2, y2 - std::max<float>(-adjacentWidth2, 0) });
1887             quad.uncheckedAppend({ x2, y1 + std::max<float>(-adjacentWidth1, 0) });
1888             break;
1889         }
1890
1891         graphicsContext.setStrokeStyle(NoStroke);
1892         graphicsContext.setFillColor(color);
1893         bool wasAntialiased = graphicsContext.shouldAntialias();
1894         graphicsContext.setShouldAntialias(antialias);
1895         graphicsContext.fillPath(Path::polygonPathFromPoints(quad));
1896         graphicsContext.setShouldAntialias(wasAntialiased);
1897
1898         graphicsContext.setStrokeStyle(oldStrokeStyle);
1899         break;
1900     }
1901     }
1902 }
1903
1904 void RenderElement::paintFocusRing(PaintInfo& paintInfo, const RenderStyle& style, const Vector<LayoutRect>& focusRingRects)
1905 {
1906     ASSERT(style.outlineStyleIsAuto());
1907     float outlineOffset = style.outlineOffset();
1908     Vector<FloatRect> pixelSnappedFocusRingRects;
1909     float deviceScaleFactor = document().deviceScaleFactor();
1910     for (auto rect : focusRingRects) {
1911         rect.inflate(outlineOffset);
1912         pixelSnappedFocusRingRects.append(snapRectToDevicePixels(rect, deviceScaleFactor));
1913     }
1914 #if PLATFORM(MAC)
1915     bool needsRepaint;
1916     if (style.hasBorderRadius()) {
1917         Path path = PathUtilities::pathWithShrinkWrappedRectsForOutline(pixelSnappedFocusRingRects, style.border(), outlineOffset, style.direction(), style.writingMode(),
1918             document().deviceScaleFactor());
1919         if (path.isEmpty()) {
1920             for (auto rect : pixelSnappedFocusRingRects)
1921                 path.addRect(rect);
1922         }
1923         paintInfo.context().drawFocusRing(path, page().focusController().timeSinceFocusWasSet(), needsRepaint);
1924     } else
1925         paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, page().focusController().timeSinceFocusWasSet(), needsRepaint);
1926     if (needsRepaint)
1927         page().focusController().setFocusedElementNeedsRepaint();
1928 #else
1929     paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, style.outlineWidth(), style.outlineOffset(), style.visitedDependentColor(CSSPropertyOutlineColor));
1930 #endif
1931 }
1932
1933 void RenderElement::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
1934 {
1935     GraphicsContext& graphicsContext = paintInfo.context();
1936     if (graphicsContext.paintingDisabled())
1937         return;
1938
1939     if (!hasOutline())
1940         return;
1941
1942     auto& styleToUse = style();
1943     float outlineWidth = floorToDevicePixel(styleToUse.outlineWidth(), document().deviceScaleFactor());
1944     float outlineOffset = floorToDevicePixel(styleToUse.outlineOffset(), document().deviceScaleFactor());
1945
1946     // Only paint the focus ring by hand if the theme isn't able to draw it.
1947     if (styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse)) {
1948         Vector<LayoutRect> focusRingRects;
1949         addFocusRingRects(focusRingRects, paintRect.location(), paintInfo.paintContainer);
1950         paintFocusRing(paintInfo, styleToUse, focusRingRects);
1951     }
1952
1953     if (hasOutlineAnnotation() && !styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
1954         addPDFURLRect(paintInfo, paintRect.location());
1955
1956     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
1957         return;
1958
1959     FloatRect outer = paintRect;
1960     outer.inflate(outlineOffset + outlineWidth);
1961     FloatRect inner = outer;
1962     inner.inflate(-outlineWidth);
1963
1964     // FIXME: This prevents outlines from painting inside the object. See bug 12042
1965     if (outer.isEmpty())
1966         return;
1967
1968     EBorderStyle outlineStyle = styleToUse.outlineStyle();
1969     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
1970
1971     bool useTransparencyLayer = !outlineColor.isOpaque();
1972     if (useTransparencyLayer) {
1973         if (outlineStyle == SOLID) {
1974             Path path;
1975             path.addRect(outer);
1976             path.addRect(inner);
1977             graphicsContext.setFillRule(RULE_EVENODD);
1978             graphicsContext.setFillColor(outlineColor);
1979             graphicsContext.fillPath(path);
1980             return;
1981         }
1982         graphicsContext.beginTransparencyLayer(outlineColor.alphaAsFloat());
1983         outlineColor = outlineColor.opaqueColor();
1984     }
1985
1986     float leftOuter = outer.x();
1987     float leftInner = inner.x();
1988     float rightOuter = outer.maxX();
1989     float rightInner = std::min(inner.maxX(), rightOuter);
1990     float topOuter = outer.y();
1991     float topInner = inner.y();
1992     float bottomOuter = outer.maxY();
1993     float bottomInner = std::min(inner.maxY(), bottomOuter);
1994
1995     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(leftInner, bottomOuter)), BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1996     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(rightOuter, topInner)), BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1997     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(rightInner, topOuter), FloatPoint(rightOuter, bottomOuter)), BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1998     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, bottomInner), FloatPoint(rightOuter, bottomOuter)), BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
1999
2000     if (useTransparencyLayer)
2001         graphicsContext.endTransparencyLayer();
2002 }
2003
2004 void RenderElement::issueRepaintForOutlineAuto(float outlineSize)
2005 {
2006     LayoutRect repaintRect;
2007     Vector<LayoutRect> focusRingRects;
2008     addFocusRingRects(focusRingRects, LayoutPoint(), containerForRepaint());
2009     for (auto rect : focusRingRects) {
2010         rect.inflate(outlineSize);
2011         repaintRect.unite(rect);
2012     }
2013     repaintRectangle(repaintRect);
2014 }
2015
2016 void RenderElement::updateOutlineAutoAncestor(bool hasOutlineAuto)
2017 {
2018     for (auto& child : childrenOfType<RenderObject>(*this)) {
2019         if (hasOutlineAuto == child.hasOutlineAutoAncestor())
2020             continue;
2021         child.setHasOutlineAutoAncestor(hasOutlineAuto);
2022         bool childHasOutlineAuto = child.outlineStyleForRepaint().outlineStyleIsAuto();
2023         if (childHasOutlineAuto)
2024             continue;
2025         if (!is<RenderElement>(child))
2026             continue;
2027         downcast<RenderElement>(child).updateOutlineAutoAncestor(hasOutlineAuto);
2028     }
2029     if (is<RenderBoxModelObject>(*this)) {
2030         if (auto* continuation = downcast<RenderBoxModelObject>(*this).continuation())
2031             continuation->updateOutlineAutoAncestor(hasOutlineAuto);
2032     }
2033 }
2034
2035 bool RenderElement::hasOutlineAnnotation() const
2036 {
2037     return element() && element()->isLink() && document().printing();
2038 }
2039
2040 bool RenderElement::hasSelfPaintingLayer() const
2041 {
2042     if (!hasLayer())
2043         return false;
2044     auto& layerModelObject = downcast<RenderLayerModelObject>(*this);
2045     return layerModelObject.hasSelfPaintingLayer();
2046 }
2047
2048 bool RenderElement::checkForRepaintDuringLayout() const
2049 {
2050     if (document().view()->layoutContext().needsFullRepaint() || !everHadLayout() || hasSelfPaintingLayer())
2051         return false;
2052     return !settings().repaintOutsideLayoutEnabled();
2053 }
2054
2055 RespectImageOrientationEnum RenderElement::shouldRespectImageOrientation() const
2056 {
2057 #if USE(CG) || USE(CAIRO)
2058     // This can only be enabled for ports which honor the orientation flag in their drawing code.
2059     if (document().isImageDocument())
2060         return RespectImageOrientation;
2061 #endif
2062     // Respect the image's orientation if it's being used as a full-page image or it's
2063     // an <img> and the setting to respect it everywhere is set.
2064     return settings().shouldRespectImageOrientation() && is<HTMLImageElement>(element()) ? RespectImageOrientation : DoNotRespectImageOrientation;
2065 }
2066
2067 void RenderElement::adjustFragmentedFlowStateOnContainingBlockChangeIfNeeded()
2068 {
2069     if (fragmentedFlowState() == NotInsideFragmentedFlow)
2070         return;
2071
2072     // Invalidate the containing block caches.
2073     if (is<RenderBlock>(*this))
2074         downcast<RenderBlock>(*this).resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants();
2075     
2076     // Adjust the flow tread state on the subtree.
2077     setFragmentedFlowState(RenderObject::computedFragmentedFlowState(*this));
2078     for (auto& descendant : descendantsOfType<RenderObject>(*this))
2079         descendant.setFragmentedFlowState(RenderObject::computedFragmentedFlowState(descendant));
2080 }
2081
2082 void RenderElement::removeFromRenderFragmentedFlow()
2083 {
2084     ASSERT(fragmentedFlowState() != NotInsideFragmentedFlow);
2085     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2086     // It's only until later when we actually destroy it and remove all the children from it.
2087     // Currently, that happens for firstLetter elements and list markers.
2088     // Pass in the flow thread so that we don't have to look it up for all the children.
2089     removeFromRenderFragmentedFlowIncludingDescendants(true);
2090 }
2091
2092 void RenderElement::removeFromRenderFragmentedFlowIncludingDescendants(bool shouldUpdateState)
2093 {
2094     // Once we reach another flow thread we don't need to update the flow thread state
2095     // but we have to continue cleanup the flow thread info.
2096     if (isRenderFragmentedFlow())
2097         shouldUpdateState = false;
2098
2099     for (auto& child : childrenOfType<RenderObject>(*this)) {
2100         if (is<RenderElement>(child)) {
2101             downcast<RenderElement>(child).removeFromRenderFragmentedFlowIncludingDescendants(shouldUpdateState);
2102             continue;
2103         }
2104         if (shouldUpdateState)
2105             child.setFragmentedFlowState(NotInsideFragmentedFlow);
2106     }
2107
2108     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
2109     RenderFragmentedFlow* enclosingFragmentedFlow = this->enclosingFragmentedFlow();
2110     while (enclosingFragmentedFlow) {
2111         enclosingFragmentedFlow->removeFlowChildInfo(*this);
2112
2113         if (enclosingFragmentedFlow->fragmentedFlowState() == NotInsideFragmentedFlow)
2114             break;
2115         auto* parent = enclosingFragmentedFlow->parent();
2116         if (!parent)
2117             break;
2118         enclosingFragmentedFlow = parent->enclosingFragmentedFlow();
2119     }
2120     if (is<RenderBlock>(*this))
2121         downcast<RenderBlock>(*this).setCachedEnclosingFragmentedFlowNeedsUpdate();
2122
2123     if (shouldUpdateState)
2124         setFragmentedFlowState(NotInsideFragmentedFlow);
2125 }
2126
2127 void RenderElement::resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants(RenderFragmentedFlow* fragmentedFlow)
2128 {
2129     if (fragmentedFlow)
2130         fragmentedFlow->removeFlowChildInfo(*this);
2131
2132     for (auto& child : childrenOfType<RenderElement>(*this))
2133         child.resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants(fragmentedFlow);
2134 }
2135
2136 #if ENABLE(TEXT_AUTOSIZING)
2137 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject& renderer)
2138 {
2139     const RenderStyle& style = renderer.style();
2140     if (style.height().type() == Fixed) {
2141         if (is<RenderBlock>(renderer)) {
2142             // For fixed height styles, if the overflow size of the element spills out of the specified
2143             // height, assume we can apply text auto-sizing.
2144             if (style.overflowY() == OVISIBLE
2145                 && style.height().value() < downcast<RenderBlock>(renderer).layoutOverflowRect().maxY())
2146                 return RenderObject::OverflowHeight;
2147         }
2148         return RenderObject::FixedHeight;
2149     }
2150     return RenderObject::FlexibleHeight;
2151 }
2152
2153 void RenderElement::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
2154 {
2155     Document* document = view().frameView().frame().document();
2156     if (!document)
2157         return;
2158
2159     Vector<int> depthStack;
2160     int currentDepth = 0;
2161     int newFixedDepth = 0;
2162
2163     // We don't apply autosizing to nodes with fixed height normally.
2164     // But we apply it to nodes which are located deep enough
2165     // (nesting depth is greater than some const) inside of a parent block
2166     // which has fixed height but its content overflows intentionally.
2167     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2168         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2169             depthStack.remove(depthStack.size() - 1);
2170         if (newFixedDepth)
2171             depthStack.append(newFixedDepth);
2172
2173         int stackSize = depthStack.size();
2174         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2175             downcast<RenderBlockFlow>(*descendent).adjustComputedFontSizes(size, visibleWidth);
2176         newFixedDepth = 0;
2177     }
2178
2179     // Remove style from auto-sizing table that are no longer valid.
2180     document->textAutoSizing().updateRenderTree();
2181 }
2182
2183 void RenderElement::resetTextAutosizing()
2184 {
2185     Document* document = view().frameView().frame().document();
2186     if (!document)
2187         return;
2188
2189     LOG(TextAutosizing, "RenderElement::resetTextAutosizing()");
2190
2191     document->textAutoSizing().reset();
2192
2193     Vector<int> depthStack;
2194     int currentDepth = 0;
2195     int newFixedDepth = 0;
2196
2197     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2198         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2199             depthStack.remove(depthStack.size() - 1);
2200         if (newFixedDepth)
2201             depthStack.append(newFixedDepth);
2202
2203         int stackSize = depthStack.size();
2204         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2205             downcast<RenderBlockFlow>(*descendent).resetComputedFontSize();
2206         newFixedDepth = 0;
2207     }
2208 }
2209 #endif // ENABLE(TEXT_AUTOSIZING)
2210
2211 }