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