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