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