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