Clarify RenderElement::adjustStyleDifference()
[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 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 "Frame.h"
35 #include "FrameSelection.h"
36 #include "HTMLBodyElement.h"
37 #include "HTMLHtmlElement.h"
38 #include "HTMLNames.h"
39 #include "FlowThreadController.h"
40 #include "RenderCounter.h"
41 #include "RenderDeprecatedFlexibleBox.h"
42 #include "RenderFlexibleBox.h"
43 #include "RenderImage.h"
44 #include "RenderImageResourceStyleImage.h"
45 #include "RenderIterator.h"
46 #include "RenderLayer.h"
47 #include "RenderLayerCompositor.h"
48 #include "RenderLineBreak.h"
49 #include "RenderListItem.h"
50 #include "RenderNamedFlowThread.h"
51 #include "RenderRegion.h"
52 #include "RenderRuby.h"
53 #include "RenderRubyText.h"
54 #include "RenderTableCaption.h"
55 #include "RenderTableCell.h"
56 #include "RenderTableCol.h"
57 #include "RenderTableRow.h"
58 #include "RenderText.h"
59 #include "RenderTheme.h"
60 #include "RenderView.h"
61 #include "SVGRenderSupport.h"
62 #include "Settings.h"
63 #include "ShadowRoot.h"
64 #include "StyleResolver.h"
65 #include <wtf/MathExtras.h>
66 #include <wtf/StackStats.h>
67
68 #if ENABLE(CSS_GRID_LAYOUT)
69 #include "RenderGrid.h"
70 #endif
71
72 namespace WebCore {
73
74 bool RenderElement::s_affectsParentBlock = false;
75 bool RenderElement::s_noLongerAffectsParentBlock = false;
76     
77 static HashMap<const RenderObject*, ControlStates*>& controlStatesRendererMap()
78 {
79     static NeverDestroyed<HashMap<const RenderObject*, ControlStates*>> map;
80     return map;
81 }
82
83 inline RenderElement::RenderElement(ContainerNode& elementOrDocument, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
84     : RenderObject(elementOrDocument)
85     , m_baseTypeFlags(baseTypeFlags)
86     , m_ancestorLineBoxDirty(false)
87     , m_hasInitializedStyle(false)
88     , m_renderInlineAlwaysCreatesLineBoxes(false)
89     , m_renderBoxNeedsLazyRepaint(false)
90     , m_hasPausedImageAnimations(false)
91     , m_hasCounterNodeMap(false)
92     , m_isCSSAnimating(false)
93     , m_hasContinuation(false)
94     , m_renderBlockHasMarginBeforeQuirk(false)
95     , m_renderBlockHasMarginAfterQuirk(false)
96     , m_renderBlockHasBorderOrPaddingLogicalWidthChanged(false)
97     , m_renderBlockFlowHasMarkupTruncation(false)
98     , m_renderBlockFlowLineLayoutPath(RenderBlockFlow::UndeterminedPath)
99     , m_firstChild(nullptr)
100     , m_lastChild(nullptr)
101     , m_style(WTF::move(style))
102 {
103 }
104
105 RenderElement::RenderElement(Element& element, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
106     : RenderElement(static_cast<ContainerNode&>(element), WTF::move(style), baseTypeFlags)
107 {
108 }
109
110 RenderElement::RenderElement(Document& document, Ref<RenderStyle>&& style, unsigned baseTypeFlags)
111     : RenderElement(static_cast<ContainerNode&>(document), WTF::move(style), baseTypeFlags)
112 {
113 }
114
115 RenderElement::~RenderElement()
116 {
117     if (hasInitializedStyle()) {
118         for (const FillLayer* bgLayer = m_style->backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
119             if (StyleImage* backgroundImage = bgLayer->image())
120                 backgroundImage->removeClient(this);
121         }
122
123         for (const FillLayer* maskLayer = m_style->maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
124             if (StyleImage* maskImage = maskLayer->image())
125                 maskImage->removeClient(this);
126             else if (maskLayer->maskImage().get())
127                 maskLayer->maskImage()->removeRendererImageClient(this);
128         }
129
130         if (StyleImage* borderImage = m_style->borderImage().image())
131             borderImage->removeClient(this);
132
133         if (StyleImage* maskBoxImage = m_style->maskBoxImage().image())
134             maskBoxImage->removeClient(this);
135
136 #if ENABLE(CSS_SHAPES)
137         if (auto shapeValue = m_style->shapeOutside()) {
138             if (auto shapeImage = shapeValue->image())
139                 shapeImage->removeClient(this);
140         }
141 #endif
142     }
143     if (m_hasPausedImageAnimations)
144         view().removeRendererWithPausedImageAnimations(*this);
145 }
146
147 RenderPtr<RenderElement> RenderElement::createFor(Element& element, Ref<RenderStyle>&& style)
148 {
149     // Minimal support for content properties replacing an entire element.
150     // Works only if we have exactly one piece of content and it's a URL.
151     // Otherwise acts as if we didn't support this feature.
152     const ContentData* contentData = style.get().contentData();
153     if (contentData && !contentData->next() && is<ImageContentData>(*contentData) && !element.isPseudoElement()) {
154         auto& styleImage = downcast<ImageContentData>(*contentData).image();
155         auto image = createRenderer<RenderImage>(element, WTF::move(style), const_cast<StyleImage*>(&styleImage));
156         image->setIsGeneratedContent();
157         return WTF::move(image);
158     }
159
160     if (element.hasTagName(HTMLNames::rubyTag)) {
161         if (style.get().display() == INLINE)
162             return createRenderer<RenderRubyAsInline>(element, WTF::move(style));
163         if (style.get().display() == BLOCK || style.get().display() == INLINE_BLOCK)
164             return createRenderer<RenderRubyAsBlock>(element, WTF::move(style));
165     }
166     // treat <rt> as ruby text ONLY if the parent is ruby.
167     if (element.hasTagName(HTMLNames::rtTag) && element.parentElement() && isRuby(element.parentElement()->renderer()))
168         return createRenderer<RenderRubyText>(element, WTF::move(style));
169     switch (style.get().display()) {
170     case NONE:
171         return nullptr;
172     case INLINE:
173         return createRenderer<RenderInline>(element, WTF::move(style));
174     case BLOCK:
175     case INLINE_BLOCK:
176     case COMPACT:
177         return createRenderer<RenderBlockFlow>(element, WTF::move(style));
178     case LIST_ITEM:
179         return createRenderer<RenderListItem>(element, WTF::move(style));
180     case TABLE:
181     case INLINE_TABLE:
182         return createRenderer<RenderTable>(element, WTF::move(style));
183     case TABLE_ROW_GROUP:
184     case TABLE_HEADER_GROUP:
185     case TABLE_FOOTER_GROUP:
186         return createRenderer<RenderTableSection>(element, WTF::move(style));
187     case TABLE_ROW:
188         return createRenderer<RenderTableRow>(element, WTF::move(style));
189     case TABLE_COLUMN_GROUP:
190     case TABLE_COLUMN:
191         return createRenderer<RenderTableCol>(element, WTF::move(style));
192     case TABLE_CELL:
193         return createRenderer<RenderTableCell>(element, WTF::move(style));
194     case TABLE_CAPTION:
195         return createRenderer<RenderTableCaption>(element, WTF::move(style));
196     case BOX:
197     case INLINE_BOX:
198         return createRenderer<RenderDeprecatedFlexibleBox>(element, WTF::move(style));
199     case FLEX:
200     case INLINE_FLEX:
201     case WEBKIT_FLEX:
202     case WEBKIT_INLINE_FLEX:
203         return createRenderer<RenderFlexibleBox>(element, WTF::move(style));
204 #if ENABLE(CSS_GRID_LAYOUT)
205     case GRID:
206     case INLINE_GRID:
207         return createRenderer<RenderGrid>(element, WTF::move(style));
208 #endif
209     }
210     ASSERT_NOT_REACHED();
211     return nullptr;
212 }
213
214 enum StyleCacheState {
215     Cached,
216     Uncached
217 };
218
219 static PassRefPtr<RenderStyle> firstLineStyleForCachedUncachedType(StyleCacheState type, const RenderElement& renderer, RenderStyle* style)
220 {
221     RenderElement& rendererForFirstLineStyle = renderer.isBeforeOrAfterContent() ? *renderer.parent() : const_cast<RenderElement&>(renderer);
222
223     if (rendererForFirstLineStyle.isRenderBlockFlow() || rendererForFirstLineStyle.isRenderButton()) {
224         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle.firstLineBlock()) {
225             if (type == Cached)
226                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
227             return firstLineBlock->getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE), style, firstLineBlock == &renderer ? style : nullptr);
228         }
229     } else if (!rendererForFirstLineStyle.isAnonymous() && rendererForFirstLineStyle.isRenderInline()) {
230         RenderStyle& parentStyle = rendererForFirstLineStyle.parent()->firstLineStyle();
231         if (&parentStyle != &rendererForFirstLineStyle.parent()->style()) {
232             if (type == Cached) {
233                 // A first-line style is in effect. Cache a first-line style for ourselves.
234                 rendererForFirstLineStyle.style().setHasPseudoStyle(FIRST_LINE_INHERITED);
235                 return rendererForFirstLineStyle.getCachedPseudoStyle(FIRST_LINE_INHERITED, &parentStyle);
236             }
237             return rendererForFirstLineStyle.getUncachedPseudoStyle(PseudoStyleRequest(FIRST_LINE_INHERITED), &parentStyle, style);
238         }
239     }
240     return nullptr;
241 }
242
243 PassRefPtr<RenderStyle> RenderElement::uncachedFirstLineStyle(RenderStyle* style) const
244 {
245     if (!document().styleSheetCollection().usesFirstLineRules())
246         return nullptr;
247
248     return firstLineStyleForCachedUncachedType(Uncached, *this, style);
249 }
250
251 RenderStyle* RenderElement::cachedFirstLineStyle() const
252 {
253     ASSERT(document().styleSheetCollection().usesFirstLineRules());
254
255     RenderStyle& style = this->style();
256     if (RefPtr<RenderStyle> firstLineStyle = firstLineStyleForCachedUncachedType(Cached, *this, &style))
257         return firstLineStyle.get();
258
259     return &style;
260 }
261
262 StyleDifference RenderElement::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
263 {
264     // If transform changed, and we are not composited, need to do a layout.
265     if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
266         // FIXME: when transforms are taken into account for overflow, we will need to do a layout.
267         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited()) {
268             if (!hasLayer())
269                 diff = std::max(diff, StyleDifferenceLayout);
270             else {
271                 // We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
272                 // then we actually need SimplifiedLayoutAndPositionedMovement.
273                 diff = std::max(diff, (diff == StyleDifferenceLayoutPositionedMovementOnly) ? StyleDifferenceSimplifiedLayoutAndPositionedMovement : StyleDifferenceSimplifiedLayout);
274             }
275         
276         } else
277             diff = std::max(diff, StyleDifferenceRecompositeLayer);
278     }
279
280     // If opacity changed, and we are not composited, need to repaint (also
281     // ignoring text nodes)
282     if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
283         if (!hasLayer() || !downcast<RenderLayerModelObject>(*this).layer()->isComposited())
284             diff = std::max(diff, StyleDifferenceRepaintLayer);
285         else
286             diff = std::max(diff, StyleDifferenceRecompositeLayer);
287     }
288
289     if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
290         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
291         if (!layer->isComposited() || layer->paintsWithFilters())
292             diff = std::max(diff, StyleDifferenceRepaintLayer);
293         else
294             diff = std::max(diff, StyleDifferenceRecompositeLayer);
295     }
296     
297     // The answer to requiresLayer() for plugins, iframes, and canvas can change without the actual
298     // style changing, since it depends on whether we decide to composite these elements. When the
299     // layer status of one of these elements changes, we need to force a layout.
300     if (diff == StyleDifferenceEqual && isRenderLayerModelObject()) {
301         if (hasLayer() != downcast<RenderLayerModelObject>(*this).requiresLayer())
302             diff = StyleDifferenceLayout;
303     }
304
305     // If we have no layer(), just treat a RepaintLayer hint as a normal Repaint.
306     if (diff == StyleDifferenceRepaintLayer && !hasLayer())
307         diff = StyleDifferenceRepaint;
308
309     return diff;
310 }
311
312 inline bool RenderElement::hasImmediateNonWhitespaceTextChildOrBorderOrOutline() const
313 {
314     for (auto& child : childrenOfType<RenderObject>(*this)) {
315         if (is<RenderText>(child) && !downcast<RenderText>(child).isAllCollapsibleWhitespace())
316             return true;
317         if (child.style().hasOutline() || child.style().hasBorder())
318             return true;
319     }
320     return false;
321 }
322
323 inline bool RenderElement::shouldRepaintForStyleDifference(StyleDifference diff) const
324 {
325     return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrBorderOrOutline && hasImmediateNonWhitespaceTextChildOrBorderOrOutline());
326 }
327
328 void RenderElement::updateFillImages(const FillLayer* oldLayers, const FillLayer* newLayers)
329 {
330     // Optimize the common case
331     if (oldLayers && !oldLayers->next() && newLayers && !newLayers->next() && oldLayers->image() == newLayers->image() && oldLayers->maskImage() == newLayers->maskImage())
332         return;
333     
334     // Go through the new layers and addClients first, to avoid removing all clients of an image.
335     for (const FillLayer* currNew = newLayers; currNew; currNew = currNew->next()) {
336         if (StyleImage* image = currNew->image())
337             image->addClient(this);
338         else if (currNew->maskImage().get())
339             currNew->maskImage()->addRendererImageClient(this);
340     }
341
342     for (const FillLayer* currOld = oldLayers; currOld; currOld = currOld->next()) {
343         if (StyleImage* image = currOld->image())
344             image->removeClient(this);
345         else if (currOld->maskImage().get())
346             currOld->maskImage()->removeRendererImageClient(this);
347     }
348 }
349
350 void RenderElement::updateImage(StyleImage* oldImage, StyleImage* newImage)
351 {
352     if (oldImage == newImage)
353         return;
354     if (oldImage)
355         oldImage->removeClient(this);
356     if (newImage)
357         newImage->addClient(this);
358 }
359
360 #if ENABLE(CSS_SHAPES)
361 void RenderElement::updateShapeImage(const ShapeValue* oldShapeValue, const ShapeValue* newShapeValue)
362 {
363     if (oldShapeValue || newShapeValue)
364         updateImage(oldShapeValue ? oldShapeValue->image() : nullptr, newShapeValue ? newShapeValue->image() : nullptr);
365 }
366 #endif
367
368 void RenderElement::initializeStyle()
369 {
370     styleWillChange(StyleDifferenceEqual, style());
371
372     m_hasInitializedStyle = true;
373
374     updateFillImages(nullptr, m_style->backgroundLayers());
375     updateFillImages(nullptr, m_style->maskLayers());
376
377     updateImage(nullptr, m_style->borderImage().image());
378     updateImage(nullptr, m_style->maskBoxImage().image());
379
380 #if ENABLE(CSS_SHAPES)
381     updateShapeImage(nullptr, m_style->shapeOutside());
382 #endif
383
384     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
385     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
386     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
387         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
388
389     styleDidChange(StyleDifferenceEqual, nullptr);
390
391     // We shouldn't have any text children that would need styleDidChange at this point.
392     ASSERT(!childrenOfType<RenderText>(*this).first());
393
394     // It would be nice to assert that !parent() here, but some RenderLayer subrenderers
395     // have their parent set before getting a call to initializeStyle() :|
396 }
397
398 void RenderElement::setStyle(Ref<RenderStyle>&& style)
399 {
400     // FIXME: Should change RenderView so it can use initializeStyle too.
401     // If we do that, we can assert m_hasInitializedStyle unconditionally,
402     // and remove the check of m_hasInitializedStyle below too.
403     ASSERT(m_hasInitializedStyle || isRenderView());
404
405     if (m_style.ptr() == style.ptr()) {
406         // FIXME: Can we change things so we never hit this code path?
407         // We need to run through adjustStyleDifference() for iframes, plugins, and canvas so
408         // style sharing is disabled for them. That should ensure that we never hit this code path.
409         ASSERT(!isRenderIFrame());
410         ASSERT(!isEmbeddedObject());
411         ASSERT(!isCanvas());
412         return;
413     }
414
415     StyleDifference diff = StyleDifferenceEqual;
416     unsigned contextSensitiveProperties = ContextSensitivePropertyNone;
417     if (m_hasInitializedStyle)
418         diff = m_style->diff(style.get(), contextSensitiveProperties);
419
420     diff = adjustStyleDifference(diff, contextSensitiveProperties);
421
422     styleWillChange(diff, style.get());
423
424     Ref<RenderStyle> oldStyle(m_style.replace(WTF::move(style)));
425
426     updateFillImages(oldStyle.get().backgroundLayers(), m_style->backgroundLayers());
427     updateFillImages(oldStyle.get().maskLayers(), m_style->maskLayers());
428
429     updateImage(oldStyle.get().borderImage().image(), m_style->borderImage().image());
430     updateImage(oldStyle.get().maskBoxImage().image(), m_style->maskBoxImage().image());
431
432 #if ENABLE(CSS_SHAPES)
433     updateShapeImage(oldStyle.get().shapeOutside(), m_style->shapeOutside());
434 #endif
435
436     // We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
437     // during styleDidChange (it's used by clippedOverflowRectForRepaint()).
438     if (m_style->outlineWidth() > 0 && m_style->outlineSize() > maximalOutlineSize(PaintPhaseOutline))
439         view().setMaximalOutlineSize(std::max(theme().platformFocusRingMaxWidth(), static_cast<int>(m_style->outlineSize())));
440
441     bool doesNotNeedLayout = !parent();
442
443     styleDidChange(diff, oldStyle.ptr());
444
445     // Text renderers use their parent style. Notify them about the change.
446     for (auto& child : childrenOfType<RenderText>(*this))
447         child.styleDidChange(diff, oldStyle.ptr());
448
449     // FIXME: |this| might be destroyed here. This can currently happen for a RenderTextFragment when
450     // its first-letter block gets an update in RenderTextFragment::styleDidChange. For RenderTextFragment(s),
451     // we will safely bail out with the doesNotNeedLayout flag. We might want to broaden this condition
452     // in the future as we move renderer changes out of layout and into style changes.
453     if (doesNotNeedLayout)
454         return;
455
456     // Now that the layer (if any) has been updated, we need to adjust the diff again,
457     // check whether we should layout now, and decide if we need to repaint.
458     StyleDifference updatedDiff = adjustStyleDifference(diff, contextSensitiveProperties);
459     
460     if (diff <= StyleDifferenceLayoutPositionedMovementOnly) {
461         if (updatedDiff == StyleDifferenceLayout)
462             setNeedsLayoutAndPrefWidthsRecalc();
463         else if (updatedDiff == StyleDifferenceLayoutPositionedMovementOnly)
464             setNeedsPositionedMovementLayout(oldStyle.ptr());
465         else if (updatedDiff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
466             setNeedsPositionedMovementLayout(oldStyle.ptr());
467             setNeedsSimplifiedNormalFlowLayout();
468         } else if (updatedDiff == StyleDifferenceSimplifiedLayout)
469             setNeedsSimplifiedNormalFlowLayout();
470     }
471
472     if (updatedDiff == StyleDifferenceRepaintLayer || shouldRepaintForStyleDifference(updatedDiff)) {
473         // Do a repaint with the new style now, e.g., for example if we go from
474         // not having an outline to having an outline.
475         repaint();
476     }
477 }
478
479 void RenderElement::addChild(RenderObject* newChild, RenderObject* beforeChild)
480 {
481     bool needsTable = false;
482
483     if (is<RenderTableCol>(*newChild)) {
484         RenderTableCol& newTableColumn = downcast<RenderTableCol>(*newChild);
485         bool isColumnInColumnGroup = newTableColumn.isTableColumn() && is<RenderTableCol>(*this);
486         needsTable = !is<RenderTable>(*this) && !isColumnInColumnGroup;
487     } else if (is<RenderTableCaption>(*newChild))
488         needsTable = !is<RenderTable>(*this);
489     else if (is<RenderTableSection>(*newChild))
490         needsTable = !is<RenderTable>(*this);
491     else if (is<RenderTableRow>(*newChild))
492         needsTable = !is<RenderTableSection>(*this);
493     else if (is<RenderTableCell>(*newChild))
494         needsTable = !is<RenderTableRow>(*this);
495
496     if (needsTable) {
497         RenderTable* table;
498         RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : m_lastChild;
499         if (afterChild && afterChild->isAnonymous() && is<RenderTable>(*afterChild) && !afterChild->isBeforeContent())
500             table = downcast<RenderTable>(afterChild);
501         else {
502             table = RenderTable::createAnonymousWithParentRenderer(this);
503             addChild(table, beforeChild);
504         }
505         table->addChild(newChild);
506     } else
507         insertChildInternal(newChild, beforeChild, NotifyChildren);
508
509     if (is<RenderText>(*newChild))
510         downcast<RenderText>(*newChild).styleDidChange(StyleDifferenceEqual, nullptr);
511
512     // SVG creates renderers for <g display="none">, as SVG requires children of hidden
513     // <g>s to have renderers - at least that's how our implementation works. Consider:
514     // <g display="none"><foreignObject><body style="position: relative">FOO...
515     // - requiresLayer() would return true for the <body>, creating a new RenderLayer
516     // - when the document is painted, both layers are painted. The <body> layer doesn't
517     //   know that it's inside a "hidden SVG subtree", and thus paints, even if it shouldn't.
518     // To avoid the problem alltogether, detect early if we're inside a hidden SVG subtree
519     // and stop creating layers at all for these cases - they're not used anyways.
520     if (newChild->hasLayer() && !layerCreationAllowedForSubtree())
521         downcast<RenderLayerModelObject>(*newChild).layer()->removeOnlyThisLayer();
522
523     SVGRenderSupport::childAdded(*this, *newChild);
524 }
525
526 void RenderElement::removeChild(RenderObject& oldChild)
527 {
528     removeChildInternal(oldChild, NotifyChildren);
529 }
530
531 void RenderElement::destroyLeftoverChildren()
532 {
533     while (m_firstChild) {
534         if (m_firstChild->style().styleType() == FIRST_LETTER && !m_firstChild->isText()) {
535             m_firstChild->removeFromParent(); // :first-letter fragment renderers are destroyed by their remaining text fragment.
536         } else {
537             // 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.
538             if (m_firstChild->node())
539                 m_firstChild->node()->setRenderer(nullptr);
540             m_firstChild->destroy();
541         }
542     }
543 }
544
545 void RenderElement::insertChildInternal(RenderObject* newChild, RenderObject* beforeChild, NotifyChildrenType notifyChildren)
546 {
547     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
548     ASSERT(!newChild->parent());
549     ASSERT(!isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
550
551     while (beforeChild && beforeChild->parent() && beforeChild->parent() != this)
552         beforeChild = beforeChild->parent();
553
554     // This should never happen, but if it does prevent render tree corruption
555     // where child->parent() ends up being owner but child->nextSibling()->parent()
556     // is not owner.
557     if (beforeChild && beforeChild->parent() != this) {
558         ASSERT_NOT_REACHED();
559         return;
560     }
561
562     newChild->setParent(this);
563
564     if (m_firstChild == beforeChild)
565         m_firstChild = newChild;
566
567     if (beforeChild) {
568         RenderObject* previousSibling = beforeChild->previousSibling();
569         if (previousSibling)
570             previousSibling->setNextSibling(newChild);
571         newChild->setPreviousSibling(previousSibling);
572         newChild->setNextSibling(beforeChild);
573         beforeChild->setPreviousSibling(newChild);
574     } else {
575         if (lastChild())
576             lastChild()->setNextSibling(newChild);
577         newChild->setPreviousSibling(lastChild());
578         m_lastChild = newChild;
579     }
580
581     if (!documentBeingDestroyed()) {
582         if (notifyChildren == NotifyChildren)
583             newChild->insertedIntoTree();
584         if (is<RenderElement>(*newChild))
585             RenderCounter::rendererSubtreeAttached(downcast<RenderElement>(*newChild));
586     }
587
588     newChild->setNeedsLayoutAndPrefWidthsRecalc();
589     setPreferredLogicalWidthsDirty(true);
590     if (!normalChildNeedsLayout())
591         setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
592
593     if (AXObjectCache* cache = document().axObjectCache())
594         cache->childrenChanged(this, newChild);
595 }
596
597 void RenderElement::removeChildInternal(RenderObject& oldChild, NotifyChildrenType notifyChildren)
598 {
599     ASSERT(canHaveChildren() || canHaveGeneratedChildren());
600     ASSERT(oldChild.parent() == this);
601
602     if (oldChild.isFloatingOrOutOfFlowPositioned())
603         downcast<RenderBox>(oldChild).removeFloatingOrPositionedChildFromBlockLists();
604
605     // So that we'll get the appropriate dirty bit set (either that a normal flow child got yanked or
606     // that a positioned child got yanked). We also repaint, so that the area exposed when the child
607     // disappears gets repainted properly.
608     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren && oldChild.everHadLayout()) {
609         oldChild.setNeedsLayoutAndPrefWidthsRecalc();
610         // We only repaint |oldChild| if we have a RenderLayer as its visual overflow may not be tracked by its parent.
611         if (oldChild.isBody())
612             view().repaintRootContents();
613         else
614             oldChild.repaint();
615     }
616
617     // If we have a line box wrapper, delete it.
618     if (is<RenderBox>(oldChild))
619         downcast<RenderBox>(oldChild).deleteLineBoxWrapper();
620     else if (is<RenderLineBreak>(oldChild))
621         downcast<RenderLineBreak>(oldChild).deleteInlineBoxWrapper();
622
623     // If oldChild is the start or end of the selection, then clear the selection to
624     // avoid problems of invalid pointers.
625     if (!documentBeingDestroyed() && oldChild.isSelectionBorder())
626         frame().selection().setNeedsSelectionUpdate();
627
628     if (!documentBeingDestroyed() && notifyChildren == NotifyChildren)
629         oldChild.willBeRemovedFromTree();
630
631     // WARNING: There should be no code running between willBeRemovedFromTree and the actual removal below.
632     // This is needed to avoid race conditions where willBeRemovedFromTree would dirty the tree's structure
633     // and the code running here would force an untimely rebuilding, leaving |oldChild| dangling.
634     
635     RenderObject* nextSibling = oldChild.nextSibling();
636
637     if (oldChild.previousSibling())
638         oldChild.previousSibling()->setNextSibling(nextSibling);
639     if (nextSibling)
640         nextSibling->setPreviousSibling(oldChild.previousSibling());
641
642     if (m_firstChild == &oldChild)
643         m_firstChild = nextSibling;
644     if (m_lastChild == &oldChild)
645         m_lastChild = oldChild.previousSibling();
646
647     oldChild.setPreviousSibling(nullptr);
648     oldChild.setNextSibling(nullptr);
649     oldChild.setParent(nullptr);
650
651     // rendererRemovedFromTree walks the whole subtree. We can improve performance
652     // by skipping this step when destroying the entire tree.
653     if (!documentBeingDestroyed() && is<RenderElement>(oldChild))
654         RenderCounter::rendererRemovedFromTree(downcast<RenderElement>(oldChild));
655
656     if (AXObjectCache* cache = document().existingAXObjectCache())
657         cache->childrenChanged(this);
658 }
659
660 static void addLayers(RenderElement& renderer, RenderLayer* parentLayer, RenderElement*& newObject, RenderLayer*& beforeChild)
661 {
662     if (renderer.hasLayer()) {
663         if (!beforeChild && newObject) {
664             // We need to figure out the layer that follows newObject. We only do
665             // this the first time we find a child layer, and then we update the
666             // pointer values for newObject and beforeChild used by everyone else.
667             beforeChild = newObject->parent()->findNextLayer(parentLayer, newObject);
668             newObject = nullptr;
669         }
670         parentLayer->addChild(downcast<RenderLayerModelObject>(renderer).layer(), beforeChild);
671         return;
672     }
673
674     for (auto& child : childrenOfType<RenderElement>(renderer))
675         addLayers(child, parentLayer, newObject, beforeChild);
676 }
677
678 void RenderElement::addLayers(RenderLayer* parentLayer)
679 {
680     if (!parentLayer)
681         return;
682
683     RenderElement* renderer = this;
684     RenderLayer* beforeChild = nullptr;
685     WebCore::addLayers(*this, parentLayer, renderer, beforeChild);
686 }
687
688 void RenderElement::removeLayers(RenderLayer* parentLayer)
689 {
690     if (!parentLayer)
691         return;
692
693     if (hasLayer()) {
694         parentLayer->removeChild(downcast<RenderLayerModelObject>(*this).layer());
695         return;
696     }
697
698     for (auto& child : childrenOfType<RenderElement>(*this))
699         child.removeLayers(parentLayer);
700 }
701
702 void RenderElement::moveLayers(RenderLayer* oldParent, RenderLayer* newParent)
703 {
704     if (!newParent)
705         return;
706
707     if (hasLayer()) {
708         RenderLayer* layer = downcast<RenderLayerModelObject>(*this).layer();
709         ASSERT(oldParent == layer->parent());
710         if (oldParent)
711             oldParent->removeChild(layer);
712         newParent->addChild(layer);
713         return;
714     }
715
716     for (auto& child : childrenOfType<RenderElement>(*this))
717         child.moveLayers(oldParent, newParent);
718 }
719
720 RenderLayer* RenderElement::findNextLayer(RenderLayer* parentLayer, RenderObject* startPoint, bool checkParent)
721 {
722     // Error check the parent layer passed in. If it's null, we can't find anything.
723     if (!parentLayer)
724         return nullptr;
725
726     // Step 1: If our layer is a child of the desired parent, then return our layer.
727     RenderLayer* ourLayer = hasLayer() ? downcast<RenderLayerModelObject>(*this).layer() : nullptr;
728     if (ourLayer && ourLayer->parent() == parentLayer)
729         return ourLayer;
730
731     // Step 2: If we don't have a layer, or our layer is the desired parent, then descend
732     // into our siblings trying to find the next layer whose parent is the desired parent.
733     if (!ourLayer || ourLayer == parentLayer) {
734         for (RenderObject* child = startPoint ? startPoint->nextSibling() : firstChild(); child; child = child->nextSibling()) {
735             if (!is<RenderElement>(*child))
736                 continue;
737             RenderLayer* nextLayer = downcast<RenderElement>(*child).findNextLayer(parentLayer, nullptr, false);
738             if (nextLayer)
739                 return nextLayer;
740         }
741     }
742
743     // Step 3: If our layer is the desired parent layer, then we're finished. We didn't
744     // find anything.
745     if (parentLayer == ourLayer)
746         return nullptr;
747
748     // Step 4: If |checkParent| is set, climb up to our parent and check its siblings that
749     // follow us to see if we can locate a layer.
750     if (checkParent && parent())
751         return parent()->findNextLayer(parentLayer, this, true);
752
753     return nullptr;
754 }
755
756 bool RenderElement::layerCreationAllowedForSubtree() const
757 {
758     RenderElement* parentRenderer = parent();
759     while (parentRenderer) {
760         if (parentRenderer->isSVGHiddenContainer())
761             return false;
762         parentRenderer = parentRenderer->parent();
763     }
764     
765     return true;
766 }
767
768 void RenderElement::propagateStyleToAnonymousChildren(StylePropagationType propagationType)
769 {
770     // FIXME: We could save this call when the change only affected non-inherited properties.
771     for (auto& elementChild : childrenOfType<RenderElement>(*this)) {
772         if (!elementChild.isAnonymous() || elementChild.style().styleType() != NOPSEUDO)
773             continue;
774
775         if (propagationType == PropagateToBlockChildrenOnly && !is<RenderBlock>(elementChild))
776             continue;
777
778 #if ENABLE(FULLSCREEN_API)
779         if (elementChild.isRenderFullScreen() || elementChild.isRenderFullScreenPlaceholder())
780             continue;
781 #endif
782
783         // RenderFlowThreads are updated through the RenderView::styleDidChange function.
784         if (is<RenderFlowThread>(elementChild))
785             continue;
786
787         auto newStyle = RenderStyle::createAnonymousStyleWithDisplay(&style(), elementChild.style().display());
788         if (style().specifiesColumns()) {
789             if (elementChild.style().specifiesColumns())
790                 newStyle.get().inheritColumnPropertiesFrom(&style());
791             if (elementChild.style().columnSpan())
792                 newStyle.get().setColumnSpan(ColumnSpanAll);
793         }
794
795         // Preserve the position style of anonymous block continuations as they can have relative or sticky position when
796         // they contain block descendants of relative or sticky positioned inlines.
797         if (elementChild.isInFlowPositioned() && downcast<RenderBlock>(elementChild).isAnonymousBlockContinuation())
798             newStyle.get().setPosition(elementChild.style().position());
799
800         elementChild.setStyle(WTF::move(newStyle));
801     }
802 }
803
804 static inline bool rendererHasBackground(const RenderElement* renderer)
805 {
806     return renderer && renderer->hasBackground();
807 }
808
809 void RenderElement::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
810 {
811     RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
812     if (oldStyle) {
813         // If our z-index changes value or our visibility changes,
814         // we need to dirty our stacking context's z-order list.
815         bool visibilityChanged = m_style->visibility() != newStyle.visibility()
816             || m_style->zIndex() != newStyle.zIndex()
817             || m_style->hasAutoZIndex() != newStyle.hasAutoZIndex();
818 #if ENABLE(DASHBOARD_SUPPORT)
819         if (visibilityChanged)
820             document().setAnnotatedRegionsDirty(true);
821 #endif
822 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
823         if (visibilityChanged)
824             document().dirtyTouchEventRects();
825 #endif
826         if (visibilityChanged) {
827             if (AXObjectCache* cache = document().existingAXObjectCache())
828                 cache->childrenChanged(parent(), this);
829         }
830
831         // Keep layer hierarchy visibility bits up to date if visibility changes.
832         if (m_style->visibility() != newStyle.visibility()) {
833             if (RenderLayer* layer = enclosingLayer()) {
834                 if (newStyle.visibility() == VISIBLE)
835                     layer->setHasVisibleContent();
836                 else if (layer->hasVisibleContent() && (this == &layer->renderer() || layer->renderer().style().visibility() != VISIBLE)) {
837                     layer->dirtyVisibleContentStatus();
838                     if (diff > StyleDifferenceRepaintLayer)
839                         repaint();
840                 }
841             }
842         }
843
844         if (m_parent && (newStyle.outlineSize() < m_style->outlineSize() || shouldRepaintForStyleDifference(diff)))
845             repaint();
846         if (isFloating() && (m_style->floating() != newStyle.floating()))
847             // For changes in float styles, we need to conceivably remove ourselves
848             // from the floating objects list.
849             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
850         else if (isOutOfFlowPositioned() && (m_style->position() != newStyle.position()))
851             // For changes in positioning styles, we need to conceivably remove ourselves
852             // from the positioned objects list.
853             downcast<RenderBox>(*this).removeFloatingOrPositionedChildFromBlockLists();
854
855         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
856             && (!newStyle.isFloating() && !newStyle.hasOutOfFlowPosition())
857             && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
858
859         s_noLongerAffectsParentBlock = ((!isFloating() && newStyle.isFloating()) || (!isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()))
860             && parent() && parent()->isRenderBlock();
861
862         // reset style flags
863         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
864             setFloating(false);
865             clearPositionedState();
866         }
867         setHorizontalWritingMode(true);
868         setHasBoxDecorations(false);
869         setHasOverflowClip(false);
870         setHasTransformRelatedProperty(false);
871         setHasReflection(false);
872     } else {
873         s_affectsParentBlock = false;
874         s_noLongerAffectsParentBlock = false;
875     }
876
877     bool newStyleUsesFixedBackgrounds = newStyle.hasFixedBackgroundImage();
878     bool oldStyleUsesFixedBackgrounds = m_style->hasFixedBackgroundImage();
879     if (newStyleUsesFixedBackgrounds || oldStyleUsesFixedBackgrounds) {
880         bool repaintFixedBackgroundsOnScroll = !frame().settings().fixedBackgroundsPaintRelativeToDocument();
881
882         bool newStyleSlowScroll = repaintFixedBackgroundsOnScroll && newStyleUsesFixedBackgrounds;
883         bool oldStyleSlowScroll = oldStyle && repaintFixedBackgroundsOnScroll && oldStyleUsesFixedBackgrounds;
884         bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
885         if (drawsRootBackground && repaintFixedBackgroundsOnScroll) {
886             if (view().compositor().supportsFixedRootBackgroundCompositing()) {
887                 if (newStyleSlowScroll && newStyle.hasEntirelyFixedBackground())
888                     newStyleSlowScroll = false;
889
890                 if (oldStyleSlowScroll && m_style->hasEntirelyFixedBackground())
891                     oldStyleSlowScroll = false;
892             }
893         }
894
895         if (oldStyleSlowScroll != newStyleSlowScroll) {
896             if (oldStyleSlowScroll)
897                 view().frameView().removeSlowRepaintObject(this);
898
899             if (newStyleSlowScroll)
900                 view().frameView().addSlowRepaintObject(this);
901         }
902     }
903
904     if (isRoot() || isBody())
905         view().frameView().updateExtendBackgroundIfNecessary();
906 }
907
908 void RenderElement::handleDynamicFloatPositionChange()
909 {
910     // We have gone from not affecting the inline status of the parent flow to suddenly
911     // having an impact.  See if there is a mismatch between the parent flow's
912     // childrenInline() state and our state.
913     setInline(style().isDisplayInlineType());
914     if (isInline() != parent()->childrenInline()) {
915         if (!isInline())
916             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
917         else {
918             // An anonymous block must be made to wrap this inline.
919             RenderBlock* block = downcast<RenderBlock>(*parent()).createAnonymousBlock();
920             parent()->insertChildInternal(block, this, RenderElement::NotifyChildren);
921             parent()->removeChildInternal(*this, RenderElement::NotifyChildren);
922             block->insertChildInternal(this, nullptr, RenderElement::NotifyChildren);
923         }
924     }
925 }
926
927 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
928 {
929     RenderBlock& parentBlock = downcast<RenderBlock>(*parent());
930     if (!parentBlock.canCollapseAnonymousBlockChild())
931         return;
932
933     // We have changed to floated or out-of-flow positioning so maybe all our parent's
934     // children can be inline now. Bail if there are any block children left on the line,
935     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
936     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
937     // if we find a continuation.
938     RenderObject* current = parent()->firstChild();
939     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isAnonymousBlockContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
940         current = current->nextSibling();
941
942     if (current)
943         return;
944
945     RenderObject* next;
946     for (current = parent()->firstChild(); current; current = next) {
947         next = current->nextSibling();
948         if (current->isAnonymousBlock())
949             parentBlock.collapseAnonymousBoxChild(parentBlock, downcast<RenderBlock>(current));
950     }
951 }
952
953 #if !PLATFORM(IOS)
954 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
955 {
956     ASSERT(a->cursors() != b->cursors());
957     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
958 }
959
960 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
961 {
962     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
963 }
964 #endif
965
966 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
967 {
968     if (s_affectsParentBlock)
969         handleDynamicFloatPositionChange();
970
971     if (s_noLongerAffectsParentBlock)
972         removeAnonymousWrappersForInlinesIfNecessary();
973
974     SVGRenderSupport::styleChanged(*this, oldStyle);
975
976     if (!m_parent)
977         return;
978     
979     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
980         RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.ptr());
981
982         // If the object already needs layout, then setNeedsLayout won't do
983         // any work. But if the containing block has changed, then we may need
984         // to mark the new containing blocks for layout. The change that can
985         // directly affect the containing block of this object is a change to
986         // the position style.
987         if (needsLayout() && oldStyle->position() != m_style->position())
988             markContainingBlocksForLayout();
989
990         if (diff == StyleDifferenceLayout)
991             setNeedsLayoutAndPrefWidthsRecalc();
992         else
993             setNeedsSimplifiedNormalFlowLayout();
994     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
995         setNeedsPositionedMovementLayout(oldStyle);
996         setNeedsSimplifiedNormalFlowLayout();
997     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
998         setNeedsPositionedMovementLayout(oldStyle);
999
1000     // Don't check for repaint here; we need to wait until the layer has been
1001     // updated by subclasses before we know if we have to repaint (in setStyle()).
1002
1003 #if !PLATFORM(IOS)
1004     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1005         frame().eventHandler().scheduleCursorUpdate();
1006 #endif
1007 }
1008
1009 void RenderElement::insertedIntoTree()
1010 {
1011     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1012         containerFlowThread->addFlowChild(*this);
1013
1014     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1015     // and don't have a layer attached to ourselves.
1016     RenderLayer* layer = nullptr;
1017     if (firstChild() || hasLayer()) {
1018         layer = parent()->enclosingLayer();
1019         addLayers(layer);
1020     }
1021
1022     // If |this| is visible but this object was not, tell the layer it has some visible content
1023     // that needs to be drawn and layer visibility optimization can't be used
1024     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1025         if (!layer)
1026             layer = parent()->enclosingLayer();
1027         if (layer)
1028             layer->setHasVisibleContent();
1029     }
1030
1031     RenderObject::insertedIntoTree();
1032 }
1033
1034 void RenderElement::willBeRemovedFromTree()
1035 {
1036     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1037     RenderLayer* layer = nullptr;
1038     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1039         if ((layer = parent()->enclosingLayer()))
1040             layer->dirtyVisibleContentStatus();
1041     }
1042     // Keep our layer hierarchy updated.
1043     if (firstChild() || hasLayer()) {
1044         if (!layer)
1045             layer = parent()->enclosingLayer();
1046         removeLayers(layer);
1047     }
1048
1049     if (m_style->hasFixedBackgroundImage() && !frame().settings().fixedBackgroundsPaintRelativeToDocument())
1050         view().frameView().removeSlowRepaintObject(this);
1051
1052     if (isOutOfFlowPositioned() && parent()->childrenInline())
1053         parent()->dirtyLinesFromChangedChild(*this);
1054
1055     if (auto* containerFlowThread = parent()->renderNamedFlowThreadWrapper())
1056         containerFlowThread->removeFlowChild(*this);
1057
1058     RenderObject::willBeRemovedFromTree();
1059 }
1060
1061 void RenderElement::willBeDestroyed()
1062 {
1063     animation().cancelAnimations(*this);
1064
1065     destroyLeftoverChildren();
1066
1067     if (hasCounterNodeMap())
1068         RenderCounter::destroyCounterNodes(*this);
1069
1070     RenderObject::willBeDestroyed();
1071
1072 #if !ASSERT_DISABLED
1073     if (!documentBeingDestroyed() && view().hasRenderNamedFlowThreads()) {
1074         // After remove, the object and the associated information should not be in any flow thread.
1075         for (auto& flowThread : *view().flowThreadController().renderNamedFlowThreadList()) {
1076             ASSERT(!flowThread->hasChild(*this));
1077             ASSERT(!flowThread->hasChildInfo(this));
1078         }
1079     }
1080 #endif
1081 }
1082
1083 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1084 {
1085     ASSERT(!isSetNeedsLayoutForbidden());
1086     if (needsPositionedMovementLayout())
1087         return;
1088     setNeedsPositionedMovementLayoutBit(true);
1089     markContainingBlocksForLayout();
1090     if (hasLayer()) {
1091         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1092             setLayerNeedsFullRepaint();
1093         else
1094             setLayerNeedsFullRepaintForPositionedMovementLayout();
1095     }
1096 }
1097
1098 void RenderElement::clearChildNeedsLayout()
1099 {
1100     setNormalChildNeedsLayoutBit(false);
1101     setPosChildNeedsLayoutBit(false);
1102     setNeedsSimplifiedNormalFlowLayoutBit(false);
1103     setNormalChildNeedsLayoutBit(false);
1104     setNeedsPositionedMovementLayoutBit(false);
1105 }
1106
1107 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1108 {
1109     ASSERT(!isSetNeedsLayoutForbidden());
1110     if (needsSimplifiedNormalFlowLayout())
1111         return;
1112     setNeedsSimplifiedNormalFlowLayoutBit(true);
1113     markContainingBlocksForLayout();
1114     if (hasLayer())
1115         setLayerNeedsFullRepaint();
1116 }
1117
1118 RenderElement& RenderElement::rendererForRootBackground()
1119 {
1120     ASSERT(isRoot());
1121     if (!hasBackground() && is<HTMLHtmlElement>(element())) {
1122         // Locate the <body> element using the DOM. This is easier than trying
1123         // to crawl around a render tree with potential :before/:after content and
1124         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
1125         // render object very easily via the DOM.
1126         if (auto* body = document().body()) {
1127             if (auto* renderer = body->renderer())
1128                 return *renderer;
1129         }
1130     }
1131     return *this;
1132 }
1133
1134 RenderElement* RenderElement::hoverAncestor() const
1135 {
1136     // When searching for the hover ancestor and encountering a named flow thread,
1137     // the search will continue with the DOM ancestor of the top-most element
1138     // in the named flow thread.
1139     // See https://bugs.webkit.org/show_bug.cgi?id=111749
1140     RenderElement* hoverAncestor = parent();
1141
1142     // Skip anonymous blocks directly flowed into flow threads as it would
1143     // prevent us from continuing the search on the DOM tree when reaching the named flow thread.
1144     if (hoverAncestor && hoverAncestor->isAnonymousBlock() && hoverAncestor->parent() && hoverAncestor->parent()->isRenderNamedFlowThread())
1145         hoverAncestor = hoverAncestor->parent();
1146
1147     if (hoverAncestor && hoverAncestor->isRenderNamedFlowThread()) {
1148         hoverAncestor = nullptr;
1149         if (Element* element = this->element()) {
1150             if (auto parent = element->parentNode())
1151                 hoverAncestor = parent->renderer();
1152         }
1153     }
1154
1155     return hoverAncestor;
1156 }
1157
1158 void RenderElement::layout()
1159 {
1160     StackStats::LayoutCheckPoint layoutCheckPoint;
1161     ASSERT(needsLayout());
1162     RenderObject* child = firstChild();
1163     while (child) {
1164         if (child->needsLayout())
1165             downcast<RenderElement>(*child).layout();
1166         ASSERT(!child->needsLayout());
1167         child = child->nextSibling();
1168     }
1169     clearNeedsLayout();
1170 }
1171
1172 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer* layer)
1173 {
1174     // Nobody will use multiple layers without wanting fancy positioning.
1175     if (layer->next())
1176         return true;
1177
1178     // Make sure we have a valid image.
1179     StyleImage* image = layer->image();
1180     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1181         return false;
1182
1183     if (!layer->xPosition().isZero() || !layer->yPosition().isZero())
1184         return true;
1185
1186     EFillSizeType sizeType = layer->sizeType();
1187
1188     if (sizeType == Contain || sizeType == Cover)
1189         return true;
1190
1191     if (sizeType == SizeLength) {
1192         LengthSize size = layer->sizeLength();
1193         if (size.width().isPercent() || size.height().isPercent())
1194             return true;
1195         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1196         if ((size.width().isAuto() || size.height().isAuto()) && image->isGeneratedImage())
1197             return true;
1198     } else if (image->usesImageContainerSize())
1199         return true;
1200
1201     return false;
1202 }
1203
1204 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1205 {
1206     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1207         return true;
1208
1209     // If we don't have a background/border/mask, then nothing to do.
1210     if (!renderer.hasBoxDecorations())
1211         return false;
1212
1213     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1214         return true;
1215
1216     // Our fill layers are ok. Let's check border.
1217     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1218         return true;
1219
1220     return false;
1221 }
1222
1223 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1224 {
1225     if (view().printing())
1226         return false; // Don't repaint if we're printing.
1227
1228     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1229     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1230     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1231     LayoutRect newOutlineBox;
1232
1233     bool fullRepaint = selfNeedsLayout();
1234     // Presumably a background or a border exists if border-fit:lines was specified.
1235     if (!fullRepaint && style().borderFit() == BorderFitLines)
1236         fullRepaint = true;
1237     if (!fullRepaint) {
1238         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1239         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1240         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1241         if (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)))
1242             fullRepaint = true;
1243     }
1244
1245     if (!repaintContainer)
1246         repaintContainer = &view();
1247
1248     if (fullRepaint) {
1249         repaintUsingContainer(repaintContainer, oldBounds);
1250         if (newBounds != oldBounds)
1251             repaintUsingContainer(repaintContainer, newBounds);
1252         return true;
1253     }
1254
1255     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1256         return false;
1257
1258     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1259     if (deltaLeft > 0)
1260         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1261     else if (deltaLeft < 0)
1262         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1263
1264     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1265     if (deltaRight > 0)
1266         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1267     else if (deltaRight < 0)
1268         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1269
1270     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1271     if (deltaTop > 0)
1272         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1273     else if (deltaTop < 0)
1274         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1275
1276     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1277     if (deltaBottom > 0)
1278         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1279     else if (deltaBottom < 0)
1280         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1281
1282     if (newOutlineBox == oldOutlineBox)
1283         return false;
1284
1285     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1286     // two rectangles (but typically only one).
1287     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1288     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1289     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1290     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1291     if (width) {
1292         LayoutUnit shadowLeft;
1293         LayoutUnit shadowRight;
1294         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1295         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1296         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1297         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min<LayoutUnit>(newBounds.width(), oldBounds.width()));
1298         LayoutUnit borderWidth = std::max<LayoutUnit>(borderRight, std::max<LayoutUnit>(valueForLength(style().borderTopRightRadius().width(), boxWidth), valueForLength(style().borderBottomRightRadius().width(), boxWidth)));
1299         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowRight);
1300         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1301             newOutlineBox.y(),
1302             width + decorationsWidth,
1303             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1304         LayoutUnit right = std::min<LayoutUnit>(newBounds.maxX(), oldBounds.maxX());
1305         if (rightRect.x() < right) {
1306             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1307             repaintUsingContainer(repaintContainer, rightRect);
1308         }
1309     }
1310     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1311     if (height) {
1312         LayoutUnit shadowTop;
1313         LayoutUnit shadowBottom;
1314         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1315         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1316         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1317         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min<LayoutUnit>(newBounds.height(), oldBounds.height()));
1318         LayoutUnit borderHeight = std::max<LayoutUnit>(borderBottom, std::max<LayoutUnit>(valueForLength(style().borderBottomLeftRadius().height(), boxHeight),
1319             valueForLength(style().borderBottomRightRadius().height(), boxHeight)));
1320         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max<LayoutUnit>(outlineWidth, shadowBottom);
1321         LayoutRect bottomRect(newOutlineBox.x(),
1322             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1323             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1324             height + decorationsHeight);
1325         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1326         if (bottomRect.y() < bottom) {
1327             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1328             repaintUsingContainer(repaintContainer, bottomRect);
1329         }
1330     }
1331     return false;
1332 }
1333
1334 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1335 {
1336     ASSERT(style().hasBorder());
1337
1338     StyleImage* borderImage = style().borderImage().image();
1339     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1340 }
1341
1342 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1343 {
1344     auto& frameView = view().frameView();
1345     if (frameView.isOffscreen())
1346         return false;
1347
1348     if (!hasOverflowClip()) {
1349         // FIXME: Computing the overflow rect is expensive if any descendant has
1350         // its own self-painting layer. As a result, we prefer to abort early in
1351         // this case and assume it may cause us to repaint inside the viewport.
1352         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1353             return true;
1354     }
1355
1356     // Compute viewport rect if it was not provided.
1357     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1358     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1359 }
1360
1361 static bool shouldRepaintForImageAnimation(const RenderElement& renderer, const IntRect& visibleRect)
1362 {
1363     const Document& document = renderer.document();
1364     if (document.inPageCache())
1365         return false;
1366 #if PLATFORM(IOS)
1367     if (document.frame()->timersPaused())
1368         return false;
1369 #endif
1370     if (document.activeDOMObjectsAreSuspended())
1371         return false;
1372     if (renderer.style().visibility() != VISIBLE)
1373         return false;
1374     if (renderer.view().frameView().isOffscreen())
1375         return false;
1376
1377     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1378     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1379     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1380     // can no longer check if it is a background image.
1381     bool backgroundIsPaintedByRoot = renderer.isRoot();
1382     if (renderer.isBody()) {
1383         auto& rootRenderer = *renderer.parent(); // If <body> has a renderer then <html> does too.
1384         ASSERT(rootRenderer.isRoot());
1385         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1386         // FIXME: Should share body background propagation code.
1387         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1388
1389     }
1390     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? renderer.view().backgroundRect(&renderer.view()) : renderer.absoluteClippedOverflowRect();
1391     if (!visibleRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1392         return false;
1393
1394     return true;
1395 }
1396
1397 void RenderElement::newImageAnimationFrameAvailable(CachedImage& image)
1398 {
1399     if (document().inPageCache())
1400         return;
1401     auto& frameView = view().frameView();
1402     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1403     if (!shouldRepaintForImageAnimation(*this, visibleRect)) {
1404         // FIXME: It would be better to pass the image along with the renderer
1405         // so that we can be smarter about detecting if the image is inside the
1406         // viewport in repaintForPausedImageAnimationsIfNeeded().
1407         view().addRendererWithPausedImageAnimations(*this);
1408         return;
1409     }
1410     imageChanged(&image);
1411 }
1412
1413 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect)
1414 {
1415     ASSERT(m_hasPausedImageAnimations);
1416     if (!shouldRepaintForImageAnimation(*this, visibleRect))
1417         return false;
1418     repaint();
1419     return true;
1420 }
1421
1422 RenderNamedFlowThread* RenderElement::renderNamedFlowThreadWrapper()
1423 {
1424     auto* renderer = this;
1425     while (renderer && renderer->isAnonymousBlock() && !is<RenderNamedFlowThread>(*renderer))
1426         renderer = renderer->parent();
1427     return is<RenderNamedFlowThread>(renderer) ? downcast<RenderNamedFlowThread>(renderer) : nullptr;
1428 }
1429
1430 bool RenderElement::hasControlStatesForRenderer(const RenderObject* o)
1431 {
1432     return controlStatesRendererMap().contains(o);
1433 }
1434
1435 ControlStates* RenderElement::controlStatesForRenderer(const RenderObject* o)
1436 {
1437     return controlStatesRendererMap().get(o);
1438 }
1439
1440 void RenderElement::removeControlStatesForRenderer(const RenderObject* o)
1441 {
1442     ControlStates* states = controlStatesRendererMap().get(o);
1443     if (states) {
1444         controlStatesRendererMap().remove(o);
1445         delete states;
1446     }
1447 }
1448
1449 void RenderElement::addControlStatesForRenderer(const RenderObject* o, ControlStates* states)
1450 {
1451     controlStatesRendererMap().add(o, states);
1452 }
1453
1454 RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, RenderStyle* parentStyle) const
1455 {
1456     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1457         return nullptr;
1458
1459     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1460     if (cachedStyle)
1461         return cachedStyle;
1462
1463     RefPtr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1464     if (result)
1465         return style().addCachedPseudoStyle(result.release());
1466     return nullptr;
1467 }
1468
1469 PassRefPtr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, RenderStyle* ownStyle) const
1470 {
1471     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1472         return nullptr;
1473
1474     if (!parentStyle) {
1475         ASSERT(!ownStyle);
1476         parentStyle = &style();
1477     }
1478
1479     if (isAnonymous())
1480         return nullptr;
1481
1482     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
1483         RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element(), parentStyle, DisallowStyleSharing);
1484         result->setStyleType(FIRST_LINE_INHERITED);
1485         return result.release();
1486     }
1487
1488     return document().ensureStyleResolver().pseudoStyleForElement(element(), pseudoStyleRequest, parentStyle);
1489 }
1490
1491 Color RenderElement::selectionColor(int colorProperty) const
1492 {
1493     // If the element is unselectable, or we are only painting the selection,
1494     // don't override the foreground color with the selection foreground color.
1495     if (style().userSelect() == SELECT_NONE
1496         || (view().frameView().paintBehavior() & PaintBehaviorSelectionOnly))
1497         return Color();
1498
1499     if (RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1500         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1501         if (!color.isValid())
1502             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1503         return color;
1504     }
1505
1506     if (frame().selection().isFocusedAndActive())
1507         return theme().activeSelectionForegroundColor();
1508     return theme().inactiveSelectionForegroundColor();
1509 }
1510
1511 PassRefPtr<RenderStyle> RenderElement::selectionPseudoStyle() const
1512 {
1513     if (isAnonymous())
1514         return nullptr;
1515
1516     if (ShadowRoot* root = element()->containingShadowRoot()) {
1517         if (root->type() == ShadowRoot::UserAgentShadowRoot) {
1518             if (Element* shadowHost = element()->shadowHost())
1519                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1520         }
1521     }
1522
1523     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1524 }
1525
1526 Color RenderElement::selectionForegroundColor() const
1527 {
1528     return selectionColor(CSSPropertyWebkitTextFillColor);
1529 }
1530
1531 Color RenderElement::selectionEmphasisMarkColor() const
1532 {
1533     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1534 }
1535
1536 Color RenderElement::selectionBackgroundColor() const
1537 {
1538     if (style().userSelect() == SELECT_NONE)
1539         return Color();
1540
1541     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1542         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1543
1544     RefPtr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1545     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1546         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1547
1548     if (frame().selection().isFocusedAndActive())
1549         return theme().activeSelectionBackgroundColor();
1550     return theme().inactiveSelectionBackgroundColor();
1551 }
1552
1553 bool RenderElement::getLeadingCorner(FloatPoint& point) const
1554 {
1555     if (!isInline() || isReplaced()) {
1556         point = localToAbsolute(FloatPoint(), UseTransforms);
1557         return true;
1558     }
1559
1560     // find the next text/image child, to get a position
1561     const RenderObject* o = this;
1562     while (o) {
1563         const RenderObject* p = o;
1564         if (RenderObject* child = o->firstChildSlow())
1565             o = child;
1566         else if (o->nextSibling())
1567             o = o->nextSibling();
1568         else {
1569             RenderObject* next = 0;
1570             while (!next && o->parent()) {
1571                 o = o->parent();
1572                 next = o->nextSibling();
1573             }
1574             o = next;
1575
1576             if (!o)
1577                 break;
1578         }
1579         ASSERT(o);
1580
1581         if (!o->isInline() || o->isReplaced()) {
1582             point = o->localToAbsolute(FloatPoint(), UseTransforms);
1583             return true;
1584         }
1585
1586         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1587             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1588         } else if (is<RenderText>(*o) || o->isReplaced()) {
1589             point = FloatPoint();
1590             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1591                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1592             else if (is<RenderBox>(*o))
1593                 point.moveBy(downcast<RenderBox>(*o).location());
1594             point = o->container()->localToAbsolute(point, UseTransforms);
1595             return true;
1596         }
1597     }
1598     
1599     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1600     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1601     if (!o && document().view()) {
1602         point = FloatPoint(0, document().view()->contentsHeight());
1603         return true;
1604     }
1605     return false;
1606 }
1607
1608 bool RenderElement::getTrailingCorner(FloatPoint& point) const
1609 {
1610     if (!isInline() || isReplaced()) {
1611         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms);
1612         return true;
1613     }
1614
1615     // find the last text/image child, to get a position
1616     const RenderObject* o = this;
1617     while (o) {
1618         if (RenderObject* child = o->lastChildSlow())
1619             o = child;
1620         else if (o->previousSibling())
1621             o = o->previousSibling();
1622         else {
1623             RenderObject* prev = 0;
1624             while (!prev) {
1625                 o = o->parent();
1626                 if (!o)
1627                     return false;
1628                 prev = o->previousSibling();
1629             }
1630             o = prev;
1631         }
1632         ASSERT(o);
1633         if (is<RenderText>(*o) || o->isReplaced()) {
1634             point = FloatPoint();
1635             if (is<RenderText>(*o)) {
1636                 IntRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1637                 if (!linesBox.maxX() && !linesBox.maxY())
1638                     continue;
1639                 point.moveBy(linesBox.maxXMaxYCorner());
1640             } else
1641                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1642             point = o->container()->localToAbsolute(point, UseTransforms);
1643             return true;
1644         }
1645     }
1646     return true;
1647 }
1648
1649 LayoutRect RenderElement::anchorRect() const
1650 {
1651     FloatPoint leading, trailing;
1652     bool foundLeading = getLeadingCorner(leading);
1653     bool foundTrailing = getTrailingCorner(trailing);
1654     
1655     // If we've found one corner, but not the other,
1656     // then we should just return a point at the corner that we did find.
1657     if (foundLeading != foundTrailing) {
1658         if (foundLeading)
1659             foundTrailing = foundLeading;
1660         else
1661             foundLeading = foundTrailing;
1662     }
1663
1664     FloatPoint upperLeft = leading;
1665     FloatPoint lowerRight = trailing;
1666
1667     // Vertical writing modes might mean the leading point is not in the top left
1668     if (!isInline() || isReplaced()) {
1669         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1670         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1671     } // Otherwise, it's not obvious what to do.
1672
1673     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1674 }
1675
1676 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1677 {
1678     const RenderElement* current = this;
1679     do {
1680         if (current->isRenderBlock())
1681             return current;
1682         if (!current->isRenderInline() || current->isRubyText())
1683             return nullptr;
1684         
1685         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1686         if (styleToUse.textDecoration() & textDecoration)
1687             return current;
1688         current = current->parent();
1689     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1690
1691     return current;
1692 }
1693
1694 }