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