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