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