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