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