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