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