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