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