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