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