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