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