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