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