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