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