Make more of the CSS animation system internals element based
[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_hasContinuation(false)
111     , m_hasValidCachedFirstLineStyle(false)
112     , m_renderBlockHasMarginBeforeQuirk(false)
113     , m_renderBlockHasMarginAfterQuirk(false)
114     , m_renderBlockShouldForceRelayoutChildren(false)
115     , m_renderBlockFlowHasMarkupTruncation(false)
116     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
117     , m_isRegisteredForVisibleInViewportCallback(false)
118     , m_visibleInViewportState(static_cast<unsigned>(VisibleInViewportState::Unknown))
119     , m_firstChild(nullptr)
120     , m_lastChild(nullptr)
121     , m_style(WTFMove(style))
122 {
123 }
124
125 RenderElement::RenderElement(Element& element, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
126     : RenderElement(static_cast<ContainerNode&>(element), WTFMove(style), baseTypeFlags)
127 {
128 }
129
130 RenderElement::RenderElement(Document& document, RenderStyle&& style, BaseTypeFlags baseTypeFlags)
131     : RenderElement(static_cast<ContainerNode&>(document), WTFMove(style), baseTypeFlags)
132 {
133 }
134
135 RenderElement::~RenderElement()
136 {
137     // Do not add any code here. Add it to willBeDestroyed() instead.
138 }
139
140 RenderPtr<RenderElement> RenderElement::createFor(Element& element, RenderStyle&& style, RendererCreationType creationType)
141 {
142     // Minimal support for content properties replacing an entire element.
143     // Works only if we have exactly one piece of content and it's a URL.
144     // Otherwise acts as if we didn't support this feature.
145     const ContentData* contentData = style.contentData();
146     if (creationType == CreateAllRenderers && contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
147         Style::loadPendingResources(style, element.document(), &element);
148         auto& styleImage = downcast<ImageContentData>(*contentData).image();
149         auto image = createRenderer<RenderImage>(element, WTFMove(style), const_cast<StyleImage*>(&styleImage));
150         image->setIsGeneratedContent();
151         return WTFMove(image);
152     }
153
154     switch (style.display()) {
155     case NONE:
156     case CONTENTS:
157         return nullptr;
158     case INLINE:
159         if (creationType == CreateAllRenderers)
160             return createRenderer<RenderInline>(element, WTFMove(style));
161         FALLTHROUGH; // Fieldsets should make a block flow if display:inline is set.
162     case BLOCK:
163     case INLINE_BLOCK:
164     case COMPACT:
165         return createRenderer<RenderBlockFlow>(element, WTFMove(style));
166     case LIST_ITEM:
167         return createRenderer<RenderListItem>(element, WTFMove(style));
168     case FLEX:
169     case INLINE_FLEX:
170     case WEBKIT_FLEX:
171     case WEBKIT_INLINE_FLEX:
172         return createRenderer<RenderFlexibleBox>(element, WTFMove(style));
173     case GRID:
174     case INLINE_GRID:
175         return createRenderer<RenderGrid>(element, WTFMove(style));
176     case BOX:
177     case INLINE_BOX:
178         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTFMove(style));
179     default: {
180         if (creationType == OnlyCreateBlockAndFlexboxRenderers)
181             return createRenderer<RenderBlockFlow>(element, WTFMove(style));
182         switch (style.display()) {
183         case TABLE:
184         case INLINE_TABLE:
185             return createRenderer<RenderTable>(element, WTFMove(style));
186         case TABLE_CELL:
187             return createRenderer<RenderTableCell>(element, WTFMove(style));
188         case TABLE_CAPTION:
189             return createRenderer<RenderTableCaption>(element, WTFMove(style));
190         case TABLE_ROW_GROUP:
191         case TABLE_HEADER_GROUP:
192         case TABLE_FOOTER_GROUP:
193             return createRenderer<RenderTableSection>(element, WTFMove(style));
194         case TABLE_ROW:
195             return createRenderer<RenderTableRow>(element, WTFMove(style));
196         case TABLE_COLUMN_GROUP:
197         case TABLE_COLUMN:
198             return createRenderer<RenderTableCol>(element, WTFMove(style));
199         default:
200             break;
201         }
202         break;
203     }
204     }
205     ASSERT_NOT_REACHED();
206     return nullptr;
207 }
208
209 std::unique_ptr<RenderStyle> RenderElement::computeFirstLineStyle() const
210 {
211     ASSERT(view().usesFirstLineRules());
212
213     RenderElement& rendererForFirstLineStyle = isBeforeOrAfterContent() ? *parent() : const_cast<RenderElement&>(*this);
214
215     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
216         RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock();
217         if (!firstLineBlock)
218             return nullptr;
219         auto* firstLineStyle = firstLineBlock->getCachedPseudoStyle(FIRST_LINE, &style());
220         if (!firstLineStyle)
221             return nullptr;
222         return RenderStyle::clonePtr(*firstLineStyle);
223     }
224
225     if (rendererForFirstLineStyle.isAnonymous() || !rendererForFirstLineStyle.isRenderInline())
226         return nullptr;
227
228     auto& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
229     if (&parentStyle == &rendererForFirstLineStyle.parent()->style())
230         return nullptr;
231     return rendererForFirstLineStyle.element()->styleResolver().styleForElement(*element(), &parentStyle).renderStyle;
232 }
233
234 const RenderStyle& RenderElement::firstLineStyle() const
235 {
236     if (!view().usesFirstLineRules())
237         return style();
238
239     if (!m_hasValidCachedFirstLineStyle) {
240         auto firstLineStyle = computeFirstLineStyle();
241         if (firstLineStyle || hasRareData())
242             const_cast<RenderElement&>(*this).ensureRareData().cachedFirstLineStyle = WTFMove(firstLineStyle);
243         m_hasValidCachedFirstLineStyle = true;
244     }
245
246     return (hasRareData() && rareData().cachedFirstLineStyle) ? *rareData().cachedFirstLineStyle : style();
247 }
248
249 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
250 {
251     // If transform changed, and we are not composited, need to do a layout.
252     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
253         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
254         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
255             if (!hasLayer())
256                 diff = std::max(diff, StyleDifferenceLayout);
257             else {
258                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
259                 // then we actually need SimplifiedLayoutAndPositionedMovement.
260                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
261             }
262         
263         } else
264             diff = std::max(diff, StyleDifferenceRecompositeLayer);
265     }
266
267     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
268         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
269             diff = std::max(diff, StyleDifferenceRepaintLayer);
270         else
271             diff = std::max(diff, StyleDifferenceRecompositeLayer);
272     }
273
274     if (contextSensitiveProperties & ContextSensitivePropertyClipPath) {
275         if (hasLayer()
276             && downcast<RenderLayerModelObject>(*this).layer()->isComposited()
277             && hasClipPath()
278             && RenderLayerCompositor::canCompositeClipPath(*downcast<RenderLayerModelObject>(*this).layer()))
279             diff = std::max(diff, StyleDifferenceRecompositeLayer);
280         else
281             diff = std::max(diff, StyleDifferenceRepaint);
282     }
283     
284     if (contextSensitiveProperties & ContextSensitivePropertyWillChange) {
285         if (style().willChange() && style().willChange()->canTriggerCompositing())
286             diff = std::max(diff, StyleDifferenceRecompositeLayer);
287     }
288     
289     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
290         auto& layer = *downcast<RenderLayerModelObject>(*this).layer();
291         if (!layer.isComposited() || layer.paintsWithFilters())
292             diff = std::max(diff, StyleDifferenceRepaintLayer);
293         else
294             diff = std::max(diff, StyleDifferenceRecompositeLayer);
295     }
296     
297     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
298     // style changing, since it depends on whether we decide to composite these elements. When the
299     // layer status of one of these elements changes, we need to force a layout.
300     if (diff < StyleDifferenceLayout && isRenderLayerModelObject()) {
301         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
302             diff = StyleDifferenceLayout;
303     }
304
305     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
306     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
307         diff = StyleDifferenceRepaint;
308
309     return diff;
310 }
311
312 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
313 {
314     for (auto& child : childrenOfType<RenderObject>(*this)) {
315         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
316             return true;
317         if (child.style().hasOutline() || child.style().hasBorder())
318             return true;
319     }
320     return false;
321 }
322
323 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
324 {
325     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
326 }
327
328 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer& newLayers)
329 {
330     // Optimize the common case.
331     if (FillLayer::imagesIdentical(oldLayers, &newLayers))
332         return;
333     
334     // Add before removing, to avoid removing all clients of an image that is in both sets.
335     for (auto* layer = &newLayers; layer; layer = layer->next()) {
336         if (layer->image())
337             layer->image()->addClient(this);
338     }
339     for (auto* layer = oldLayers; layer; layer = layer->next()) {
340         if (layer->image())
341             layer->image()->removeClient(this);
342     }
343 }
344
345 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
346 {
347     if (oldImage == newImage)
348         return;
349     if (oldImage)
350         oldImage->removeClient(this);
351     if (newImage)
352         newImage->addClient(this);
353 }
354
355 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
356 {
357     if (oldShapeValue || newShapeValue)
358         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
359 }
360
361 void RenderElement::initializeStyle()
362 {
363     Style::loadPendingResources(m_style, document(), element());
364
365     styleWillChange(StyleDifferenceNewStyle, style());
366     m_hasInitializedStyle = true;
367     styleDidChange(StyleDifferenceNewStyle, nullptr);
368
369     // We shouldn't have any text children that would need styleDidChange at this point.
370     ASSERT(!childrenOfType<RenderText>(*this).first());
371
372     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
373     // have their parent set before getting a call to initializeStyle() :|
374 }
375
376 void RenderElement::setStyle(RenderStyle&& style, StyleDifference minimalStyleDifference)
377 {
378     // FIXME: Should change RenderView so it can use initializeStyle too.
379     // If we do that, we can assert m_hasInitializedStyle unconditionally,
380     // and remove the check of m_hasInitializedStyle below too.
381     ASSERT(m_hasInitializedStyle || isRenderView());
382
383     StyleDifference diff = StyleDifferenceEqual;
384     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
385     if (m_hasInitializedStyle)
386         diff = m_style.diff(style, contextSensitiveProperties);
387
388     diff = std::max(diff, minimalStyleDifference);
389
390     diff = adjustStyleDifference(diff, contextSensitiveProperties);
391
392     Style::loadPendingResources(style, document(), element());
393
394     styleWillChange(diff, style);
395     auto oldStyle = m_style.replace(WTFMove(style));
396     bool detachedFromParent = !parent();
397
398     // Make sure we invalidate the containing block cache for flows when the contianing block context changes
399     // so that styleDidChange can safely use RenderBlock::locateFlowThreadContainingBlock()
400     if (oldStyle.position() != m_style.position())
401         adjustFlowThreadStateOnContainingBlockChangeIfNeeded();
402
403     styleDidChange(diff, &oldStyle);
404
405     // Text renderers use their parent style. Notify them about the change.
406     for (auto& child : childrenOfType<RenderText>(*this))
407         child.styleDidChange(diff, &oldStyle);
408
409     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
410     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
411     // we will safely bail out with the detachedFromParent flag. We might want to broaden this condition
412     // in the future as we move renderer changes out of layout and into style changes.
413     if (detachedFromParent)
414         return;
415
416     // Now that the layer (if any) has been updated, we need to adjust the diff again,
417     // check whether we should layout now, and decide if we need to repaint.
418     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
419     
420     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
421         if (updatedDiff == StyleDifferenceLayout)
422             setNeedsLayoutAndPrefWidthsRecalc();
423         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
424             setNeedsPositionedMovementLayout(&oldStyle);
425         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
426             setNeedsPositionedMovementLayout(&oldStyle);
427             setNeedsSimplifiedNormalFlowLayout();
428         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
429             setNeedsSimplifiedNormalFlowLayout();
430     }
431
432     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
433         // Do a repaint with the new style now, e.g., for example if we go from
434         // not having an outline to having an outline.
435         repaint();
436     }
437 }
438
439 bool RenderElement::childRequiresTable(const RenderObject& child) const
440 {
441     if (is<RenderTableCol>(child)) {
442         const RenderTableCol& newTableColumn = downcast<RenderTableCol>(child);
443         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
444         return !is<RenderTable>(*this) && !isColumnInColumnGroup;
445     }
446     if (is<RenderTableCaption>(child))
447         return !is<RenderTable>(*this);
448
449     if (is<RenderTableSection>(child))
450         return !is<RenderTable>(*this);
451
452     if (is<RenderTableRow>(child))
453         return !is<RenderTableSection>(*this);
454
455     if (is<RenderTableCell>(child))
456         return !is<RenderTableRow>(*this);
457
458     return false;
459 }
460
461 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
462 {
463     if (childRequiresTable(*newChild)) {
464         RenderTable* table;
465         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
466         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
467             table = downcast<RenderTable>(afterChild);
468         else {
469             table = RenderTable::createAnonymousWithParentRenderer(*this).release();
470             addChild(table, beforeChild);
471         }
472         table->addChild(newChild);
473     } else
474         insertChildInternal(newChild, beforeChild, NotifyChildren);
475
476     if (is<RenderText>(*newChild))
477         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
478
479     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
480     // <g>s to have renderers - at least that's how our implementation works. Consider:
481     // <g display="none"><foreignObject><body style="position: relative">FOO...
482     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
483     // - when the document is painted, both layers are painted. The <body> layer doesn't
484     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
485     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
486     // and stop creating layers at all for these cases - they're not used anyways.
487     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
488         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
489
490     SVGRenderSupport::childAdded(*this, *newChild);
491 }
492
493 void RenderElement::removeChild(RenderObject& oldChild)
494 {
495     removeChildInternal(oldChild, NotifyChildren);
496 }
497
498 void RenderElement::destroyLeftoverChildren()
499 {
500     while (m_firstChild) {
501         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
502             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
503         } else {
504             // 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.
505             if (m_firstChild->node())
506                 m_firstChild->node()->setRenderer(nullptr);
507             m_firstChild->destroy();
508         }
509     }
510 }
511
512 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
513 {
514     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
515     ASSERT(!newChild->parent());
516     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
517
518     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
519         beforeChild = beforeChild->parent();
520
521     // This should never happen, but if it does prevent render tree corruption
522     // where child->parent() ends up being owner but child->nextSibling()->parent()
523     // is not owner.
524     if (beforeChild && beforeChild->parent() != this) {
525         ASSERT_NOT_REACHED();
526         return;
527     }
528
529     newChild->setParent(this);
530
531     if (m_firstChild == beforeChild)
532         m_firstChild = newChild;
533
534     if (beforeChild) {
535         RenderObject* previousSibling = beforeChild->previousSibling();
536         if (previousSibling)
537             previousSibling->setNextSibling(newChild);
538         newChild->setPreviousSibling(previousSibling);
539         newChild->setNextSibling(beforeChild);
540         beforeChild->setPreviousSibling(newChild);
541     } else {
542         if (lastChild())
543             lastChild()->setNextSibling(newChild);
544         newChild->setPreviousSibling(lastChild());
545         m_lastChild = newChild;
546     }
547
548     newChild->initializeFlowThreadStateOnInsertion();
549     if (!renderTreeBeingDestroyed()) {
550         if (notifyChildren == NotifyChildren)
551             newChild->insertedIntoTree();
552         if (is<RenderElement>(*newChild))
553             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
554     }
555
556     newChild->setNeedsLayoutAndPrefWidthsRecalc();
557     setPreferredLogicalWidthsDirty(true);
558     if (!normalChildNeedsLayout())
559         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
560
561     if (AXObjectCache* cache = document().axObjectCache())
562         cache->childrenChanged(this, newChild);
563     if (is<RenderBlockFlow>(*this))
564         downcast<RenderBlockFlow>(*this).invalidateLineLayoutPath();
565     if (hasOutlineAutoAncestor() || outlineStyleForRepaint().outlineStyleIsAuto())
566         newChild->setHasOutlineAutoAncestor();
567 }
568
569 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
570 {
571     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
572     ASSERT(oldChild.parent() == this);
573
574     if (oldChild.isFloatingOrOutOfFlowPositioned())
575         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
576
577     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
578     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
579     // disappears gets repainted properly.
580     if (!renderTreeBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
581         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
582         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
583         if (oldChild.isBody())
584             view().repaintRootContents();
585         else
586             oldChild.repaint();
587     }
588
589     // If we have a line box wrapper, delete it.
590     if (is<RenderBox>(oldChild))
591         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
592     else if (is<RenderLineBreak>(oldChild))
593         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
594     
595     if (!renderTreeBeingDestroyed() && is<RenderFlexibleBox>(this) && !oldChild.isFloatingOrOutOfFlowPositioned() && oldChild.isBox())
596         downcast<RenderFlexibleBox>(this)->clearCachedChildIntrinsicContentLogicalHeight(downcast<RenderBox>(oldChild));
597
598     // If oldChild is the start or end of the selection, then clear the selection to
599     // avoid problems of invalid pointers.
600     if (!renderTreeBeingDestroyed() && oldChild.isSelectionBorder())
601         frame().selection().setNeedsSelectionUpdate();
602
603     if (!renderTreeBeingDestroyed() && notifyChildren == NotifyChildren)
604         oldChild.willBeRemovedFromTree();
605
606     oldChild.resetFlowThreadStateOnRemoval();
607
608     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
609     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
610     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
611     
612     RenderObject* nextSibling = oldChild.nextSibling();
613
614     if (oldChild.previousSibling())
615         oldChild.previousSibling()->setNextSibling(nextSibling);
616     if (nextSibling)
617         nextSibling->setPreviousSibling(oldChild.previousSibling());
618
619     if (m_firstChild == &oldChild)
620         m_firstChild = nextSibling;
621     if (m_lastChild == &oldChild)
622         m_lastChild = oldChild.previousSibling();
623
624     oldChild.setPreviousSibling(nullptr);
625     oldChild.setNextSibling(nullptr);
626     oldChild.setParent(nullptr);
627
628     // rendererRemovedFromTree walks the whole subtree. We can improve performance
629     // by skipping this step when destroying the entire tree.
630     if (!renderTreeBeingDestroyed() && is<RenderElement>(oldChild))
631         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
632
633     if (AXObjectCache* cache = document().existingAXObjectCache())
634         cache->childrenChanged(this);
635 #if !ASSERT_DISABLED
636     // Check if the marker gets detached while laying out the list item.
637     if (is<RenderListMarker>(oldChild))
638         ASSERT(m_reparentingChild || !downcast<RenderListMarker>(oldChild).listItem().inLayout());
639 #endif
640 }
641
642 RenderBlock* RenderElement::containingBlockForFixedPosition() const
643 {
644     auto* renderer = parent();
645     while (renderer && !renderer->canContainFixedPositionObjects())
646         renderer = renderer->parent();
647
648     ASSERT(!renderer || !renderer->isAnonymousBlock());
649     return downcast<RenderBlock>(renderer);
650 }
651
652 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
653 {
654     // A relatively positioned RenderInline forwards its absolute positioned descendants to
655     // its nearest non-anonymous containing block (to avoid having a positioned objects list in all RenderInlines).
656     auto* renderer = isRenderInline() ? const_cast<RenderElement*>(downcast<RenderElement>(this)) : parent();
657     while (renderer && !renderer->canContainAbsolutelyPositionedObjects())
658         renderer = renderer->parent();
659     // Make sure we only return non-anonymous RenderBlock as containing block.
660     while (renderer && (!is<RenderBlock>(*renderer) || renderer->isAnonymousBlock()))
661         renderer = renderer->containingBlock();
662     return downcast<RenderBlock>(renderer);
663 }
664
665 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
666 {
667     if (renderer.hasLayer()) {
668         if (!beforeChild && newObject) {
669             // We need to figure out the layer that follows newObject. We only do
670             // this the first time we find a child layer, and then we update the
671             // pointer values for newObject and beforeChild used by everyone else.
672             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
673             newObject = nullptr;
674         }
675         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
676         return;
677     }
678
679     for (auto& child : childrenOfType<RenderElement>(renderer))
680         addLayers(child, parentLayer, newObject, beforeChild);
681 }
682
683 void RenderElement::addLayers(RenderLayer* parentLayer)
684 {
685     if (!parentLayer)
686         return;
687
688     RenderElement* renderer = this;
689     RenderLayer* beforeChild = nullptr;
690     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
691 }
692
693 void RenderElement::removeLayers(RenderLayer* parentLayer)
694 {
695     if (!parentLayer)
696         return;
697
698     if (hasLayer()) {
699         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
700         return;
701     }
702
703     for (auto& child : childrenOfType<RenderElement>(*this))
704         child.removeLayers(parentLayer);
705 }
706
707 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
708 {
709     if (!newParent)
710         return;
711
712     if (hasLayer()) {
713         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
714         ASSERT(oldParent == layer->parent());
715         if (oldParent)
716             oldParent->removeChild(layer);
717         newParent->addChild(layer);
718         return;
719     }
720
721     for (auto& child : childrenOfType<RenderElement>(*this))
722         child.moveLayers(oldParent, newParent);
723 }
724
725 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
726 {
727     // Error check the parent layer passed in. If it's null, we can't find anything.
728     if (!parentLayer)
729         return nullptr;
730
731     // Step 1: If our layer is a child of the desired parent, then return our layer.
732     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
733     if (ourLayer && ourLayer->parent() == parentLayer)
734         return ourLayer;
735
736     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
737     // into our siblings trying to find the next layer whose parent is the desired parent.
738     if (!ourLayer || ourLayer == parentLayer) {
739         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
740             if (!is<RenderElement>(*child))
741                 continue;
742             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
743             if (nextLayer)
744                 return nextLayer;
745         }
746     }
747
748     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
749     // find anything.
750     if (parentLayer == ourLayer)
751         return nullptr;
752
753     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
754     // follow us to see if we can locate a layer.
755     if (checkParent && parent())
756         return parent()->findNextLayer(parentLayer, this, true);
757
758     return nullptr;
759 }
760
761 bool RenderElement::layerCreationAllowedForSubtree() const
762 {
763     RenderElement* parentRenderer = parent();
764     while (parentRenderer) {
765         if (parentRenderer->isSVGHiddenContainer())
766             return false;
767         parentRenderer = parentRenderer->parent();
768     }
769     
770     return true;
771 }
772
773 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
774 {
775     // FIXME: We could save this call when the change only affected non-inherited properties.
776     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
777         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
778             continue;
779
780         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
781             continue;
782
783 #if ENABLE(FULLSCREEN_API)
784         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
785             continue;
786 #endif
787
788         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
789         if (is<RenderFlowThread>(elementChild))
790             continue;
791
792         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), elementChild.style().display());
793         if (style().specifiesColumns()) {
794             if (elementChild.style().specifiesColumns())
795                 newStyle.inheritColumnPropertiesFrom(style());
796             if (elementChild.style().columnSpan())
797                 newStyle.setColumnSpan(ColumnSpanAll);
798         }
799
800         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
801         // they contain block descendants of relative or sticky positioned inlines.
802         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
803             newStyle.setPosition(elementChild.style().position());
804
805         updateAnonymousChildStyle(elementChild, newStyle);
806         
807         elementChild.setStyle(WTFMove(newStyle));
808     }
809 }
810
811 static inline bool rendererHasBackground(const RenderElement* renderer)
812 {
813     return renderer && renderer->hasBackground();
814 }
815
816 void RenderElement::invalidateCachedFirstLineStyle()
817 {
818     if (!m_hasValidCachedFirstLineStyle)
819         return;
820     m_hasValidCachedFirstLineStyle = false;
821     // Invalidate the subtree as descendant's first line style may depend on ancestor's.
822     for (auto& descendant : descendantsOfType<RenderElement>(*this))
823         descendant.m_hasValidCachedFirstLineStyle = false;
824 }
825
826 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
827 {
828     auto* oldStyle = hasInitializedStyle() ? &style() : nullptr;
829     if (oldStyle) {
830         // If our z-index changes value or our visibility changes,
831         // we need to dirty our stacking context's z-order list.
832         bool visibilityChanged = m_style.visibility() != newStyle.visibility()
833             || m_style.zIndex() != newStyle.zIndex()
834             || m_style.hasAutoZIndex() != newStyle.hasAutoZIndex();
835 #if ENABLE(DASHBOARD_SUPPORT)
836         if (visibilityChanged)
837             document().setAnnotatedRegionsDirty(true);
838 #endif
839 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
840         if (visibilityChanged)
841             document().setTouchEventRegionsNeedUpdate();
842 #endif
843         if (visibilityChanged) {
844             if (AXObjectCache* cache = document().existingAXObjectCache())
845                 cache->childrenChanged(parent(), this);
846         }
847
848         // Keep layer hierarchy visibility bits up to date if visibility changes.
849         if (m_style.visibility() != newStyle.visibility()) {
850             if (RenderLayer* layer = enclosingLayer()) {
851                 if (newStyle.visibility() == VISIBLE)
852                     layer->setHasVisibleContent();
853                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
854                     layer->dirtyVisibleContentStatus();
855                     if (diff > StyleDifferenceRepaintLayer)
856                         repaint();
857                 }
858             }
859         }
860
861         if (m_parent && (newStyle.outlineSize() < m_style.outlineSize() || shouldRepaintForStyleDifference(diff)))
862             repaint();
863         if (isFloating() && m_style.floating() != newStyle.floating()) {
864             // For changes in float styles, we need to conceivably remove ourselves
865             // from the floating objects list.
866             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
867         } else if (isOutOfFlowPositioned() && m_style.position() != newStyle.position()) {
868             // For changes in positioning styles, we need to conceivably remove ourselves
869             // from the positioned objects list.
870             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
871         }
872
873         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
874             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
875             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
876
877         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
878             && parent() && parent()->isRenderBlock();
879
880         // reset style flags
881         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
882             setFloating(false);
883             clearPositionedState();
884         }
885         if (newStyle.hasPseudoStyle(FIRST_LINE) || oldStyle->hasPseudoStyle(FIRST_LINE))
886             invalidateCachedFirstLineStyle();
887
888         setHorizontalWritingMode(true);
889         setHasVisibleBoxDecorations(false);
890         setHasOverflowClip(false);
891         setHasTransformRelatedProperty(false);
892         setHasReflection(false);
893     } else {
894         s_affectsParentBlock = false;
895         s_noLongerAffectsParentBlock = false;
896     }
897
898     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
899     bool oldStyleUsesFixedBackgrounds = m_style.hasFixedBackgroundImage();
900     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
901         bool repaintFixedBackgroundsOnScroll = !settings().fixedBackgroundsPaintRelativeToDocument();
902         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
903         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
904         bool drawsRootBackground = isDocumentElementRenderer() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
905         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
906             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
907                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
908                     newStyleSlowScroll = false;
909
910                 if (oldStyleSlowScroll && m_style.hasEntirelyFixedBackground())
911                     oldStyleSlowScroll = false;
912             }
913         }
914
915         if (oldStyleSlowScroll != newStyleSlowScroll) {
916             if (oldStyleSlowScroll)
917                 view().frameView().removeSlowRepaintObject(this);
918
919             if (newStyleSlowScroll)
920                 view().frameView().addSlowRepaintObject(this);
921         }
922     }
923
924     if (isDocumentElementRenderer() || isBody())
925         view().frameView().updateExtendBackgroundIfNecessary();
926 }
927
928 void RenderElement::handleDynamicFloatPositionChange()
929 {
930     // We have gone from not affecting the inline status of the parent flow to suddenly
931     // having an impact.  See if there is a mismatch between the parent flow's
932     // childrenInline() state and our state.
933     setInline(style().isDisplayInlineType());
934     if (isInline() != parent()->childrenInline()) {
935         if (!isInline())
936             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
937         else {
938             // An anonymous block must be made to wrap this inline.
939             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
940             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
941             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
942             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
943         }
944     }
945 }
946
947 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
948 {
949     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
950     if (!parentBlock.canDropAnonymousBlockChild())
951         return;
952
953     // We have changed to floated or out-of-flow positioning so maybe all our parent's
954     // children can be inline now. Bail if there are any block children left on the line,
955     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
956     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
957     // if we find a continuation.
958     RenderObject* current = parent()->firstChild();
959     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
960         current = current->nextSibling();
961
962     if (current)
963         return;
964
965     RenderObject* next;
966     for (current = parent()->firstChild(); current; current = next) {
967         next = current->nextSibling();
968         if (current->isAnonymousBlock())
969             parentBlock.dropAnonymousBoxChild(parentBlock, downcast<RenderBlock>(*current));
970     }
971 }
972
973 #if !PLATFORM(IOS)
974 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
975 {
976     ASSERT(a->cursors() != b->cursors());
977     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
978 }
979
980 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
981 {
982     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
983 }
984 #endif
985
986 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
987 {
988     updateFillImages(oldStyle ? &oldStyle->backgroundLayers() : nullptr, m_style.backgroundLayers());
989     updateFillImages(oldStyle ? &oldStyle->maskLayers() : nullptr, m_style.maskLayers());
990     updateImage(oldStyle ? oldStyle->borderImage().image() : nullptr, m_style.borderImage().image());
991     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : nullptr, m_style.maskBoxImage().image());
992     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : nullptr, m_style.shapeOutside());
993
994     if (s_affectsParentBlock)
995         handleDynamicFloatPositionChange();
996
997     if (s_noLongerAffectsParentBlock)
998         removeAnonymousWrappersForInlinesIfNecessary();
999
1000     SVGRenderSupport::styleChanged(*this, oldStyle);
1001
1002     if (!m_parent)
1003         return;
1004     
1005     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1006         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style);
1007
1008         // If the object already needs layout, then setNeedsLayout won't do
1009         // any work. But if the containing block has changed, then we may need
1010         // to mark the new containing blocks for layout. The change that can
1011         // directly affect the containing block of this object is a change to
1012         // the position style.
1013         if (needsLayout() && oldStyle->position() != m_style.position())
1014             markContainingBlocksForLayout();
1015
1016         if (diff == StyleDifferenceLayout)
1017             setNeedsLayoutAndPrefWidthsRecalc();
1018         else
1019             setNeedsSimplifiedNormalFlowLayout();
1020     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1021         setNeedsPositionedMovementLayout(oldStyle);
1022         setNeedsSimplifiedNormalFlowLayout();
1023     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1024         setNeedsPositionedMovementLayout(oldStyle);
1025
1026     // Don't check for repaint here; we need to wait until the layer has been
1027     // updated by subclasses before we know if we have to repaint (in setStyle()).
1028
1029 #if !PLATFORM(IOS)
1030     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1031         frame().eventHandler().scheduleCursorUpdate();
1032 #endif
1033     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
1034     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
1035     if (hasOutlineAuto != hadOutlineAuto) {
1036         updateOutlineAutoAncestor(hasOutlineAuto);
1037         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
1038     }
1039 }
1040
1041 void RenderElement::insertedIntoTree()
1042 {
1043     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1044     // and don't have a layer attached to ourselves.
1045     RenderLayer* layer = nullptr;
1046     if (firstChild() || hasLayer()) {
1047         layer = parent()->enclosingLayer();
1048         addLayers(layer);
1049     }
1050
1051     // If |this| is visible but this object was not, tell the layer it has some visible content
1052     // that needs to be drawn and layer visibility optimization can't be used
1053     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1054         if (!layer)
1055             layer = parent()->enclosingLayer();
1056         if (layer)
1057             layer->setHasVisibleContent();
1058     }
1059
1060     RenderObject::insertedIntoTree();
1061 }
1062
1063 void RenderElement::willBeRemovedFromTree()
1064 {
1065     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1066     RenderLayer* layer = nullptr;
1067     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1068         if ((layer = parent()->enclosingLayer()))
1069             layer->dirtyVisibleContentStatus();
1070     }
1071     // Keep our layer hierarchy updated.
1072     if (firstChild() || hasLayer()) {
1073         if (!layer)
1074             layer = parent()->enclosingLayer();
1075         removeLayers(layer);
1076     }
1077
1078     if (isOutOfFlowPositioned() && parent()->childrenInline())
1079         parent()->dirtyLinesFromChangedChild(*this);
1080
1081     RenderObject::willBeRemovedFromTree();
1082 }
1083
1084 inline void RenderElement::clearLayoutRootIfNeeded() const
1085 {
1086     if (renderTreeBeingDestroyed())
1087         return;
1088
1089     if (view().frameView().layoutRoot() != this)
1090         return;
1091
1092     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1093     // which ensures that this renderer is no longer the layout root.
1094     ASSERT_NOT_REACHED();
1095     
1096     // This indicates a failure to layout the child, which is why
1097     // the layout root is still set to |this|. Make sure to clear it
1098     // since we are getting destroyed.
1099     view().frameView().clearLayoutRoot();
1100 }
1101
1102 void RenderElement::willBeDestroyed()
1103 {
1104     if (m_style.hasFixedBackgroundImage() && !settings().fixedBackgroundsPaintRelativeToDocument())
1105         view().frameView().removeSlowRepaintObject(this);
1106
1107     if (element())
1108         animation().cancelAnimations(*element());
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     if (document().view()->needsFullRepaint() || !everHadLayout() || hasSelfPaintingLayer())
2191         return false;
2192     return !settings().repaintOutsideLayoutEnabled();
2193 }
2194
2195 RespectImageOrientationEnum RenderElement::shouldRespectImageOrientation() const
2196 {
2197 #if USE(CG) || USE(CAIRO)
2198     // This can only be enabled for ports which honor the orientation flag in their drawing code.
2199     if (document().isImageDocument())
2200         return RespectImageOrientation;
2201 #endif
2202     // Respect the image's orientation if it's being used as a full-page image or it's
2203     // an <img> and the setting to respect it everywhere is set.
2204     return settings().shouldRespectImageOrientation() && is<HTMLImageElement>(element()) ? RespectImageOrientation : DoNotRespectImageOrientation;
2205 }
2206
2207 void RenderElement::adjustFlowThreadStateOnContainingBlockChangeIfNeeded()
2208 {
2209     if (flowThreadState() == NotInsideFlowThread)
2210         return;
2211
2212     // Invalidate the containing block caches.
2213     if (is<RenderBlock>(*this))
2214         downcast<RenderBlock>(*this).resetFlowThreadContainingBlockAndChildInfoIncludingDescendants();
2215     
2216     // Adjust the flow tread state on the subtree.
2217     setFlowThreadState(RenderObject::computedFlowThreadState(*this));
2218     for (auto& descendant : descendantsOfType<RenderObject>(*this))
2219         descendant.setFlowThreadState(RenderObject::computedFlowThreadState(descendant));
2220 }
2221
2222 void RenderElement::removeFromRenderFlowThread()
2223 {
2224     ASSERT(flowThreadState() != NotInsideFlowThread);
2225     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2226     // It's only until later when we actually destroy it and remove all the children from it.
2227     // Currently, that happens for firstLetter elements and list markers.
2228     // Pass in the flow thread so that we don't have to look it up for all the children.
2229     removeFromRenderFlowThreadIncludingDescendants(true);
2230 }
2231
2232 void RenderElement::removeFromRenderFlowThreadIncludingDescendants(bool shouldUpdateState)
2233 {
2234     // Once we reach another flow thread we don't need to update the flow thread state
2235     // but we have to continue cleanup the flow thread info.
2236     if (isRenderFlowThread())
2237         shouldUpdateState = false;
2238
2239     for (auto& child : childrenOfType<RenderObject>(*this)) {
2240         if (is<RenderElement>(child)) {
2241             downcast<RenderElement>(child).removeFromRenderFlowThreadIncludingDescendants(shouldUpdateState);
2242             continue;
2243         }
2244         if (shouldUpdateState)
2245             child.setFlowThreadState(NotInsideFlowThread);
2246     }
2247
2248     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
2249     RenderFlowThread* flowThreadContainingBlock = this->flowThreadContainingBlock();
2250     while (flowThreadContainingBlock) {
2251         flowThreadContainingBlock->removeFlowChildInfo(*this);
2252
2253         if (flowThreadContainingBlock->flowThreadState() == NotInsideFlowThread)
2254             break;
2255         auto* parent = flowThreadContainingBlock->parent();
2256         if (!parent)
2257             break;
2258         flowThreadContainingBlock = parent->flowThreadContainingBlock();
2259     }
2260     if (is<RenderBlock>(*this))
2261         downcast<RenderBlock>(*this).setCachedFlowThreadContainingBlockNeedsUpdate();
2262
2263     if (shouldUpdateState)
2264         setFlowThreadState(NotInsideFlowThread);
2265 }
2266
2267 void RenderElement::resetFlowThreadContainingBlockAndChildInfoIncludingDescendants(RenderFlowThread* flowThread)
2268 {
2269     if (flowThread)
2270         flowThread->removeFlowChildInfo(*this);
2271
2272     for (auto& child : childrenOfType<RenderElement>(*this))
2273         child.resetFlowThreadContainingBlockAndChildInfoIncludingDescendants(flowThread);
2274 }
2275
2276 #if ENABLE(TEXT_AUTOSIZING)
2277 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject& renderer)
2278 {
2279     const RenderStyle& style = renderer.style();
2280     if (style.height().type() == Fixed) {
2281         if (is<RenderBlock>(renderer)) {
2282             // For fixed height styles, if the overflow size of the element spills out of the specified
2283             // height, assume we can apply text auto-sizing.
2284             if (style.overflowY() == OVISIBLE
2285                 && style.height().value() < downcast<RenderBlock>(renderer).layoutOverflowRect().maxY())
2286                 return RenderObject::OverflowHeight;
2287         }
2288         return RenderObject::FixedHeight;
2289     }
2290     return RenderObject::FlexibleHeight;
2291 }
2292
2293 void RenderElement::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
2294 {
2295     Document* document = view().frameView().frame().document();
2296     if (!document)
2297         return;
2298
2299     Vector<int> depthStack;
2300     int currentDepth = 0;
2301     int newFixedDepth = 0;
2302
2303     // We don't apply autosizing to nodes with fixed height normally.
2304     // But we apply it to nodes which are located deep enough
2305     // (nesting depth is greater than some const) inside of a parent block
2306     // which has fixed height but its content overflows intentionally.
2307     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2308         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2309             depthStack.remove(depthStack.size() - 1);
2310         if (newFixedDepth)
2311             depthStack.append(newFixedDepth);
2312
2313         int stackSize = depthStack.size();
2314         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2315             downcast<RenderBlockFlow>(*descendent).adjustComputedFontSizes(size, visibleWidth);
2316         newFixedDepth = 0;
2317     }
2318
2319     // Remove style from auto-sizing table that are no longer valid.
2320     document->textAutoSizing().updateRenderTree();
2321 }
2322
2323 void RenderElement::resetTextAutosizing()
2324 {
2325     Document* document = view().frameView().frame().document();
2326     if (!document)
2327         return;
2328
2329     LOG(TextAutosizing, "RenderElement::resetTextAutosizing()");
2330
2331     document->textAutoSizing().reset();
2332
2333     Vector<int> depthStack;
2334     int currentDepth = 0;
2335     int newFixedDepth = 0;
2336
2337     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2338         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2339             depthStack.remove(depthStack.size() - 1);
2340         if (newFixedDepth)
2341             depthStack.append(newFixedDepth);
2342
2343         int stackSize = depthStack.size();
2344         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2345             downcast<RenderBlockFlow>(*descendent).resetComputedFontSize();
2346         newFixedDepth = 0;
2347     }
2348 }
2349 #endif // ENABLE(TEXT_AUTOSIZING)
2350
2351 }