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