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