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