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