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