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