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