Factor style sharing code out of StyleResolver
[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         // Fresh floats need to be reparented if they actually belong to the previous anonymous block.
1002         // It copies the logic of RenderBlock::addChildIgnoringContinuation
1003         if (style().isFloating() && previousSibling() && previousSibling()->isAnonymousBlock())
1004             downcast<RenderBoxModelObject>(*parent()).moveChildTo(&downcast<RenderBoxModelObject>(*previousSibling()), this);
1005     }
1006
1007     SVGRenderSupport::styleChanged(*this, oldStyle);
1008
1009     if (!m_parent)
1010         return;
1011     
1012     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
1013         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
1014
1015         // If the object already needs layout, then setNeedsLayout won't do
1016         // any work. But if the containing block has changed, then we may need
1017         // to mark the new containing blocks for layout. The change that can
1018         // directly affect the containing block of this object is a change to
1019         // the position style.
1020         if (needsLayout() && oldStyle->position() != m_style->position())
1021             markContainingBlocksForLayout();
1022
1023         if (diff == StyleDifferenceLayout)
1024             setNeedsLayoutAndPrefWidthsRecalc();
1025         else
1026             setNeedsSimplifiedNormalFlowLayout();
1027     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1028         setNeedsPositionedMovementLayout(oldStyle);
1029         setNeedsSimplifiedNormalFlowLayout();
1030     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1031         setNeedsPositionedMovementLayout(oldStyle);
1032
1033     // Don't check for repaint here; we need to wait until the layer has been
1034     // updated by subclasses before we know if we have to repaint (in setStyle()).
1035
1036 #if !PLATFORM(IOS)
1037     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1038         frame().eventHandler().scheduleCursorUpdate();
1039 #endif
1040 }
1041
1042 void RenderElement::insertedIntoTree()
1043 {
1044     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1045         containerFlowThread->addFlowChild(*this);
1046
1047     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1048     // and don't have a layer attached to ourselves.
1049     RenderLayer* layer = nullptr;
1050     if (firstChild() || hasLayer()) {
1051         layer = parent()->enclosingLayer();
1052         addLayers(layer);
1053     }
1054
1055     // If |this| is visible but this object was not, tell the layer it has some visible content
1056     // that needs to be drawn and layer visibility optimization can't be used
1057     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1058         if (!layer)
1059             layer = parent()->enclosingLayer();
1060         if (layer)
1061             layer->setHasVisibleContent();
1062     }
1063
1064     RenderObject::insertedIntoTree();
1065 }
1066
1067 void RenderElement::willBeRemovedFromTree()
1068 {
1069     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1070     RenderLayer* layer = nullptr;
1071     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1072         if ((layer = parent()->enclosingLayer()))
1073             layer->dirtyVisibleContentStatus();
1074     }
1075     // Keep our layer hierarchy updated.
1076     if (firstChild() || hasLayer()) {
1077         if (!layer)
1078             layer = parent()->enclosingLayer();
1079         removeLayers(layer);
1080     }
1081
1082     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1083         view().frameView().removeSlowRepaintObject(this);
1084
1085     if (isOutOfFlowPositioned() && parent()->childrenInline())
1086         parent()->dirtyLinesFromChangedChild(*this);
1087
1088     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1089         containerFlowThread->removeFlowChild(*this);
1090
1091     RenderObject::willBeRemovedFromTree();
1092 }
1093
1094 inline void RenderElement::clearLayoutRootIfNeeded() const
1095 {
1096     if (documentBeingDestroyed())
1097         return;
1098
1099     if (view().frameView().layoutRoot() != this)
1100         return;
1101
1102     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1103     // which ensures that this renderer is no longer the layout root.
1104     ASSERT_NOT_REACHED();
1105     
1106     // This indicates a failure to layout the child, which is why
1107     // the layout root is still set to |this|. Make sure to clear it
1108     // since we are getting destroyed.
1109     view().frameView().clearLayoutRoot();
1110 }
1111
1112 void RenderElement::willBeDestroyed()
1113 {
1114     animation().cancelAnimations(*this);
1115
1116     destroyLeftoverChildren();
1117
1118     if (hasCounterNodeMap())
1119         RenderCounter::destroyCounterNodes(*this);
1120
1121     RenderObject::willBeDestroyed();
1122
1123 #if !ASSERT_DISABLED
1124     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1125         // After remove, the object and the associated information should not be in any flow thread.
1126         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1127             ASSERT(!flowThread->hasChild(*this));
1128             ASSERT(!flowThread->hasChildInfo(this));
1129         }
1130     }
1131 #endif
1132     clearLayoutRootIfNeeded();
1133 }
1134
1135 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1136 {
1137     ASSERT(!isSetNeedsLayoutForbidden());
1138     if (needsPositionedMovementLayout())
1139         return;
1140     setNeedsPositionedMovementLayoutBit(true);
1141     markContainingBlocksForLayout();
1142     if (hasLayer()) {
1143         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1144             setLayerNeedsFullRepaint();
1145         else
1146             setLayerNeedsFullRepaintForPositionedMovementLayout();
1147     }
1148 }
1149
1150 void RenderElement::clearChildNeedsLayout()
1151 {
1152     setNormalChildNeedsLayoutBit(false);
1153     setPosChildNeedsLayoutBit(false);
1154     setNeedsSimplifiedNormalFlowLayoutBit(false);
1155     setNormalChildNeedsLayoutBit(false);
1156     setNeedsPositionedMovementLayoutBit(false);
1157 }
1158
1159 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1160 {
1161     ASSERT(!isSetNeedsLayoutForbidden());
1162     if (needsSimplifiedNormalFlowLayout())
1163         return;
1164     setNeedsSimplifiedNormalFlowLayoutBit(true);
1165     markContainingBlocksForLayout();
1166     if (hasLayer())
1167         setLayerNeedsFullRepaint();
1168 }
1169
1170 RenderElement& RenderElement::rendererForRootBackground()
1171 {
1172     ASSERT(isDocumentElementRenderer());
1173     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1174         // Locate the <body> element using the DOM. This is easier than trying
1175         // to crawl around a render tree with potential :before/:after content and
1176         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1177         // render object very easily via the DOM.
1178         if (auto* body = document().body()) {
1179             if (auto* renderer = body->renderer())
1180                 return *renderer;
1181         }
1182     }
1183     return *this;
1184 }
1185
1186 RenderElement* RenderElement::hoverAncestor() const
1187 {
1188     // When searching for the hover ancestor and encountering a named flow thread,
1189     // the search will continue with the DOM ancestor of the top-most element
1190     // in the named flow thread.
1191     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1192     RenderElement* hoverAncestor = parent();
1193
1194     // Skip anonymous blocks directly flowed into flow threads as it would
1195     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1196     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1197         hoverAncestor = hoverAncestor->parent();
1198
1199     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1200         hoverAncestor = nullptr;
1201         if (Element* element = this->element()) {
1202             if (auto parent = element->parentNode())
1203                 hoverAncestor = parent->renderer();
1204         }
1205     }
1206
1207     return hoverAncestor;
1208 }
1209
1210 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1211 {
1212     paintInfo.phase = phase;
1213     element.paint(paintInfo, childPoint);
1214 }
1215
1216 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1217 {
1218     // Paint all phases atomically, as though the element established its own stacking context.
1219     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1220     // This is also used by other elements (e.g. flex items and grid items).
1221     if (paintInfo.phase == PaintPhaseSelection) {
1222         paint(paintInfo, childPoint);
1223     } else if (paintInfo.phase == PaintPhaseForeground) {
1224         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1225         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1226         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1227         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1228         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1229
1230         // Reset |paintInfo| to the original phase.
1231         paintInfo.phase = PaintPhaseForeground;
1232     }
1233 }
1234
1235 void RenderElement::layout()
1236 {
1237     StackStats::LayoutCheckPoint layoutCheckPoint;
1238     ASSERT(needsLayout());
1239     RenderObject* child = firstChild();
1240     while (child) {
1241         if (child->needsLayout())
1242             downcast<RenderElement>(*child).layout();
1243         ASSERT(!child->needsLayout());
1244         child = child->nextSibling();
1245     }
1246     clearNeedsLayout();
1247 }
1248
1249 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1250 {
1251     // Nobody will use multiple layers without wanting fancy positioning.
1252     if (layer->next())
1253         return true;
1254
1255     // Make sure we have a valid image.
1256     StyleImage* image = layer->image();
1257     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1258         return false;
1259
1260     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1261         return true;
1262
1263     EFillSizeType sizeType = layer->sizeType();
1264
1265     if (sizeType == Contain || sizeType == Cover)
1266         return true;
1267
1268     if (sizeType == SizeLength) {
1269         LengthSize size = layer->sizeLength();
1270         if (size.width().isPercentOrCalculated() || size.height().isPercentOrCalculated())
1271             return true;
1272         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1273         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1274             return true;
1275     } else if (image->usesImageContainerSize())
1276         return true;
1277
1278     return false;
1279 }
1280
1281 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1282 {
1283     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1284         return true;
1285
1286     // If we don't have a background/border/mask, then nothing to do.
1287     if (!renderer.hasBoxDecorations())
1288         return false;
1289
1290     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1291         return true;
1292
1293     // Our fill layers are ok. Let's check border.
1294     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1295         return true;
1296
1297     return false;
1298 }
1299
1300 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1301 {
1302     if (view().printing())
1303         return false; // Don't repaint if we're printing.
1304
1305     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1306     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1307     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1308     LayoutRect newOutlineBox;
1309
1310     bool fullRepaint = selfNeedsLayout();
1311     // Presumably a background or a border exists if border-fit:lines was specified.
1312     if (!fullRepaint && style().borderFit() == BorderFitLines)
1313         fullRepaint = true;
1314     if (!fullRepaint) {
1315         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1316         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1317         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1318         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1319             fullRepaint = true;
1320     }
1321
1322     if (!repaintContainer)
1323         repaintContainer = &view();
1324
1325     if (fullRepaint) {
1326         repaintUsingContainer(repaintContainer, oldBounds);
1327         if (newBounds != oldBounds)
1328             repaintUsingContainer(repaintContainer, newBounds);
1329         return true;
1330     }
1331
1332     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1333         return false;
1334
1335     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1336     if (deltaLeft > 0)
1337         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1338     else if (deltaLeft < 0)
1339         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1340
1341     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1342     if (deltaRight > 0)
1343         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1344     else if (deltaRight < 0)
1345         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1346
1347     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1348     if (deltaTop > 0)
1349         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1350     else if (deltaTop < 0)
1351         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1352
1353     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1354     if (deltaBottom > 0)
1355         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1356     else if (deltaBottom < 0)
1357         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1358
1359     if (newOutlineBox == oldOutlineBox)
1360         return false;
1361
1362     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1363     // two rectangles (but typically only one).
1364     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1365     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1366     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1367     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1368     if (width) {
1369         LayoutUnit shadowLeft;
1370         LayoutUnit shadowRight;
1371         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1372         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1373         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1374         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1375         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1376         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1377         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1378             newOutlineBox.y(),
1379             width + decorationsWidth,
1380             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1381         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1382         if (rightRect.x() < right) {
1383             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1384             repaintUsingContainer(repaintContainer, rightRect);
1385         }
1386     }
1387     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1388     if (height) {
1389         LayoutUnit shadowTop;
1390         LayoutUnit shadowBottom;
1391         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1392         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1393         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1394         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1395         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1396             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1397         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1398         LayoutRect bottomRect(newOutlineBox.x(),
1399             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1400             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1401             height + decorationsHeight);
1402         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1403         if (bottomRect.y() < bottom) {
1404             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1405             repaintUsingContainer(repaintContainer, bottomRect);
1406         }
1407     }
1408     return false;
1409 }
1410
1411 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1412 {
1413     ASSERT(style().hasBorder());
1414
1415     StyleImage* borderImage = style().borderImage().image();
1416     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1417 }
1418
1419 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1420 {
1421     auto& frameView = view().frameView();
1422     if (frameView.isOffscreen())
1423         return false;
1424
1425     if (!hasOverflowClip()) {
1426         // FIXME: Computing the overflow rect is expensive if any descendant has
1427         // its own self-painting layer. As a result, we prefer to abort early in
1428         // this case and assume it may cause us to repaint inside the viewport.
1429         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1430             return true;
1431     }
1432
1433     // Compute viewport rect if it was not provided.
1434     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1435     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1436 }
1437
1438 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1439 {
1440     const Document& document = renderer.document();
1441     if (document.inPageCache())
1442         return false;
1443     if (document.activeDOMObjectsAreSuspended())
1444         return false;
1445     if (renderer.style().visibility() != VISIBLE)
1446         return false;
1447     if (renderer.view().frameView().isOffscreen())
1448         return false;
1449
1450     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1451     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1452     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1453     // can no longer check if it is a background image.
1454     bool backgroundIsPaintedByRoot = renderer.isDocumentElementRenderer();
1455     if (renderer.isBody()) {
1456         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1457         ASSERT(rootRenderer.isDocumentElementRenderer());
1458         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1459         // FIXME: Should share body background propagation code.
1460         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1461
1462     }
1463     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect() : renderer.absoluteClippedOverflowRect();
1464     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1465         return false;
1466
1467     return true;
1468 }
1469
1470 void RenderElement::registerForVisibleInViewportCallback()
1471 {
1472     if (isRegisteredForVisibleInViewportCallback())
1473         return;
1474     setIsRegisteredForVisibleInViewportCallback(true);
1475
1476     view().registerForVisibleInViewportCallback(*this);
1477 }
1478
1479 void RenderElement::unregisterForVisibleInViewportCallback()
1480 {
1481     if (!isRegisteredForVisibleInViewportCallback())
1482         return;
1483     setIsRegisteredForVisibleInViewportCallback(false);
1484
1485     view().unregisterForVisibleInViewportCallback(*this);
1486     m_visibleInViewportState = VisibilityUnknown;
1487 }
1488
1489 void RenderElement::visibleInViewportStateChanged(VisibleInViewportState state)
1490 {
1491     if (state == visibleInViewportState())
1492         return;
1493     setVisibleInViewportState(state);
1494
1495     if (element())
1496         element()->isVisibleInViewportChanged();
1497 }
1498
1499 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1500 {
1501     if (document().inPageCache())
1502         return;
1503     auto& frameView = view().frameView();
1504     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1505     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1506         // FIXME: It would be better to pass the image along with the renderer
1507         // so that we can be smarter about detecting if the image is inside the
1508         // viewport in repaintForPausedImageAnimationsIfNeeded().
1509         view().addRendererWithPausedImageAnimations(*this);
1510         return;
1511     }
1512     imageChanged(&image);
1513 }
1514
1515 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1516 {
1517     ASSERT(m_hasPausedImageAnimations);
1518     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1519         return false;
1520
1521     repaint();
1522
1523     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1524     if (is<RenderBoxModelObject>(*this))
1525         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1526
1527     return true;
1528 }
1529
1530 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1531 {
1532     auto* renderer = this;
1533     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1534         renderer = renderer->parent();
1535     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1536 }
1537
1538 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1539 {
1540     return controlStatesRendererMap().contains(o);
1541 }
1542
1543 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1544 {
1545     return controlStatesRendererMap().get(o);
1546 }
1547
1548 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1549 {
1550     ControlStates* states = controlStatesRendererMap().get(o);
1551     if (states) {
1552         controlStatesRendererMap().remove(o);
1553         delete states;
1554     }
1555 }
1556
1557 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1558 {
1559     controlStatesRendererMap().add(o, states);
1560 }
1561
1562 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1563 {
1564     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1565         return nullptr;
1566
1567     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1568     if (cachedStyle)
1569         return cachedStyle;
1570
1571     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1572     if (result)
1573         return style().addCachedPseudoStyle(result.release());
1574     return nullptr;
1575 }
1576
1577 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1578 {
1579     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1580         return nullptr;
1581
1582     if (!parentStyle) {
1583         ASSERT(!ownStyle);
1584         parentStyle = &style();
1585     }
1586
1587     if (isAnonymous())
1588         return nullptr;
1589
1590     auto& styleResolver = element()->styleResolver();
1591
1592     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1593         RefPtr<RenderStyle> result = styleResolver.styleForElement(*element(), parentStyle);
1594         result->setStyleType(FIRST_LINE_INHERITED);
1595         return result.release();
1596     }
1597
1598     return styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1599 }
1600
1601 RenderBlock* RenderElement::containingBlockForFixedPosition() const
1602 {
1603     const RenderElement* object = this;
1604     while (object && !object->canContainFixedPositionObjects())
1605         object = object->parent();
1606
1607     ASSERT(!object || !object->isAnonymousBlock());
1608     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1609 }
1610
1611 RenderBlock* RenderElement::containingBlockForAbsolutePosition() const
1612 {
1613     const RenderElement* object = this;
1614     while (object && !object->canContainAbsolutelyPositionedObjects())
1615         object = object->parent();
1616
1617     // For a relatively positioned inline, return its nearest non-anonymous containing block,
1618     // not the inline itself, to avoid having a positioned objects list in all RenderInlines
1619     // and use RenderBlock* as RenderElement::containingBlock's return type.
1620     // Use RenderBlock::container() to obtain the inline.
1621     if (object && !is<RenderBlock>(*object))
1622         object = object->containingBlock();
1623
1624     while (object && object->isAnonymousBlock())
1625         object = object->containingBlock();
1626
1627     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1628 }
1629
1630 static inline bool isNonRenderBlockInline(const RenderElement& object)
1631 {
1632     return (object.isInline() && !object.isReplaced()) || !object.isRenderBlock();
1633 }
1634
1635 RenderBlock* RenderElement::containingBlockForObjectInFlow() const
1636 {
1637     const RenderElement* object = this;
1638     while (object && isNonRenderBlockInline(*object))
1639         object = object->parent();
1640     return const_cast<RenderBlock*>(downcast<RenderBlock>(object));
1641 }
1642
1643 Color RenderElement::selectionColor(int colorProperty) const
1644 {
1645     // If the element is unselectable, or we are only painting the selection,
1646     // don't override the foreground color with the selection foreground color.
1647     if (style().userSelect() == SELECT_NONE
1648         || (view().frameView().paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorSelectionAndBackgroundsOnly)))
1649         return Color();
1650
1651     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1652         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1653         if (!color.isValid())
1654             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1655         return color;
1656     }
1657
1658     if (frame().selection().isFocusedAndActive())
1659         return theme().activeSelectionForegroundColor();
1660     return theme().inactiveSelectionForegroundColor();
1661 }
1662
1663 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1664 {
1665     if (isAnonymous())
1666         return nullptr;
1667
1668     if (ShadowRoot* root = element()->containingShadowRoot()) {
1669         if (root->type() == ShadowRoot::Type::UserAgent) {
1670             if (Element* shadowHost = element()->shadowHost())
1671                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1672         }
1673     }
1674
1675     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1676 }
1677
1678 Color RenderElement::selectionForegroundColor() const
1679 {
1680     return selectionColor(CSSPropertyWebkitTextFillColor);
1681 }
1682
1683 Color RenderElement::selectionEmphasisMarkColor() const
1684 {
1685     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1686 }
1687
1688 Color RenderElement::selectionBackgroundColor() const
1689 {
1690     if (style().userSelect() == SELECT_NONE)
1691         return Color();
1692
1693     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1694         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1695
1696     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1697     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1698         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1699
1700     if (frame().selection().isFocusedAndActive())
1701         return theme().activeSelectionBackgroundColor();
1702     return theme().inactiveSelectionBackgroundColor();
1703 }
1704
1705 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1706 {
1707     if (!isInline() || isReplaced()) {
1708         point = localToAbsolute(FloatPoint(), UseTransforms);
1709         return true;
1710     }
1711
1712     // find the next text/image child, to get a position
1713     const RenderObject* o = this;
1714     while (o) {
1715         const RenderObject* p = o;
1716         if (RenderObject* child = o->firstChildSlow())
1717             o = child;
1718         else if (o->nextSibling())
1719             o = o->nextSibling();
1720         else {
1721             RenderObject* next = 0;
1722             while (!next && o->parent()) {
1723                 o = o->parent();
1724                 next = o->nextSibling();
1725             }
1726             o = next;
1727
1728             if (!o)
1729                 break;
1730         }
1731         ASSERT(o);
1732
1733         if (!o->isInline() || o->isReplaced()) {
1734             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1735             return true;
1736         }
1737
1738         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1739             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1740         } else if (is<RenderText>(*o) || o->isReplaced()) {
1741             point = FloatPoint();
1742             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1743                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1744             else if (is<RenderBox>(*o))
1745                 point.moveBy(downcast<RenderBox>(*o).location());
1746             point = o->container()->localToAbsolute(point, UseTransforms);
1747             return true;
1748         }
1749     }
1750     
1751     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1752     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1753     if (!o && document().view()) {
1754         point = FloatPoint(0, document().view()->contentsHeight());
1755         return true;
1756     }
1757     return false;
1758 }
1759
1760 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1761 {
1762     if (!isInline() || isReplaced()) {
1763         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1764         return true;
1765     }
1766
1767     // find the last text/image child, to get a position
1768     const RenderObject* o = this;
1769     while (o) {
1770         if (RenderObject* child = o->lastChildSlow())
1771             o = child;
1772         else if (o->previousSibling())
1773             o = o->previousSibling();
1774         else {
1775             RenderObject* prev = 0;
1776             while (!prev) {
1777                 o = o->parent();
1778                 if (!o)
1779                     return false;
1780                 prev = o->previousSibling();
1781             }
1782             o = prev;
1783         }
1784         ASSERT(o);
1785         if (is<RenderText>(*o) || o->isReplaced()) {
1786             point = FloatPoint();
1787             if (is<RenderText>(*o)) {
1788                 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1789                 if (!linesBox.maxX() && !linesBox.maxY())
1790                     continue;
1791                 point.moveBy(linesBox.maxXMaxYCorner());
1792             } else
1793                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1794             point = o->container()->localToAbsolute(point, UseTransforms);
1795             return true;
1796         }
1797     }
1798     return true;
1799 }
1800
1801 LayoutRect RenderElement::anchorRect() const
1802 {
1803     FloatPoint leading, trailing;
1804     getLeadingCorner(leading);
1805     getTrailingCorner(trailing);
1806
1807     FloatPoint upperLeft = leading;
1808     FloatPoint lowerRight = trailing;
1809
1810     // Vertical writing modes might mean the leading point is not in the top left
1811     if (!isInline() || isReplaced()) {
1812         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1813         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1814     } // Otherwise, it's not obvious what to do.
1815
1816     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1817 }
1818
1819 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1820 {
1821     const RenderElement* current = this;
1822     do {
1823         if (current->isRenderBlock())
1824             return current;
1825         if (!current->isRenderInline() || current->isRubyText())
1826             return nullptr;
1827         
1828         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1829         if (styleToUse.textDecoration() & textDecoration)
1830             return current;
1831         current = current->parent();
1832     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1833
1834     return current;
1835 }
1836
1837 void RenderElement::drawLineForBoxSide(GraphicsContext& graphicsContext, const FloatRect& rect, BoxSide side, Color color, EBorderStyle borderStyle, float adjacentWidth1, float adjacentWidth2, bool antialias) const
1838 {
1839     auto drawBorderRect = [&graphicsContext] (const FloatRect& rect)
1840     {
1841         if (rect.isEmpty())
1842             return;
1843         graphicsContext.drawRect(rect);
1844     };
1845
1846     float x1 = rect.x();
1847     float x2 = rect.maxX();
1848     float y1 = rect.y();
1849     float y2 = rect.maxY();
1850     float thickness;
1851     float length;
1852     if (side == BSTop || side == BSBottom) {
1853         thickness = y2 - y1;
1854         length = x2 - x1;
1855     } else {
1856         thickness = x2 - x1;
1857         length = y2 - y1;
1858     }
1859     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
1860     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
1861     if (!thickness || !length)
1862         return;
1863
1864     float deviceScaleFactor = document().deviceScaleFactor();
1865     if (borderStyle == DOUBLE && (thickness * deviceScaleFactor) < 3)
1866         borderStyle = SOLID;
1867
1868     switch (borderStyle) {
1869     case BNONE:
1870     case BHIDDEN:
1871         return;
1872     case DOTTED:
1873     case DASHED: {
1874         bool wasAntialiased = graphicsContext.shouldAntialias();
1875         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1876         graphicsContext.setShouldAntialias(antialias);
1877         graphicsContext.setStrokeColor(color);
1878         graphicsContext.setStrokeThickness(thickness);
1879         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1880         graphicsContext.drawLine(roundPointToDevicePixels(LayoutPoint(x1, y1), deviceScaleFactor), roundPointToDevicePixels(LayoutPoint(x2, y2), deviceScaleFactor));
1881         graphicsContext.setShouldAntialias(wasAntialiased);
1882         graphicsContext.setStrokeStyle(oldStrokeStyle);
1883         break;
1884     }
1885     case DOUBLE: {
1886         float thirdOfThickness = ceilToDevicePixel(thickness / 3, deviceScaleFactor);
1887         ASSERT(thirdOfThickness);
1888
1889         if (!adjacentWidth1 && !adjacentWidth2) {
1890             StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1891             graphicsContext.setStrokeStyle(NoStroke);
1892             graphicsContext.setFillColor(color);
1893
1894             bool wasAntialiased = graphicsContext.shouldAntialias();
1895             graphicsContext.setShouldAntialias(antialias);
1896
1897             switch (side) {
1898             case BSTop:
1899             case BSBottom:
1900                 drawBorderRect(snapRectToDevicePixels(x1, y1, length, thirdOfThickness, deviceScaleFactor));
1901                 drawBorderRect(snapRectToDevicePixels(x1, y2 - thirdOfThickness, length, thirdOfThickness, deviceScaleFactor));
1902                 break;
1903             case BSLeft:
1904             case BSRight:
1905                 drawBorderRect(snapRectToDevicePixels(x1, y1, thirdOfThickness, length, deviceScaleFactor));
1906                 drawBorderRect(snapRectToDevicePixels(x2 - thirdOfThickness, y1, thirdOfThickness, length, deviceScaleFactor));
1907                 break;
1908             }
1909
1910             graphicsContext.setShouldAntialias(wasAntialiased);
1911             graphicsContext.setStrokeStyle(oldStrokeStyle);
1912         } else {
1913             float adjacent1BigThird = ceilToDevicePixel(adjacentWidth1 / 3, deviceScaleFactor);
1914             float adjacent2BigThird = ceilToDevicePixel(adjacentWidth2 / 3, deviceScaleFactor);
1915
1916             float offset1 = floorToDevicePixel(fabs(adjacentWidth1) * 2 / 3, deviceScaleFactor);
1917             float offset2 = floorToDevicePixel(fabs(adjacentWidth2) * 2 / 3, deviceScaleFactor);
1918
1919             float mitreOffset1 = adjacentWidth1 < 0 ? offset1 : 0;
1920             float mitreOffset2 = adjacentWidth1 > 0 ? offset1 : 0;
1921             float mitreOffset3 = adjacentWidth2 < 0 ? offset2 : 0;
1922             float mitreOffset4 = adjacentWidth2 > 0 ? offset2 : 0;
1923
1924             FloatRect paintBorderRect;
1925             switch (side) {
1926             case BSTop:
1927                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y1, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1928                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1929                     adjacent1BigThird, adjacent2BigThird, antialias);
1930
1931                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y2 - thirdOfThickness, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1932                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1933                     adjacent1BigThird, adjacent2BigThird, antialias);
1934                 break;
1935             case BSLeft:
1936                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1937                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1938                     adjacent1BigThird, adjacent2BigThird, antialias);
1939
1940                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1941                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1942                     adjacent1BigThird, adjacent2BigThird, antialias);
1943                 break;
1944             case BSBottom:
1945                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y1, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1946                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1947                     adjacent1BigThird, adjacent2BigThird, antialias);
1948
1949                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y2 - thirdOfThickness, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1950                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1951                     adjacent1BigThird, adjacent2BigThird, antialias);
1952                 break;
1953             case BSRight:
1954                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1955                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1956                     adjacent1BigThird, adjacent2BigThird, antialias);
1957
1958                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1959                 drawLineForBoxSide(graphicsContext, paintBorderRect, side, color, SOLID,
1960                     adjacent1BigThird, adjacent2BigThird, antialias);
1961                 break;
1962             default:
1963                 break;
1964             }
1965         }
1966         break;
1967     }
1968     case RIDGE:
1969     case GROOVE: {
1970         EBorderStyle s1;
1971         EBorderStyle s2;
1972         if (borderStyle == GROOVE) {
1973             s1 = INSET;
1974             s2 = OUTSET;
1975         } else {
1976             s1 = OUTSET;
1977             s2 = INSET;
1978         }
1979
1980         float adjacent1BigHalf = ceilToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1981         float adjacent2BigHalf = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1982
1983         float adjacent1SmallHalf = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1984         float adjacent2SmallHalf = floorToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1985
1986         float offset1 = 0;
1987         float offset2 = 0;
1988         float offset3 = 0;
1989         float offset4 = 0;
1990
1991         if (((side == BSTop || side == BSLeft) && adjacentWidth1 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 > 0))
1992             offset1 = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1993
1994         if (((side == BSTop || side == BSLeft) && adjacentWidth2 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 > 0))
1995             offset2 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1996
1997         if (((side == BSTop || side == BSLeft) && adjacentWidth1 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 < 0))
1998             offset3 = floorToDevicePixel(fabs(adjacentWidth1) / 2, deviceScaleFactor);
1999
2000         if (((side == BSTop || side == BSLeft) && adjacentWidth2 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 < 0))
2001             offset4 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
2002
2003         float adjustedX = ceilToDevicePixel((x1 + x2) / 2, deviceScaleFactor);
2004         float adjustedY = ceilToDevicePixel((y1 + y2) / 2, deviceScaleFactor);
2005         // Quads can't use the default snapping rect functions.
2006         x1 = roundToDevicePixel(x1, deviceScaleFactor);
2007         x2 = roundToDevicePixel(x2, deviceScaleFactor);
2008         y1 = roundToDevicePixel(y1, deviceScaleFactor);
2009         y2 = roundToDevicePixel(y2, deviceScaleFactor);
2010
2011         switch (side) {
2012         case BSTop:
2013             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
2014             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, color, s2, adjacent1SmallHalf, adjacent2SmallHalf, antialias);
2015             break;
2016         case BSLeft:
2017             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
2018             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, color, s2, adjacent1SmallHalf, adjacent2SmallHalf, antialias);
2019             break;
2020         case BSBottom:
2021             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
2022             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, color, s1, adjacent1SmallHalf, adjacent2SmallHalf, antialias);
2023             break;
2024         case BSRight:
2025             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
2026             drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, color, s1, adjacent1SmallHalf, adjacent2SmallHalf, antialias);
2027             break;
2028         }
2029         break;
2030     }
2031     case INSET:
2032     case OUTSET:
2033         calculateBorderStyleColor(borderStyle, side, color);
2034         FALLTHROUGH;
2035     case SOLID: {
2036         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
2037         ASSERT(x2 >= x1);
2038         ASSERT(y2 >= y1);
2039         if (!adjacentWidth1 && !adjacentWidth2) {
2040             graphicsContext.setStrokeStyle(NoStroke);
2041             graphicsContext.setFillColor(color);
2042             bool wasAntialiased = graphicsContext.shouldAntialias();
2043             graphicsContext.setShouldAntialias(antialias);
2044             drawBorderRect(snapRectToDevicePixels(x1, y1, x2 - x1, y2 - y1, deviceScaleFactor));
2045             graphicsContext.setShouldAntialias(wasAntialiased);
2046             graphicsContext.setStrokeStyle(oldStrokeStyle);
2047             return;
2048         }
2049
2050         // FIXME: These roundings should be replaced by ASSERT(device pixel positioned) when all the callers have transitioned to device pixels.
2051         x1 = roundToDevicePixel(x1, deviceScaleFactor);
2052         y1 = roundToDevicePixel(y1, deviceScaleFactor);
2053         x2 = roundToDevicePixel(x2, deviceScaleFactor);
2054         y2 = roundToDevicePixel(y2, deviceScaleFactor);
2055
2056         Vector<FloatPoint> quad;
2057         quad.reserveInitialCapacity(4);
2058         switch (side) {
2059         case BSTop:
2060             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y1 });
2061             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y2 });
2062             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y2 });
2063             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y1 });
2064             break;
2065         case BSBottom:
2066             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y1 });
2067             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y2 });
2068             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y2 });
2069             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y1 });
2070             break;
2071         case BSLeft:
2072             quad.uncheckedAppend({ x1, y1 + std::max<float>(-adjacentWidth1, 0) });
2073             quad.uncheckedAppend({ x1, y2 - std::max<float>(-adjacentWidth2, 0) });
2074             quad.uncheckedAppend({ x2, y2 - std::max<float>( adjacentWidth2, 0) });
2075             quad.uncheckedAppend({ x2, y1 + std::max<float>( adjacentWidth1, 0) });
2076             break;
2077         case BSRight:
2078             quad.uncheckedAppend({ x1, y1 + std::max<float>( adjacentWidth1, 0) });
2079             quad.uncheckedAppend({ x1, y2 - std::max<float>( adjacentWidth2, 0) });
2080             quad.uncheckedAppend({ x2, y2 - std::max<float>(-adjacentWidth2, 0) });
2081             quad.uncheckedAppend({ x2, y1 + std::max<float>(-adjacentWidth1, 0) });
2082             break;
2083         }
2084
2085         graphicsContext.setStrokeStyle(NoStroke);
2086         graphicsContext.setFillColor(color);
2087         bool wasAntialiased = graphicsContext.shouldAntialias();
2088         graphicsContext.setShouldAntialias(antialias);
2089         graphicsContext.fillPath(Path::polygonPathFromPoints(quad));
2090         graphicsContext.setShouldAntialias(wasAntialiased);
2091
2092         graphicsContext.setStrokeStyle(oldStrokeStyle);
2093         break;
2094     }
2095     }
2096 }
2097
2098 void RenderElement::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const RenderStyle& style)
2099 {
2100     ASSERT(style.outlineStyleIsAuto());
2101
2102     Vector<IntRect> focusRingRects;
2103     addFocusRingRects(focusRingRects, paintOffset, paintInfo.paintContainer);
2104 #if PLATFORM(MAC)
2105     bool needsRepaint;
2106     paintInfo.context().drawFocusRing(focusRingRects, theme().platformFocusRingWidth(), style.outlineOffset(), document().page()->focusController().timeSinceFocusWasSet(), needsRepaint);
2107     if (needsRepaint)
2108         document().page()->focusController().setFocusedElementNeedsRepaint();
2109 #else
2110     paintInfo.context().drawFocusRing(focusRingRects, style.outlineWidth(), style.outlineOffset(), style.visitedDependentColor(CSSPropertyOutlineColor));
2111 #endif
2112 }
2113
2114 void RenderElement::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
2115 {
2116     GraphicsContext& graphicsContext = paintInfo.context();
2117     if (graphicsContext.paintingDisabled())
2118         return;
2119
2120     if (!hasOutline())
2121         return;
2122
2123     RenderStyle& styleToUse = style();
2124     float outlineWidth = floorToDevicePixel(styleToUse.outlineWidth(), document().deviceScaleFactor());
2125     float outlineOffset = floorToDevicePixel(styleToUse.outlineOffset(), document().deviceScaleFactor());
2126
2127     // Only paint the focus ring by hand if the theme isn't able to draw it.
2128     if (styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2129         paintFocusRing(paintInfo, paintRect.location(), styleToUse);
2130
2131     if (hasOutlineAnnotation() && !styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2132         addPDFURLRect(paintInfo, paintRect.location());
2133
2134     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
2135         return;
2136
2137     FloatRect outer = paintRect;
2138     outer.inflate(outlineOffset + outlineWidth);
2139     FloatRect inner = outer;
2140     inner.inflate(-outlineWidth);
2141
2142     // FIXME: This prevents outlines from painting inside the object. See bug 12042
2143     if (outer.isEmpty())
2144         return;
2145
2146     EBorderStyle outlineStyle = styleToUse.outlineStyle();
2147     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
2148
2149     bool useTransparencyLayer = outlineColor.hasAlpha();
2150     if (useTransparencyLayer) {
2151         if (outlineStyle == SOLID) {
2152             Path path;
2153             path.addRect(outer);
2154             path.addRect(inner);
2155             graphicsContext.setFillRule(RULE_EVENODD);
2156             graphicsContext.setFillColor(outlineColor);
2157             graphicsContext.fillPath(path);
2158             return;
2159         }
2160         graphicsContext.beginTransparencyLayer(static_cast<float>(outlineColor.alpha()) / 255);
2161         outlineColor = Color(outlineColor.red(), outlineColor.green(), outlineColor.blue());
2162     }
2163
2164     float leftOuter = outer.x();
2165     float leftInner = inner.x();
2166     float rightOuter = outer.maxX();
2167     float rightInner = std::min(inner.maxX(), rightOuter);
2168     float topOuter = outer.y();
2169     float topInner = inner.y();
2170     float bottomOuter = outer.maxY();
2171     float bottomInner = std::min(inner.maxY(), bottomOuter);
2172
2173     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(leftInner, bottomOuter)), BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2174     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(rightOuter, topInner)), BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2175     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(rightInner, topOuter), FloatPoint(rightOuter, bottomOuter)), BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2176     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, bottomInner), FloatPoint(rightOuter, bottomOuter)), BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2177
2178     if (useTransparencyLayer)
2179         graphicsContext.endTransparencyLayer();
2180 }
2181
2182 }