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