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