Remove monotonicallyIncreasingTime
[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 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
98     : RenderObject(elementOrDocument)
99     , m_baseTypeFlags(baseTypeFlags)
100     , m_ancestorLineBoxDirty(false)
101     , m_hasInitializedStyle(false)
102     , m_renderInlineAlwaysCreatesLineBoxes(false)
103     , m_renderBoxNeedsLazyRepaint(false)
104     , m_hasPausedImageAnimations(false)
105     , m_hasCounterNodeMap(false)
106     , m_hasContinuationChainNode(false)
107     , m_isContinuation(false)
108     , m_isFirstLetter(false)
109     , m_hasValidCachedFirstLineStyle(false)
110     , m_renderBlockHasMarginBeforeQuirk(false)
111     , m_renderBlockHasMarginAfterQuirk(false)
112     , m_renderBlockShouldForceRelayoutChildren(false)
113     , m_renderBlockFlowHasMarkupTruncation(false)
114     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
115     , m_isRegisteredForVisibleInViewportCallback(false)
116     , m_visibleInViewportState(static_cast<unsigned>(VisibleInViewportState::Unknown))
117     , m_firstChild(nullptr)
118     , m_lastChild(nullptr)
119     , m_style(WTFMove(style))
120 {
121 }
122
123 RenderElement::RenderElement(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
124     : RenderElement(static_cast<ContainerNode&>(element), WTFMove(style), baseTypeFlags)
125 {
126 }
127
128 RenderElement::RenderElement(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
129     : RenderElement(static_cast<ContainerNode&>(document), WTFMove(style), baseTypeFlags)
130 {
131 }
132
133 RenderElement::~RenderElement()
134 {
135     // Do not add any code here. Add it to willBeDestroyed() instead.
136     ASSERT(!m_firstChild);
137 }
138
139 RenderPtr<RenderElement> RenderElement::createFor(Element& element, RenderStyle&& style, RendererCreationType creationType)
140 {
141     // Minimal support for content properties replacing an entire element.
142     // Works only if we have exactly one piece of content and it's a URL.
143     // Otherwise acts as if we didn't support this feature.
144     const ContentData* contentData = style.contentData();
145     if (creationType == CreateAllRenderers && contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
146         Style::loadPendingResources(style, element.document(), &element);
147         auto& styleImage = downcast<ImageContentData>(*contentData).image();
148         auto image = createRenderer<RenderImage>(element, WTFMove(style), const_cast<StyleImage*>(&styleImage));
149         image->setIsGeneratedContent();
150         return WTFMove(image);
151     }
152
153     switch (style.display()) {
154     case NONE:
155     case CONTENTS:
156         return nullptr;
157     case INLINE:
158         if (creationType == CreateAllRenderers)
159             return createRenderer<RenderInline>(element, WTFMove(style));
160         FALLTHROUGH; // Fieldsets should make a block flow if display:inline is set.
161     case BLOCK:
162     case INLINE_BLOCK:
163     case COMPACT:
164         return createRenderer<RenderBlockFlow>(element, WTFMove(style));
165     case LIST_ITEM:
166         return createRenderer<RenderListItem>(element, WTFMove(style));
167     case FLEX:
168     case INLINE_FLEX:
169     case WEBKIT_FLEX:
170     case WEBKIT_INLINE_FLEX:
171         return createRenderer<RenderFlexibleBox>(element, WTFMove(style));
172     case GRID:
173     case INLINE_GRID:
174         return createRenderer<RenderGrid>(element, WTFMove(style));
175     case BOX:
176     case INLINE_BOX:
177         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTFMove(style));
178     default: {
179         if (creationType == OnlyCreateBlockAndFlexboxRenderers)
180             return createRenderer<RenderBlockFlow>(element, WTFMove(style));
181         switch (style.display()) {
182         case TABLE:
183         case INLINE_TABLE:
184             return createRenderer<RenderTable>(element, WTFMove(style));
185         case TABLE_CELL:
186             return createRenderer<RenderTableCell>(element, WTFMove(style));
187         case TABLE_CAPTION:
188             return createRenderer<RenderTableCaption>(element, WTFMove(style));
189         case TABLE_ROW_GROUP:
190         case TABLE_HEADER_GROUP:
191         case TABLE_FOOTER_GROUP:
192             return createRenderer<RenderTableSection>(element, WTFMove(style));
193         case TABLE_ROW:
194             return createRenderer<RenderTableRow>(element, WTFMove(style));
195         case TABLE_COLUMN_GROUP:
196         case TABLE_COLUMN:
197             return createRenderer<RenderTableCol>(element, WTFMove(style));
198         default:
199             break;
200         }
201         break;
202     }
203     }
204     ASSERT_NOT_REACHED();
205     return nullptr;
206 }
207
208 std::unique_ptr<RenderStyle> RenderElement::computeFirstLineStyle() const
209 {
210     ASSERT(view().usesFirstLineRules());
211
212     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
213
214     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
215         RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock();
216         if (!firstLineBlock)
217             return nullptr;
218         auto* firstLineStyle = firstLineBlock->getCachedPseudoStyle(FIRST_LINE, &style());
219         if (!firstLineStyle)
220             return nullptr;
221         return RenderStyle::clonePtr(*firstLineStyle);
222     }
223
224     if (!rendererForFirstLineStyle.isRenderInline())
225         return nullptr;
226
227     auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
228     if (&parentStyle == &rendererForFirstLineStyle.parent()->style())
229         return nullptr;
230
231     if (rendererForFirstLineStyle.isAnonymous()) {
232         auto* textRendererWithDisplayContentsParent = RenderText::findByDisplayContentsInlineWrapperCandidate(rendererForFirstLineStyle);
233         if (!textRendererWithDisplayContentsParent)
234             return nullptr;
235         auto* composedTreeParentElement = textRendererWithDisplayContentsParent->textNode()->parentElementInComposedTree();
236         if (!composedTreeParentElement)
237             return nullptr;
238
239         auto style = composedTreeParentElement->styleResolver().styleForElement(*composedTreeParentElement, &parentStyle).renderStyle;
240         ASSERT(style->display() == CONTENTS);
241
242         // We act as if there was an unstyled <span> around the text node. Only styling happens via inheritance.
243         auto firstLineStyle = RenderStyle::createPtr();
244         firstLineStyle->inheritFrom(*style);
245         return firstLineStyle;
246     }
247
248     return rendererForFirstLineStyle.element()->styleResolver().styleForElement(*element(), &parentStyle).renderStyle;
249 }
250
251 const RenderStyle& RenderElement::firstLineStyle() const
252 {
253     if (!view().usesFirstLineRules())
254         return style();
255
256     if (!m_hasValidCachedFirstLineStyle) {
257         auto firstLineStyle = computeFirstLineStyle();
258         if (firstLineStyle || hasRareData())
259             const_cast<RenderElement&>(*this).ensureRareData().cachedFirstLineStyle = WTFMove(firstLineStyle);
260         m_hasValidCachedFirstLineStyle = true;
261     }
262
263     return (hasRareData() && rareData().cachedFirstLineStyle) ? *rareData().cachedFirstLineStyle : style();
264 }
265
266 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
267 {
268     // If transform changed, and we are not composited, need to do a layout.
269     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
270         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
271         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
272             if (!hasLayer())
273                 diff = std::max(diff, StyleDifferenceLayout);
274             else {
275                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
276                 // then we actually need SimplifiedLayoutAndPositionedMovement.
277                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
278             }
279         
280         } else
281             diff = std::max(diff, StyleDifferenceRecompositeLayer);
282     }
283
284     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
285         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
286             diff = std::max(diff, StyleDifferenceRepaintLayer);
287         else
288             diff = std::max(diff, StyleDifferenceRecompositeLayer);
289     }
290
291     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
292         if (hasLayer()
293             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
294             && hasClipPath()
295             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
296             diff = std::max(diff, StyleDifferenceRecompositeLayer);
297         else
298             diff = std::max(diff, StyleDifferenceRepaint);
299     }
300     
301     if (contextSensitiveProperties & ContextSensitivePropertyWillChange) {
302         if (style().willChange() && style().willChange()->canTriggerCompositing())
303             diff = std::max(diff, StyleDifferenceRecompositeLayer);
304     }
305     
306     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
307         auto& layer = *downcast<RenderLayerModelObject>(*this).layer();
308         if (!layer.isComposited() || layer.paintsWithFilters())
309             diff = std::max(diff, StyleDifferenceRepaintLayer);
310         else
311             diff = std::max(diff, StyleDifferenceRecompositeLayer);
312     }
313     
314     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
315     // style changing, since it depends on whether we decide to composite these elements. When the
316     // layer status of one of these elements changes, we need to force a layout.
317     if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
318         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
319             diff = StyleDifferenceLayout;
320     }
321
322     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
323     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
324         diff = StyleDifferenceRepaint;
325
326     return diff;
327 }
328
329 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
330 {
331     for (auto& child : childrenOfType<RenderObject>(*this)) {
332         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
333             return true;
334         if (child.style().hasOutline() || child.style().hasBorder())
335             return true;
336     }
337     return false;
338 }
339
340 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
341 {
342     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
343 }
344
345 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer& newLayers)
346 {
347     // Optimize the common case.
348     if (FillLayer::imagesIdentical(oldLayers, &newLayers))
349         return;
350     
351     // Add before removing, to avoid removing all clients of an image that is in both sets.
352     for (auto* layer = &newLayers; layer; layer = layer->next()) {
353         if (layer->image())
354             layer->image()->addClient(this);
355     }
356     for (auto* layer = oldLayers; layer; layer = layer->next()) {
357         if (layer->image())
358             layer->image()->removeClient(this);
359     }
360 }
361
362 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
363 {
364     if (oldImage == newImage)
365         return;
366     if (oldImage)
367         oldImage->removeClient(this);
368     if (newImage)
369         newImage->addClient(this);
370 }
371
372 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
373 {
374     if (oldShapeValue || newShapeValue)
375         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
376 }
377
378 void RenderElement::initializeStyle()
379 {
380     Style::loadPendingResources(m_style, document(), element());
381
382     styleWillChange(StyleDifferenceNewStyle, style());
383     m_hasInitializedStyle = true;
384     styleDidChange(StyleDifferenceNewStyle, nullptr);
385
386     // We shouldn't have any text children that would need styleDidChange at this point.
387     ASSERT(!childrenOfType<RenderText>(*this).first());
388
389     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
390     // have their parent set before getting a call to initializeStyle() :|
391 }
392
393 void RenderElement::setStyle(RenderStyle&& style, StyleDifference minimalStyleDifference)
394 {
395     // FIXME: Should change RenderView so it can use initializeStyle too.
396     // If we do that, we can assert m_hasInitializedStyle unconditionally,
397     // and remove the check of m_hasInitializedStyle below too.
398     ASSERT(m_hasInitializedStyle || isRenderView());
399
400     StyleDifference diff = StyleDifferenceEqual;
401     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
402     if (m_hasInitializedStyle)
403         diff = m_style.diff(style, contextSensitiveProperties);
404
405     diff = std::max(diff, minimalStyleDifference);
406
407     diff = adjustStyleDifference(diff, contextSensitiveProperties);
408
409     Style::loadPendingResources(style, document(), element());
410
411     styleWillChange(diff, style);
412     auto oldStyle = m_style.replace(WTFMove(style));
413     bool detachedFromParent = !parent();
414
415     // Make sure we invalidate the containing block cache for flows when the contianing block context changes
416     // so that styleDidChange can safely use RenderBlock::locateEnclosingFragmentedFlow()
417     if (oldStyle.position() != m_style.position())
418         adjustFragmentedFlowStateOnContainingBlockChangeIfNeeded();
419
420     styleDidChange(diff, &oldStyle);
421
422     // Text renderers use their parent style. Notify them about the change.
423     for (auto& child : childrenOfType<RenderText>(*this))
424         child.styleDidChange(diff, &oldStyle);
425
426     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
427     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
428     // we will safely bail out with the detachedFromParent flag. We might want to broaden this condition
429     // in the future as we move renderer changes out of layout and into style changes.
430     if (detachedFromParent)
431         return;
432
433     // Now that the layer (if any) has been updated, we need to adjust the diff again,
434     // check whether we should layout now, and decide if we need to repaint.
435     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
436     
437     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
438         if (updatedDiff == StyleDifferenceLayout)
439             setNeedsLayoutAndPrefWidthsRecalc();
440         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
441             setNeedsPositionedMovementLayout(&oldStyle);
442         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
443             setNeedsPositionedMovementLayout(&oldStyle);
444             setNeedsSimplifiedNormalFlowLayout();
445         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
446             setNeedsSimplifiedNormalFlowLayout();
447     }
448
449     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
450         // Do a repaint with the new style now, e.g., for example if we go from
451         // not having an outline to having an outline.
452         repaint();
453     }
454 }
455
456 void RenderElement::didAttachChild(RenderObject& child, RenderObject*)
457 {
458     if (is<RenderText>(child))
459         downcast<RenderText>(child).styleDidChange(StyleDifferenceEqual, nullptr);
460     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
461     // <g>s to have renderers - at least that's how our implementation works. Consider:
462     // <g display="none"><foreignObject><body style="position: relative">FOO...
463     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
464     // - when the document is painted, both layers are painted. The <body> layer doesn't
465     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
466     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
467     // and stop creating layers at all for these cases - they're not used anyways.
468     if (child.hasLayer() && !layerCreationAllowedForSubtree())
469         downcast<RenderLayerModelObject>(child).layer()->removeOnlyThisLayer();
470     SVGRenderSupport::childAdded(*this, child);
471 }
472
473 RenderObject* RenderElement::attachRendererInternal(RenderPtr<RenderObject> child, RenderObject* beforeChild)
474 {
475     child->setParent(this);
476
477     if (m_firstChild == beforeChild)
478         m_firstChild = child.get();
479
480     if (beforeChild) {
481         auto* previousSibling = beforeChild->previousSibling();
482         if (previousSibling)
483             previousSibling->setNextSibling(child.get());
484         child->setPreviousSibling(previousSibling);
485         child->setNextSibling(beforeChild);
486         beforeChild->setPreviousSibling(child.get());
487         return child.release();
488     }
489     if (m_lastChild)
490         m_lastChild->setNextSibling(child.get());
491     child->setPreviousSibling(m_lastChild);
492     m_lastChild = child.get();
493     return child.release();
494 }
495
496 RenderPtr<RenderObject> RenderElement::detachRendererInternal(RenderObject& renderer)
497 {
498     auto* parent = renderer.parent();
499     ASSERT(parent);
500     auto* nextSibling = renderer.nextSibling();
501
502     if (renderer.previousSibling())
503         renderer.previousSibling()->setNextSibling(nextSibling);
504     if (nextSibling)
505         nextSibling->setPreviousSibling(renderer.previousSibling());
506
507     if (parent->firstChild() == &renderer)
508         parent->m_firstChild = nextSibling;
509     if (parent->lastChild() == &renderer)
510         parent->m_lastChild = renderer.previousSibling();
511
512     renderer.setPreviousSibling(nullptr);
513     renderer.setNextSibling(nullptr);
514     renderer.setParent(nullptr);
515     return RenderPtr<RenderObject>(&renderer);
516 }
517
518 RenderBlock* RenderElement::containingBlockForFixedPosition() const
519 {
520     auto* renderer = parent();
521     while (renderer && !renderer->canContainFixedPositionObjects())
522         renderer = renderer->parent();
523
524     ASSERT(!renderer || !renderer->isAnonymousBlock());
525     return downcast<RenderBlock>(renderer);
526 }
527
528 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
529 {
530     // A relatively positioned RenderInline forwards its absolute positioned descendants to
531     // its nearest non-anonymous containing block (to avoid having a positioned objects list in all RenderInlines).
532     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
533     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
534         renderer = renderer->parent();
535     // Make sure we only return non-anonymous RenderBlock as containing block.
536     while (renderer && (!is<RenderBlock>(*renderer) || renderer->isAnonymousBlock()))
537         renderer = renderer->containingBlock();
538     return downcast<RenderBlock>(renderer);
539 }
540
541 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
542 {
543     if (renderer.hasLayer()) {
544         if (!beforeChild && newObject) {
545             // We need to figure out the layer that follows newObject. We only do
546             // this the first time we find a child layer, and then we update the
547             // pointer values for newObject and beforeChild used by everyone else.
548             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
549             newObject = nullptr;
550         }
551         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
552         return;
553     }
554
555     for (auto& child : childrenOfType<RenderElement>(renderer))
556         addLayers(child, parentLayer, newObject, beforeChild);
557 }
558
559 void RenderElement::addLayers(RenderLayer* parentLayer)
560 {
561     if (!parentLayer)
562         return;
563
564     RenderElement* renderer = this;
565     RenderLayer* beforeChild = nullptr;
566     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
567 }
568
569 void RenderElement::removeLayers(RenderLayer* parentLayer)
570 {
571     if (!parentLayer)
572         return;
573
574     if (hasLayer()) {
575         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
576         return;
577     }
578
579     for (auto& child : childrenOfType<RenderElement>(*this))
580         child.removeLayers(parentLayer);
581 }
582
583 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
584 {
585     if (!newParent)
586         return;
587
588     if (hasLayer()) {
589         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
590         ASSERT(oldParent == layer->parent());
591         if (oldParent)
592             oldParent->removeChild(layer);
593         newParent->addChild(layer);
594         return;
595     }
596
597     for (auto& child : childrenOfType<RenderElement>(*this))
598         child.moveLayers(oldParent, newParent);
599 }
600
601 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
602 {
603     // Error check the parent layer passed in. If it's null, we can't find anything.
604     if (!parentLayer)
605         return nullptr;
606
607     // Step 1: If our layer is a child of the desired parent, then return our layer.
608     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
609     if (ourLayer && ourLayer->parent() == parentLayer)
610         return ourLayer;
611
612     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
613     // into our siblings trying to find the next layer whose parent is the desired parent.
614     if (!ourLayer || ourLayer == parentLayer) {
615         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
616             if (!is<RenderElement>(*child))
617                 continue;
618             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
619             if (nextLayer)
620                 return nextLayer;
621         }
622     }
623
624     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
625     // find anything.
626     if (parentLayer == ourLayer)
627         return nullptr;
628
629     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
630     // follow us to see if we can locate a layer.
631     if (checkParent && parent())
632         return parent()->findNextLayer(parentLayer, this, true);
633
634     return nullptr;
635 }
636
637 bool RenderElement::layerCreationAllowedForSubtree() const
638 {
639     RenderElement* parentRenderer = parent();
640     while (parentRenderer) {
641         if (parentRenderer->isSVGHiddenContainer())
642             return false;
643         parentRenderer = parentRenderer->parent();
644     }
645     
646     return true;
647 }
648
649 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
650 {
651     // FIXME: We could save this call when the change only affected non-inherited properties.
652     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
653         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
654             continue;
655
656         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
657             continue;
658
659 #if ENABLE(FULLSCREEN_API)
660         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
661             continue;
662 #endif
663
664         // RenderFragmentedFlows are updated through the RenderView::styleDidChange function.
665         if (is<RenderFragmentedFlow>(elementChild))
666             continue;
667
668         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style().display());
669         if (style().specifiesColumns()) {
670             if (elementChild.style().specifiesColumns())
671                 newStyle.inheritColumnPropertiesFrom(style());
672             if (elementChild.style().columnSpan())
673                 newStyle.setColumnSpan(ColumnSpanAll);
674         }
675
676         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
677         // they contain block descendants of relative or sticky positioned inlines.
678         if (elementChild.isInFlowPositioned() && elementChild.isContinuation())
679             newStyle.setPosition(elementChild.style().position());
680
681         updateAnonymousChildStyle(newStyle);
682         
683         elementChild.setStyle(WTFMove(newStyle));
684     }
685 }
686
687 static inline bool rendererHasBackground(const RenderElement* renderer)
688 {
689     return renderer && renderer->hasBackground();
690 }
691
692 void RenderElement::invalidateCachedFirstLineStyle()
693 {
694     if (!m_hasValidCachedFirstLineStyle)
695         return;
696     m_hasValidCachedFirstLineStyle = false;
697     // Invalidate the subtree as descendant's first line style may depend on ancestor's.
698     for (auto& descendant : descendantsOfType<RenderElement>(*this))
699         descendant.m_hasValidCachedFirstLineStyle = false;
700 }
701
702 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
703 {
704     auto* oldStyle = hasInitializedStyle() ? &style() : nullptr;
705     if (oldStyle) {
706         // If our z-index changes value or our visibility changes,
707         // we need to dirty our stacking context's z-order list.
708         bool visibilityChanged = m_style.visibility() != newStyle.visibility()
709             || m_style.zIndex() != newStyle.zIndex()
710             || m_style.hasAutoZIndex() != newStyle.hasAutoZIndex();
711 #if ENABLE(DASHBOARD_SUPPORT)
712         if (visibilityChanged)
713             document().setAnnotatedRegionsDirty(true);
714 #endif
715 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
716         if (visibilityChanged)
717             document().setTouchEventRegionsNeedUpdate();
718 #endif
719         if (visibilityChanged) {
720             if (AXObjectCache* cache = document().existingAXObjectCache())
721                 cache->childrenChanged(parent(), this);
722         }
723
724         // Keep layer hierarchy visibility bits up to date if visibility changes.
725         if (m_style.visibility() != newStyle.visibility()) {
726             if (RenderLayer* layer = enclosingLayer()) {
727                 if (newStyle.visibility() == VISIBLE)
728                     layer->setHasVisibleContent();
729                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
730                     layer->dirtyVisibleContentStatus();
731                     if (diff > StyleDifferenceRepaintLayer)
732                         repaint();
733                 }
734             }
735         }
736
737         if (m_parent && (newStyle.outlineSize() < m_style.outlineSize() || shouldRepaintForStyleDifference(diff)))
738             repaint();
739         if (isFloating() && m_style.floating() != newStyle.floating()) {
740             // For changes in float styles, we need to conceivably remove ourselves
741             // from the floating objects list.
742             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
743         } else if (isOutOfFlowPositioned() && m_style.position() != newStyle.position()) {
744             // For changes in positioning styles, we need to conceivably remove ourselves
745             // from the positioned objects list.
746             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
747         }
748
749         // reset style flags
750         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
751             setFloating(false);
752             clearPositionedState();
753         }
754         if (newStyle.hasPseudoStyle(FIRST_LINE) || oldStyle->hasPseudoStyle(FIRST_LINE))
755             invalidateCachedFirstLineStyle();
756
757         setHorizontalWritingMode(true);
758         setHasVisibleBoxDecorations(false);
759         setHasOverflowClip(false);
760         setHasTransformRelatedProperty(false);
761         setHasReflection(false);
762     }
763
764     bool newStyleSlowScroll = false;
765     if (newStyle.hasFixedBackgroundImage() && !settings().fixedBackgroundsPaintRelativeToDocument()) {
766         newStyleSlowScroll = true;
767         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
768         if (drawsRootBackground && newStyle.hasEntirelyFixedBackground() && view().compositor().supportsFixedRootBackgroundCompositing())
769             newStyleSlowScroll = false;
770     }
771
772     if (view().frameView().hasSlowRepaintObject(*this)) {
773         if (!newStyleSlowScroll)
774             view().frameView().removeSlowRepaintObject(*this);
775     } else if (newStyleSlowScroll)
776         view().frameView().addSlowRepaintObject(*this);
777
778     if (isDocumentElementRenderer() || isBody())
779         view().frameView().updateExtendBackgroundIfNecessary();
780 }
781
782 #if !PLATFORM(IOS)
783 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
784 {
785     ASSERT(a->cursors() != b->cursors());
786     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
787 }
788
789 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
790 {
791     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
792 }
793 #endif
794
795 bool RenderElement::noLongerAffectsParentBlock(const RenderStyle& oldStyle) const
796 {
797     return parent() && parent()->isRenderBlock()
798         && ((!oldStyle.isFloating() && style().isFloating()) || (!oldStyle.hasOutOfFlowPosition() && style().hasOutOfFlowPosition()));
799 }
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 (oldStyle && noLongerAffectsParentBlock(*oldStyle))
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().seconds(), needsRepaint);
1861     } else
1862         paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, page().focusController().timeSinceFocusWasSet().seconds(), 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 }