[RenderTreeBuilder] Move RenderElement addChild mutation logic 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::handleDynamicFloatPositionChange()
906 {
907     // We have gone from not affecting the inline status of the parent flow to suddenly
908     // having an impact.  See if there is a mismatch between the parent flow's
909     // childrenInline() state and our state.
910     setInline(style().isDisplayInlineType());
911     if (isInline() != parent()->childrenInline()) {
912         if (!isInline())
913             downcast<RenderBoxModelObject>(*parent()).childBecameNonInline(*this);
914         else {
915             // An anonymous block must be made to wrap this inline.
916             auto newBlock = downcast<RenderBlock>(*parent()).createAnonymousBlock();
917             auto& block = *newBlock;
918             parent()->insertChildInternal(WTFMove(newBlock), this);
919             auto thisToMove = parent()->takeChildInternal(*this);
920             block.insertChildInternal(WTFMove(thisToMove), nullptr);
921         }
922     }
923 }
924
925 void RenderElement::removeAnonymousWrappersForInlinesIfNecessary()
926 {
927     // FIXME: Move to RenderBlock.
928     if (!is<RenderBlock>(*this))
929         return;
930     RenderBlock& thisBlock = downcast<RenderBlock>(*this);
931     if (!thisBlock.canDropAnonymousBlockChild())
932         return;
933
934     // We have changed to floated or out-of-flow positioning so maybe all our parent's
935     // children can be inline now. Bail if there are any block children left on the line,
936     // otherwise we can proceed to stripping solitary anonymous wrappers from the inlines.
937     // FIXME: We should also handle split inlines here - we exclude them at the moment by returning
938     // if we find a continuation.
939     RenderObject* current = firstChild();
940     while (current && ((current->isAnonymousBlock() && !downcast<RenderBlock>(*current).isContinuation()) || current->style().isFloating() || current->style().hasOutOfFlowPosition()))
941         current = current->nextSibling();
942
943     if (current)
944         return;
945
946     RenderObject* next;
947     for (current = firstChild(); current; current = next) {
948         next = current->nextSibling();
949         if (current->isAnonymousBlock())
950             thisBlock.dropAnonymousBoxChild(downcast<RenderBlock>(*current));
951     }
952 }
953
954 #if !PLATFORM(IOS)
955 static bool areNonIdenticalCursorListsEqual(const RenderStyle* a, const RenderStyle* b)
956 {
957     ASSERT(a->cursors() != b->cursors());
958     return a->cursors() && b->cursors() && *a->cursors() == *b->cursors();
959 }
960
961 static inline bool areCursorsEqual(const RenderStyle* a, const RenderStyle* b)
962 {
963     return a->cursor() == b->cursor() && (a->cursors() == b->cursors() || areNonIdenticalCursorListsEqual(a, b));
964 }
965 #endif
966
967 void RenderElement::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
968 {
969     updateFillImages(oldStyle ? &oldStyle->backgroundLayers() : nullptr, m_style.backgroundLayers());
970     updateFillImages(oldStyle ? &oldStyle->maskLayers() : nullptr, m_style.maskLayers());
971     updateImage(oldStyle ? oldStyle->borderImage().image() : nullptr, m_style.borderImage().image());
972     updateImage(oldStyle ? oldStyle->maskBoxImage().image() : nullptr, m_style.maskBoxImage().image());
973     updateShapeImage(oldStyle ? oldStyle->shapeOutside() : nullptr, m_style.shapeOutside());
974
975     if (s_affectsParentBlock)
976         handleDynamicFloatPositionChange();
977
978     if (s_noLongerAffectsParentBlock)
979         parent()->removeAnonymousWrappersForInlinesIfNecessary();
980
981     SVGRenderSupport::styleChanged(*this, oldStyle);
982
983     if (!m_parent)
984         return;
985     
986     if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
987         RenderCounter::rendererStyleChanged(*this, oldStyle, &m_style);
988
989         // If the object already needs layout, then setNeedsLayout won't do
990         // any work. But if the containing block has changed, then we may need
991         // to mark the new containing blocks for layout. The change that can
992         // directly affect the containing block of this object is a change to
993         // the position style.
994         if (needsLayout() && oldStyle->position() != m_style.position())
995             markContainingBlocksForLayout();
996
997         if (diff == StyleDifferenceLayout)
998             setNeedsLayoutAndPrefWidthsRecalc();
999         else
1000             setNeedsSimplifiedNormalFlowLayout();
1001     } else if (diff == StyleDifferenceSimplifiedLayoutAndPositionedMovement) {
1002         setNeedsPositionedMovementLayout(oldStyle);
1003         setNeedsSimplifiedNormalFlowLayout();
1004     } else if (diff == StyleDifferenceLayoutPositionedMovementOnly)
1005         setNeedsPositionedMovementLayout(oldStyle);
1006
1007     // Don't check for repaint here; we need to wait until the layer has been
1008     // updated by subclasses before we know if we have to repaint (in setStyle()).
1009
1010 #if !PLATFORM(IOS)
1011     if (oldStyle && !areCursorsEqual(oldStyle, &style()))
1012         frame().eventHandler().scheduleCursorUpdate();
1013 #endif
1014     bool hadOutlineAuto = oldStyle && oldStyle->outlineStyleIsAuto();
1015     bool hasOutlineAuto = outlineStyleForRepaint().outlineStyleIsAuto();
1016     if (hasOutlineAuto != hadOutlineAuto) {
1017         updateOutlineAutoAncestor(hasOutlineAuto);
1018         issueRepaintForOutlineAuto(hasOutlineAuto ? outlineStyleForRepaint().outlineSize() : oldStyle->outlineSize());
1019     }
1020 }
1021
1022 void RenderElement::insertedIntoTree()
1023 {
1024     // Keep our layer hierarchy updated. Optimize for the common case where we don't have any children
1025     // and don't have a layer attached to ourselves.
1026     RenderLayer* layer = nullptr;
1027     if (firstChild() || hasLayer()) {
1028         layer = parent()->enclosingLayer();
1029         addLayers(layer);
1030     }
1031
1032     // If |this| is visible but this object was not, tell the layer it has some visible content
1033     // that needs to be drawn and layer visibility optimization can't be used
1034     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1035         if (!layer)
1036             layer = parent()->enclosingLayer();
1037         if (layer)
1038             layer->setHasVisibleContent();
1039     }
1040
1041     RenderObject::insertedIntoTree();
1042 }
1043
1044 void RenderElement::willBeRemovedFromTree()
1045 {
1046     // If we remove a visible child from an invisible parent, we don't know the layer visibility any more.
1047     RenderLayer* layer = nullptr;
1048     if (parent()->style().visibility() != VISIBLE && style().visibility() == VISIBLE && !hasLayer()) {
1049         if ((layer = parent()->enclosingLayer()))
1050             layer->dirtyVisibleContentStatus();
1051     }
1052     // Keep our layer hierarchy updated.
1053     if (firstChild() || hasLayer()) {
1054         if (!layer)
1055             layer = parent()->enclosingLayer();
1056         removeLayers(layer);
1057     }
1058
1059     if (isOutOfFlowPositioned() && parent()->childrenInline())
1060         parent()->dirtyLinesFromChangedChild(*this);
1061
1062     RenderObject::willBeRemovedFromTree();
1063 }
1064
1065 inline void RenderElement::clearSubtreeLayoutRootIfNeeded() const
1066 {
1067     if (renderTreeBeingDestroyed())
1068         return;
1069
1070     if (view().frameView().layoutContext().subtreeLayoutRoot() != this)
1071         return;
1072
1073     // Normally when a renderer is detached from the tree, the appropriate dirty bits get set
1074     // which ensures that this renderer is no longer the layout root.
1075     ASSERT_NOT_REACHED();
1076     
1077     // This indicates a failure to layout the child, which is why
1078     // the layout root is still set to |this|. Make sure to clear it
1079     // since we are getting destroyed.
1080     view().frameView().layoutContext().clearSubtreeLayoutRoot();
1081 }
1082
1083 void RenderElement::willBeDestroyed()
1084 {
1085     if (m_style.hasFixedBackgroundImage() && !settings().fixedBackgroundsPaintRelativeToDocument())
1086         view().frameView().removeSlowRepaintObject(*this);
1087
1088     unregisterForVisibleInViewportCallback();
1089
1090     if (hasCounterNodeMap())
1091         RenderCounter::destroyCounterNodes(*this);
1092
1093     RenderObject::willBeDestroyed();
1094
1095     clearSubtreeLayoutRootIfNeeded();
1096
1097     if (hasInitializedStyle()) {
1098         for (auto* bgLayer = &m_style.backgroundLayers(); bgLayer; bgLayer = bgLayer->next()) {
1099             if (auto* backgroundImage = bgLayer->image())
1100                 backgroundImage->removeClient(this);
1101         }
1102         for (auto* maskLayer = &m_style.maskLayers(); maskLayer; maskLayer = maskLayer->next()) {
1103             if (auto* maskImage = maskLayer->image())
1104                 maskImage->removeClient(this);
1105         }
1106         if (auto* borderImage = m_style.borderImage().image())
1107             borderImage->removeClient(this);
1108         if (auto* maskBoxImage = m_style.maskBoxImage().image())
1109             maskBoxImage->removeClient(this);
1110         if (auto shapeValue = m_style.shapeOutside()) {
1111             if (auto shapeImage = shapeValue->image())
1112                 shapeImage->removeClient(this);
1113         }
1114     }
1115     if (m_hasPausedImageAnimations)
1116         view().removeRendererWithPausedImageAnimations(*this);
1117 }
1118
1119 void RenderElement::setNeedsPositionedMovementLayout(const RenderStyle* oldStyle)
1120 {
1121     ASSERT(!isSetNeedsLayoutForbidden());
1122     if (needsPositionedMovementLayout())
1123         return;
1124     setNeedsPositionedMovementLayoutBit(true);
1125     markContainingBlocksForLayout();
1126     if (hasLayer()) {
1127         if (oldStyle && style().diffRequiresLayerRepaint(*oldStyle, downcast<RenderLayerModelObject>(*this).layer()->isComposited()))
1128             setLayerNeedsFullRepaint();
1129         else
1130             setLayerNeedsFullRepaintForPositionedMovementLayout();
1131     }
1132 }
1133
1134 void RenderElement::clearChildNeedsLayout()
1135 {
1136     setNormalChildNeedsLayoutBit(false);
1137     setPosChildNeedsLayoutBit(false);
1138     setNeedsSimplifiedNormalFlowLayoutBit(false);
1139     setNormalChildNeedsLayoutBit(false);
1140     setNeedsPositionedMovementLayoutBit(false);
1141 }
1142
1143 void RenderElement::setNeedsSimplifiedNormalFlowLayout()
1144 {
1145     ASSERT(!isSetNeedsLayoutForbidden());
1146     if (needsSimplifiedNormalFlowLayout())
1147         return;
1148     setNeedsSimplifiedNormalFlowLayoutBit(true);
1149     markContainingBlocksForLayout();
1150     if (hasLayer())
1151         setLayerNeedsFullRepaint();
1152 }
1153
1154 RenderElement* RenderElement::hoverAncestor() const
1155 {
1156     return parent();
1157 }
1158
1159 static inline void paintPhase(RenderElement& element, PaintPhase phase, PaintInfo& paintInfo, const LayoutPoint& childPoint)
1160 {
1161     paintInfo.phase = phase;
1162     element.paint(paintInfo, childPoint);
1163 }
1164
1165 void RenderElement::paintAsInlineBlock(PaintInfo& paintInfo, const LayoutPoint& childPoint)
1166 {
1167     // Paint all phases atomically, as though the element established its own stacking context.
1168     // (See Appendix E.2, section 6.4 on inline block/table/replaced elements in the CSS2.1 specification.)
1169     // This is also used by other elements (e.g. flex items and grid items).
1170     PaintPhase paintPhaseToUse = isExcludedAndPlacedInBorder() ? paintInfo.phase : PaintPhaseForeground;
1171     if (paintInfo.phase == PaintPhaseSelection)
1172         paint(paintInfo, childPoint);
1173     else if (paintInfo.phase == paintPhaseToUse) {
1174         paintPhase(*this, PaintPhaseBlockBackground, paintInfo, childPoint);
1175         paintPhase(*this, PaintPhaseChildBlockBackgrounds, paintInfo, childPoint);
1176         paintPhase(*this, PaintPhaseFloat, paintInfo, childPoint);
1177         paintPhase(*this, PaintPhaseForeground, paintInfo, childPoint);
1178         paintPhase(*this, PaintPhaseOutline, paintInfo, childPoint);
1179
1180         // Reset |paintInfo| to the original phase.
1181         paintInfo.phase = paintPhaseToUse;
1182     }
1183 }
1184
1185 void RenderElement::layout()
1186 {
1187     StackStats::LayoutCheckPoint layoutCheckPoint;
1188     ASSERT(needsLayout());
1189     for (auto* child = firstChild(); child; child = child->nextSibling()) {
1190         if (child->needsLayout())
1191             downcast<RenderElement>(*child).layout();
1192         ASSERT(!child->needsLayout());
1193     }
1194     clearNeedsLayout();
1195 }
1196
1197 static bool mustRepaintFillLayers(const RenderElement& renderer, const FillLayer& layer)
1198 {
1199     // Nobody will use multiple layers without wanting fancy positioning.
1200     if (layer.next())
1201         return true;
1202
1203     // Make sure we have a valid image.
1204     auto* image = layer.image();
1205     if (!image || !image->canRender(&renderer, renderer.style().effectiveZoom()))
1206         return false;
1207
1208     if (!layer.xPosition().isZero() || !layer.yPosition().isZero())
1209         return true;
1210
1211     auto sizeType = layer.sizeType();
1212
1213     if (sizeType == Contain || sizeType == Cover)
1214         return true;
1215
1216     if (sizeType == SizeLength) {
1217         auto size = layer.sizeLength();
1218         if (size.width.isPercentOrCalculated() || size.height.isPercentOrCalculated())
1219             return true;
1220         // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for 'contain'.
1221         if ((size.width.isAuto() || size.height.isAuto()) && image->isGeneratedImage())
1222             return true;
1223     } else if (image->usesImageContainerSize())
1224         return true;
1225
1226     return false;
1227 }
1228
1229 static bool mustRepaintBackgroundOrBorder(const RenderElement& renderer)
1230 {
1231     if (renderer.hasMask() && mustRepaintFillLayers(renderer, renderer.style().maskLayers()))
1232         return true;
1233
1234     // If we don't have a background/border/mask, then nothing to do.
1235     if (!renderer.hasVisibleBoxDecorations())
1236         return false;
1237
1238     if (mustRepaintFillLayers(renderer, renderer.style().backgroundLayers()))
1239         return true;
1240
1241     // Our fill layers are ok. Let's check border.
1242     if (renderer.style().hasBorder() && renderer.borderImageIsLoadedAndCanBeRendered())
1243         return true;
1244
1245     return false;
1246 }
1247
1248 bool RenderElement::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
1249 {
1250     if (view().printing())
1251         return false; // Don't repaint if we're printing.
1252
1253     // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1254     // ASSERT(!newBoundsPtr || *newBoundsPtr == clippedOverflowRectForRepaint(repaintContainer));
1255     LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
1256     LayoutRect newOutlineBox;
1257
1258     bool fullRepaint = selfNeedsLayout();
1259     // Presumably a background or a border exists if border-fit:lines was specified.
1260     if (!fullRepaint && style().borderFit() == BorderFitLines)
1261         fullRepaint = true;
1262     if (!fullRepaint) {
1263         // This ASSERT fails due to animations. See https://bugs.webkit.org/show_bug.cgi?id=37048
1264         // ASSERT(!newOutlineBoxRectPtr || *newOutlineBoxRectPtr == outlineBoundsForRepaint(repaintContainer));
1265         newOutlineBox = newOutlineBoxRectPtr ? *newOutlineBoxRectPtr : outlineBoundsForRepaint(repaintContainer);
1266         fullRepaint = (newOutlineBox.location() != oldOutlineBox.location() || (mustRepaintBackgroundOrBorder(*this) && (newBounds != oldBounds || newOutlineBox != oldOutlineBox)));
1267     }
1268
1269     if (!repaintContainer)
1270         repaintContainer = &view();
1271
1272     if (fullRepaint) {
1273         repaintUsingContainer(repaintContainer, oldBounds);
1274         if (newBounds != oldBounds)
1275             repaintUsingContainer(repaintContainer, newBounds);
1276         return true;
1277     }
1278
1279     if (newBounds == oldBounds && newOutlineBox == oldOutlineBox)
1280         return false;
1281
1282     LayoutUnit deltaLeft = newBounds.x() - oldBounds.x();
1283     if (deltaLeft > 0)
1284         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), deltaLeft, oldBounds.height()));
1285     else if (deltaLeft < 0)
1286         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), -deltaLeft, newBounds.height()));
1287
1288     LayoutUnit deltaRight = newBounds.maxX() - oldBounds.maxX();
1289     if (deltaRight > 0)
1290         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.maxX(), newBounds.y(), deltaRight, newBounds.height()));
1291     else if (deltaRight < 0)
1292         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.maxX(), oldBounds.y(), -deltaRight, oldBounds.height()));
1293
1294     LayoutUnit deltaTop = newBounds.y() - oldBounds.y();
1295     if (deltaTop > 0)
1296         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), oldBounds.y(), oldBounds.width(), deltaTop));
1297     else if (deltaTop < 0)
1298         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), newBounds.y(), newBounds.width(), -deltaTop));
1299
1300     LayoutUnit deltaBottom = newBounds.maxY() - oldBounds.maxY();
1301     if (deltaBottom > 0)
1302         repaintUsingContainer(repaintContainer, LayoutRect(newBounds.x(), oldBounds.maxY(), newBounds.width(), deltaBottom));
1303     else if (deltaBottom < 0)
1304         repaintUsingContainer(repaintContainer, LayoutRect(oldBounds.x(), newBounds.maxY(), oldBounds.width(), -deltaBottom));
1305
1306     if (newOutlineBox == oldOutlineBox)
1307         return false;
1308
1309     // We didn't move, but we did change size. Invalidate the delta, which will consist of possibly
1310     // two rectangles (but typically only one).
1311     const RenderStyle& outlineStyle = outlineStyleForRepaint();
1312     LayoutUnit outlineWidth = outlineStyle.outlineSize();
1313     LayoutBoxExtent insetShadowExtent = style().getBoxShadowInsetExtent();
1314     LayoutUnit width = absoluteValue(newOutlineBox.width() - oldOutlineBox.width());
1315     if (width) {
1316         LayoutUnit shadowLeft;
1317         LayoutUnit shadowRight;
1318         style().getBoxShadowHorizontalExtent(shadowLeft, shadowRight);
1319         LayoutUnit borderRight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderRight() : LayoutUnit::fromPixel(0);
1320         LayoutUnit boxWidth = is<RenderBox>(*this) ? downcast<RenderBox>(*this).width() : LayoutUnit();
1321         LayoutUnit minInsetRightShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.right(), std::min(newBounds.width(), oldBounds.width()));
1322         LayoutUnit borderWidth = std::max(borderRight, std::max(valueForLength(style().borderTopRightRadius().width, boxWidth), valueForLength(style().borderBottomRightRadius().width, boxWidth)));
1323         LayoutUnit decorationsWidth = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderWidth + minInsetRightShadowExtent) + std::max(outlineWidth, shadowRight);
1324         LayoutRect rightRect(newOutlineBox.x() + std::min(newOutlineBox.width(), oldOutlineBox.width()) - decorationsWidth,
1325             newOutlineBox.y(),
1326             width + decorationsWidth,
1327             std::max(newOutlineBox.height(), oldOutlineBox.height()));
1328         LayoutUnit right = std::min(newBounds.maxX(), oldBounds.maxX());
1329         if (rightRect.x() < right) {
1330             rightRect.setWidth(std::min(rightRect.width(), right - rightRect.x()));
1331             repaintUsingContainer(repaintContainer, rightRect);
1332         }
1333     }
1334     LayoutUnit height = absoluteValue(newOutlineBox.height() - oldOutlineBox.height());
1335     if (height) {
1336         LayoutUnit shadowTop;
1337         LayoutUnit shadowBottom;
1338         style().getBoxShadowVerticalExtent(shadowTop, shadowBottom);
1339         LayoutUnit borderBottom = is<RenderBox>(*this) ? downcast<RenderBox>(*this).borderBottom() : LayoutUnit::fromPixel(0);
1340         LayoutUnit boxHeight = is<RenderBox>(*this) ? downcast<RenderBox>(*this).height() : LayoutUnit();
1341         LayoutUnit minInsetBottomShadowExtent = std::min<LayoutUnit>(-insetShadowExtent.bottom(), std::min(newBounds.height(), oldBounds.height()));
1342         LayoutUnit borderHeight = std::max(borderBottom, std::max(valueForLength(style().borderBottomLeftRadius().height, boxHeight),
1343             valueForLength(style().borderBottomRightRadius().height, boxHeight)));
1344         LayoutUnit decorationsHeight = std::max<LayoutUnit>(-outlineStyle.outlineOffset(), borderHeight + minInsetBottomShadowExtent) + std::max(outlineWidth, shadowBottom);
1345         LayoutRect bottomRect(newOutlineBox.x(),
1346             std::min(newOutlineBox.maxY(), oldOutlineBox.maxY()) - decorationsHeight,
1347             std::max(newOutlineBox.width(), oldOutlineBox.width()),
1348             height + decorationsHeight);
1349         LayoutUnit bottom = std::min(newBounds.maxY(), oldBounds.maxY());
1350         if (bottomRect.y() < bottom) {
1351             bottomRect.setHeight(std::min(bottomRect.height(), bottom - bottomRect.y()));
1352             repaintUsingContainer(repaintContainer, bottomRect);
1353         }
1354     }
1355     return false;
1356 }
1357
1358 bool RenderElement::borderImageIsLoadedAndCanBeRendered() const
1359 {
1360     ASSERT(style().hasBorder());
1361
1362     StyleImage* borderImage = style().borderImage().image();
1363     return borderImage && borderImage->canRender(this, style().effectiveZoom()) && borderImage->isLoaded();
1364 }
1365
1366 bool RenderElement::mayCauseRepaintInsideViewport(const IntRect* optionalViewportRect) const
1367 {
1368     auto& frameView = view().frameView();
1369     if (frameView.isOffscreen())
1370         return false;
1371
1372     if (!hasOverflowClip()) {
1373         // FIXME: Computing the overflow rect is expensive if any descendant has
1374         // its own self-painting layer. As a result, we prefer to abort early in
1375         // this case and assume it may cause us to repaint inside the viewport.
1376         if (!hasLayer() || downcast<RenderLayerModelObject>(*this).layer()->firstChild())
1377             return true;
1378     }
1379
1380     // Compute viewport rect if it was not provided.
1381     const IntRect& visibleRect = optionalViewportRect ? *optionalViewportRect : frameView.windowToContents(frameView.windowClipRect());
1382     return visibleRect.intersects(enclosingIntRect(absoluteClippedOverflowRect()));
1383 }
1384
1385 bool RenderElement::isVisibleInDocumentRect(const IntRect& documentRect) const
1386 {
1387     if (document().activeDOMObjectsAreSuspended())
1388         return false;
1389     if (style().visibility() != VISIBLE)
1390         return false;
1391     if (view().frameView().isOffscreen())
1392         return false;
1393
1394     // Use background rect if we are the root or if we are the body and the background is propagated to the root.
1395     // FIXME: This is overly conservative as the image may not be a background-image, in which case it will not
1396     // be propagated to the root. At this point, we unfortunately don't have access to the image anymore so we
1397     // can no longer check if it is a background image.
1398     bool backgroundIsPaintedByRoot = isDocumentElementRenderer();
1399     if (isBody()) {
1400         auto& rootRenderer = *parent(); // If <body> has a renderer then <html> does too.
1401         ASSERT(rootRenderer.isDocumentElementRenderer());
1402         ASSERT(is<HTMLHtmlElement>(rootRenderer.element()));
1403         // FIXME: Should share body background propagation code.
1404         backgroundIsPaintedByRoot = !rootRenderer.hasBackground();
1405
1406     }
1407
1408     LayoutRect backgroundPaintingRect = backgroundIsPaintedByRoot ? view().backgroundRect() : absoluteClippedOverflowRect();
1409     if (!documentRect.intersects(enclosingIntRect(backgroundPaintingRect)))
1410         return false;
1411
1412     return true;
1413 }
1414
1415 void RenderElement::registerForVisibleInViewportCallback()
1416 {
1417     if (m_isRegisteredForVisibleInViewportCallback)
1418         return;
1419     m_isRegisteredForVisibleInViewportCallback = true;
1420
1421     view().registerForVisibleInViewportCallback(*this);
1422 }
1423
1424 void RenderElement::unregisterForVisibleInViewportCallback()
1425 {
1426     if (!m_isRegisteredForVisibleInViewportCallback)
1427         return;
1428     m_isRegisteredForVisibleInViewportCallback = false;
1429
1430     view().unregisterForVisibleInViewportCallback(*this);
1431 }
1432
1433 void RenderElement::setVisibleInViewportState(VisibleInViewportState state)
1434 {
1435     if (state == visibleInViewportState())
1436         return;
1437     m_visibleInViewportState = static_cast<unsigned>(state);
1438     visibleInViewportStateChanged();
1439 }
1440
1441 void RenderElement::visibleInViewportStateChanged()
1442 {
1443     ASSERT_NOT_REACHED();
1444 }
1445
1446 bool RenderElement::isVisibleInViewport() const
1447 {
1448     auto& frameView = view().frameView();
1449     auto visibleRect = frameView.windowToContents(frameView.windowClipRect());
1450     return isVisibleInDocumentRect(visibleRect);
1451 }
1452
1453 VisibleInViewportState RenderElement::imageFrameAvailable(CachedImage& image, ImageAnimatingState animatingState, const IntRect* changeRect)
1454 {
1455     bool isVisible = isVisibleInViewport();
1456
1457     if (!isVisible && animatingState == ImageAnimatingState::Yes)
1458         view().addRendererWithPausedImageAnimations(*this, image);
1459
1460     // Static images should repaint even if they are outside the viewport rectangle
1461     // because they should be inside the TileCoverageRect.
1462     if (isVisible || animatingState == ImageAnimatingState::No)
1463         imageChanged(&image, changeRect);
1464
1465     if (element() && image.image()->isBitmapImage())
1466         element()->dispatchWebKitImageReadyEventForTesting();
1467
1468     return isVisible ? VisibleInViewportState::Yes : VisibleInViewportState::No;
1469 }
1470
1471 void RenderElement::didRemoveCachedImageClient(CachedImage& cachedImage)
1472 {
1473     if (hasPausedImageAnimations())
1474         view().removeRendererWithPausedImageAnimations(*this, cachedImage);
1475 }
1476
1477 bool RenderElement::repaintForPausedImageAnimationsIfNeeded(const IntRect& visibleRect, CachedImage& cachedImage)
1478 {
1479     ASSERT(m_hasPausedImageAnimations);
1480     if (!isVisibleInDocumentRect(visibleRect))
1481         return false;
1482
1483     repaint();
1484
1485     if (auto* image = cachedImage.image())
1486         image->startAnimation();
1487
1488     // For directly-composited animated GIFs it does not suffice to call repaint() to resume animation. We need to mark the image as changed.
1489     if (is<RenderBoxModelObject>(*this))
1490         downcast<RenderBoxModelObject>(*this).contentChanged(ImageChanged);
1491
1492     return true;
1493 }
1494
1495 const RenderStyle* RenderElement::getCachedPseudoStyle(PseudoId pseudo, const RenderStyle* parentStyle) const
1496 {
1497     if (pseudo < FIRST_INTERNAL_PSEUDOID && !style().hasPseudoStyle(pseudo))
1498         return nullptr;
1499
1500     RenderStyle* cachedStyle = style().getCachedPseudoStyle(pseudo);
1501     if (cachedStyle)
1502         return cachedStyle;
1503
1504     std::unique_ptr<RenderStyle> result = getUncachedPseudoStyle(PseudoStyleRequest(pseudo), parentStyle);
1505     if (result)
1506         return const_cast<RenderStyle&>(m_style).addCachedPseudoStyle(WTFMove(result));
1507     return nullptr;
1508 }
1509
1510 std::unique_ptr<RenderStyle> RenderElement::getUncachedPseudoStyle(const PseudoStyleRequest& pseudoStyleRequest, const RenderStyle* parentStyle, const RenderStyle* ownStyle) const
1511 {
1512     if (pseudoStyleRequest.pseudoId < FIRST_INTERNAL_PSEUDOID && !ownStyle && !style().hasPseudoStyle(pseudoStyleRequest.pseudoId))
1513         return nullptr;
1514
1515     if (!parentStyle) {
1516         ASSERT(!ownStyle);
1517         parentStyle = &style();
1518     }
1519
1520     if (isAnonymous())
1521         return nullptr;
1522
1523     auto& styleResolver = element()->styleResolver();
1524
1525     std::unique_ptr<RenderStyle> style = styleResolver.pseudoStyleForElement(*element(), pseudoStyleRequest, *parentStyle);
1526
1527     if (style)
1528         Style::loadPendingResources(*style, document(), element());
1529
1530     return style;
1531 }
1532
1533 Color RenderElement::selectionColor(int colorProperty) const
1534 {
1535     // If the element is unselectable, or we are only painting the selection,
1536     // don't override the foreground color with the selection foreground color.
1537     if (style().userSelect() == SELECT_NONE
1538         || (view().frameView().paintBehavior() & (PaintBehaviorSelectionOnly | PaintBehaviorSelectionAndBackgroundsOnly)))
1539         return Color();
1540
1541     if (std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle()) {
1542         Color color = pseudoStyle->visitedDependentColor(colorProperty);
1543         if (!color.isValid())
1544             color = pseudoStyle->visitedDependentColor(CSSPropertyColor);
1545         return color;
1546     }
1547
1548     if (frame().selection().isFocusedAndActive())
1549         return theme().activeSelectionForegroundColor();
1550     return theme().inactiveSelectionForegroundColor();
1551 }
1552
1553 std::unique_ptr<RenderStyle> RenderElement::selectionPseudoStyle() const
1554 {
1555     if (isAnonymous())
1556         return nullptr;
1557
1558     if (ShadowRoot* root = element()->containingShadowRoot()) {
1559         if (root->mode() == ShadowRootMode::UserAgent) {
1560             if (Element* shadowHost = element()->shadowHost())
1561                 return shadowHost->renderer()->getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1562         }
1563     }
1564
1565     return getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
1566 }
1567
1568 Color RenderElement::selectionForegroundColor() const
1569 {
1570     return selectionColor(CSSPropertyWebkitTextFillColor);
1571 }
1572
1573 Color RenderElement::selectionEmphasisMarkColor() const
1574 {
1575     return selectionColor(CSSPropertyWebkitTextEmphasisColor);
1576 }
1577
1578 Color RenderElement::selectionBackgroundColor() const
1579 {
1580     if (style().userSelect() == SELECT_NONE)
1581         return Color();
1582
1583     if (frame().selection().shouldShowBlockCursor() && frame().selection().isCaret())
1584         return style().visitedDependentColor(CSSPropertyColor).blendWithWhite();
1585
1586     std::unique_ptr<RenderStyle> pseudoStyle = selectionPseudoStyle();
1587     if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
1588         return pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
1589
1590     if (frame().selection().isFocusedAndActive())
1591         return theme().activeSelectionBackgroundColor();
1592     return theme().inactiveSelectionBackgroundColor();
1593 }
1594
1595 bool RenderElement::getLeadingCorner(FloatPoint& point, bool& insideFixed) const
1596 {
1597     if (!isInline() || isReplaced()) {
1598         point = localToAbsolute(FloatPoint(), UseTransforms, &insideFixed);
1599         return true;
1600     }
1601
1602     // find the next text/image child, to get a position
1603     const RenderObject* o = this;
1604     while (o) {
1605         const RenderObject* p = o;
1606         if (RenderObject* child = o->firstChildSlow())
1607             o = child;
1608         else if (o->nextSibling())
1609             o = o->nextSibling();
1610         else {
1611             RenderObject* next = 0;
1612             while (!next && o->parent()) {
1613                 o = o->parent();
1614                 next = o->nextSibling();
1615             }
1616             o = next;
1617
1618             if (!o)
1619                 break;
1620         }
1621         ASSERT(o);
1622
1623         if (!o->isInline() || o->isReplaced()) {
1624             point = o->localToAbsolute(FloatPoint(), UseTransforms, &insideFixed);
1625             return true;
1626         }
1627
1628         if (p->node() && p->node() == element() && is<RenderText>(*o) && !downcast<RenderText>(*o).firstTextBox()) {
1629             // do nothing - skip unrendered whitespace that is a child or next sibling of the anchor
1630         } else if (is<RenderText>(*o) || o->isReplaced()) {
1631             point = FloatPoint();
1632             if (is<RenderText>(*o) && downcast<RenderText>(*o).firstTextBox())
1633                 point.move(downcast<RenderText>(*o).linesBoundingBox().x(), downcast<RenderText>(*o).topOfFirstText());
1634             else if (is<RenderBox>(*o))
1635                 point.moveBy(downcast<RenderBox>(*o).location());
1636             point = o->container()->localToAbsolute(point, UseTransforms, &insideFixed);
1637             return true;
1638         }
1639     }
1640     
1641     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
1642     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
1643     if (!o && document().view()) {
1644         point = FloatPoint(0, document().view()->contentsHeight());
1645         return true;
1646     }
1647     return false;
1648 }
1649
1650 bool RenderElement::getTrailingCorner(FloatPoint& point, bool& insideFixed) const
1651 {
1652     if (!isInline() || isReplaced()) {
1653         point = localToAbsolute(LayoutPoint(downcast<RenderBox>(*this).size()), UseTransforms, &insideFixed);
1654         return true;
1655     }
1656
1657     // find the last text/image child, to get a position
1658     const RenderObject* o = this;
1659     while (o) {
1660         if (RenderObject* child = o->lastChildSlow())
1661             o = child;
1662         else if (o->previousSibling())
1663             o = o->previousSibling();
1664         else {
1665             RenderObject* prev = 0;
1666             while (!prev) {
1667                 o = o->parent();
1668                 if (!o)
1669                     return false;
1670                 prev = o->previousSibling();
1671             }
1672             o = prev;
1673         }
1674         ASSERT(o);
1675         if (is<RenderText>(*o) || o->isReplaced()) {
1676             point = FloatPoint();
1677             if (is<RenderText>(*o)) {
1678                 LayoutRect linesBox = downcast<RenderText>(*o).linesBoundingBox();
1679                 if (!linesBox.maxX() && !linesBox.maxY())
1680                     continue;
1681                 point.moveBy(linesBox.maxXMaxYCorner());
1682             } else
1683                 point.moveBy(downcast<RenderBox>(*o).frameRect().maxXMaxYCorner());
1684             point = o->container()->localToAbsolute(point, UseTransforms, &insideFixed);
1685             return true;
1686         }
1687     }
1688     return true;
1689 }
1690
1691 LayoutRect RenderElement::absoluteAnchorRect(bool* insideFixed) const
1692 {
1693     FloatPoint leading, trailing;
1694     bool leadingInFixed = false;
1695     bool trailingInFixed = false;
1696     getLeadingCorner(leading, leadingInFixed);
1697     getTrailingCorner(trailing, trailingInFixed);
1698
1699     FloatPoint upperLeft = leading;
1700     FloatPoint lowerRight = trailing;
1701
1702     // Vertical writing modes might mean the leading point is not in the top left
1703     if (!isInline() || isReplaced()) {
1704         upperLeft = FloatPoint(std::min(leading.x(), trailing.x()), std::min(leading.y(), trailing.y()));
1705         lowerRight = FloatPoint(std::max(leading.x(), trailing.x()), std::max(leading.y(), trailing.y()));
1706     } // Otherwise, it's not obvious what to do.
1707
1708     if (insideFixed) {
1709         // For now, just look at the leading corner. Handling one inside fixed and one not would be tricky.
1710         *insideFixed = leadingInFixed;
1711     }
1712
1713     return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
1714 }
1715
1716 const RenderElement* RenderElement::enclosingRendererWithTextDecoration(TextDecoration textDecoration, bool firstLine) const
1717 {
1718     const RenderElement* current = this;
1719     do {
1720         if (current->isRenderBlock())
1721             return current;
1722         if (!current->isRenderInline() || current->isRubyText())
1723             return nullptr;
1724         
1725         const RenderStyle& styleToUse = firstLine ? current->firstLineStyle() : current->style();
1726         if (styleToUse.textDecoration() & textDecoration)
1727             return current;
1728         current = current->parent();
1729     } while (current && (!current->element() || (!is<HTMLAnchorElement>(*current->element()) && !current->element()->hasTagName(HTMLNames::fontTag))));
1730
1731     return current;
1732 }
1733
1734 void RenderElement::drawLineForBoxSide(GraphicsContext& graphicsContext, const FloatRect& rect, BoxSide side, Color color, EBorderStyle borderStyle, float adjacentWidth1, float adjacentWidth2, bool antialias) const
1735 {
1736     auto drawBorderRect = [&graphicsContext] (const FloatRect& rect)
1737     {
1738         if (rect.isEmpty())
1739             return;
1740         graphicsContext.drawRect(rect);
1741     };
1742
1743     auto drawLineFor = [this, &graphicsContext, color, antialias] (const FloatRect& rect, BoxSide side, EBorderStyle borderStyle, const FloatSize& adjacent)
1744     {
1745         if (rect.isEmpty())
1746             return;
1747         drawLineForBoxSide(graphicsContext, rect, side, color, borderStyle, adjacent.width(), adjacent.height(), antialias);
1748     };
1749
1750     float x1 = rect.x();
1751     float x2 = rect.maxX();
1752     float y1 = rect.y();
1753     float y2 = rect.maxY();
1754     float thickness;
1755     float length;
1756     if (side == BSTop || side == BSBottom) {
1757         thickness = y2 - y1;
1758         length = x2 - x1;
1759     } else {
1760         thickness = x2 - x1;
1761         length = y2 - y1;
1762     }
1763     // FIXME: We really would like this check to be an ASSERT as we don't want to draw empty borders. However
1764     // nothing guarantees that the following recursive calls to drawLineForBoxSide will have non-null dimensions.
1765     if (!thickness || !length)
1766         return;
1767
1768     float deviceScaleFactor = document().deviceScaleFactor();
1769     if (borderStyle == DOUBLE && (thickness * deviceScaleFactor) < 3)
1770         borderStyle = SOLID;
1771
1772     switch (borderStyle) {
1773     case BNONE:
1774     case BHIDDEN:
1775         return;
1776     case DOTTED:
1777     case DASHED: {
1778         bool wasAntialiased = graphicsContext.shouldAntialias();
1779         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1780         graphicsContext.setShouldAntialias(antialias);
1781         graphicsContext.setStrokeColor(color);
1782         graphicsContext.setStrokeThickness(thickness);
1783         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1784         graphicsContext.drawLine(roundPointToDevicePixels(LayoutPoint(x1, y1), deviceScaleFactor), roundPointToDevicePixels(LayoutPoint(x2, y2), deviceScaleFactor));
1785         graphicsContext.setShouldAntialias(wasAntialiased);
1786         graphicsContext.setStrokeStyle(oldStrokeStyle);
1787         break;
1788     }
1789     case DOUBLE: {
1790         float thirdOfThickness = ceilToDevicePixel(thickness / 3, deviceScaleFactor);
1791         ASSERT(thirdOfThickness);
1792
1793         if (!adjacentWidth1 && !adjacentWidth2) {
1794             StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1795             graphicsContext.setStrokeStyle(NoStroke);
1796             graphicsContext.setFillColor(color);
1797
1798             bool wasAntialiased = graphicsContext.shouldAntialias();
1799             graphicsContext.setShouldAntialias(antialias);
1800
1801             switch (side) {
1802             case BSTop:
1803             case BSBottom:
1804                 drawBorderRect(snapRectToDevicePixels(x1, y1, length, thirdOfThickness, deviceScaleFactor));
1805                 drawBorderRect(snapRectToDevicePixels(x1, y2 - thirdOfThickness, length, thirdOfThickness, deviceScaleFactor));
1806                 break;
1807             case BSLeft:
1808             case BSRight:
1809                 drawBorderRect(snapRectToDevicePixels(x1, y1, thirdOfThickness, length, deviceScaleFactor));
1810                 drawBorderRect(snapRectToDevicePixels(x2 - thirdOfThickness, y1, thirdOfThickness, length, deviceScaleFactor));
1811                 break;
1812             }
1813
1814             graphicsContext.setShouldAntialias(wasAntialiased);
1815             graphicsContext.setStrokeStyle(oldStrokeStyle);
1816         } else {
1817             float adjacent1BigThird = ceilToDevicePixel(adjacentWidth1 / 3, deviceScaleFactor);
1818             float adjacent2BigThird = ceilToDevicePixel(adjacentWidth2 / 3, deviceScaleFactor);
1819
1820             float offset1 = floorToDevicePixel(fabs(adjacentWidth1) * 2 / 3, deviceScaleFactor);
1821             float offset2 = floorToDevicePixel(fabs(adjacentWidth2) * 2 / 3, deviceScaleFactor);
1822
1823             float mitreOffset1 = adjacentWidth1 < 0 ? offset1 : 0;
1824             float mitreOffset2 = adjacentWidth1 > 0 ? offset1 : 0;
1825             float mitreOffset3 = adjacentWidth2 < 0 ? offset2 : 0;
1826             float mitreOffset4 = adjacentWidth2 > 0 ? offset2 : 0;
1827
1828             FloatRect paintBorderRect;
1829             switch (side) {
1830             case BSTop:
1831                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y1, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1832                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1833
1834                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y2 - thirdOfThickness, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1835                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1836                 break;
1837             case BSLeft:
1838                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1839                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1840
1841                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1842                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1843                 break;
1844             case BSBottom:
1845                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset2, y1, (x2 - mitreOffset4) - (x1 + mitreOffset2), thirdOfThickness), deviceScaleFactor);
1846                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1847
1848                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1 + mitreOffset1, y2 - thirdOfThickness, (x2 - mitreOffset3) - (x1 + mitreOffset1), thirdOfThickness), deviceScaleFactor);
1849                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1850                 break;
1851             case BSRight:
1852                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x1, y1 + mitreOffset2, thirdOfThickness, (y2 - mitreOffset4) - (y1 + mitreOffset2)), deviceScaleFactor);
1853                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1854
1855                 paintBorderRect = snapRectToDevicePixels(LayoutRect(x2 - thirdOfThickness, y1 + mitreOffset1, thirdOfThickness, (y2 - mitreOffset3) - (y1 + mitreOffset1)), deviceScaleFactor);
1856                 drawLineFor(paintBorderRect, side, SOLID, FloatSize(adjacent1BigThird, adjacent2BigThird));
1857                 break;
1858             default:
1859                 break;
1860             }
1861         }
1862         break;
1863     }
1864     case RIDGE:
1865     case GROOVE: {
1866         EBorderStyle s1;
1867         EBorderStyle s2;
1868         if (borderStyle == GROOVE) {
1869             s1 = INSET;
1870             s2 = OUTSET;
1871         } else {
1872             s1 = OUTSET;
1873             s2 = INSET;
1874         }
1875
1876         float adjacent1BigHalf = ceilToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1877         float adjacent2BigHalf = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1878
1879         float adjacent1SmallHalf = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1880         float adjacent2SmallHalf = floorToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1881
1882         float offset1 = 0;
1883         float offset2 = 0;
1884         float offset3 = 0;
1885         float offset4 = 0;
1886
1887         if (((side == BSTop || side == BSLeft) && adjacentWidth1 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 > 0))
1888             offset1 = floorToDevicePixel(adjacentWidth1 / 2, deviceScaleFactor);
1889
1890         if (((side == BSTop || side == BSLeft) && adjacentWidth2 < 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 > 0))
1891             offset2 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1892
1893         if (((side == BSTop || side == BSLeft) && adjacentWidth1 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth1 < 0))
1894             offset3 = floorToDevicePixel(fabs(adjacentWidth1) / 2, deviceScaleFactor);
1895
1896         if (((side == BSTop || side == BSLeft) && adjacentWidth2 > 0) || ((side == BSBottom || side == BSRight) && adjacentWidth2 < 0))
1897             offset4 = ceilToDevicePixel(adjacentWidth2 / 2, deviceScaleFactor);
1898
1899         float adjustedX = ceilToDevicePixel((x1 + x2) / 2, deviceScaleFactor);
1900         float adjustedY = ceilToDevicePixel((y1 + y2) / 2, deviceScaleFactor);
1901         // Quads can't use the default snapping rect functions.
1902         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1903         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1904         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1905         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1906
1907         switch (side) {
1908         case BSTop:
1909             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1910             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1911             break;
1912         case BSLeft:
1913             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s1, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1914             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s2, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1915             break;
1916         case BSBottom:
1917             drawLineFor(FloatRect(FloatPoint(x1 + offset1, y1), FloatPoint(x2 - offset2, adjustedY)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1918             drawLineFor(FloatRect(FloatPoint(x1 + offset3, adjustedY), FloatPoint(x2 - offset4, y2)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1919             break;
1920         case BSRight:
1921             drawLineFor(FloatRect(FloatPoint(x1, y1 + offset1), FloatPoint(adjustedX, y2 - offset2)), side, s2, FloatSize(adjacent1BigHalf, adjacent2BigHalf));
1922             drawLineFor(FloatRect(FloatPoint(adjustedX, y1 + offset3), FloatPoint(x2, y2 - offset4)), side, s1, FloatSize(adjacent1SmallHalf, adjacent2SmallHalf));
1923             break;
1924         }
1925         break;
1926     }
1927     case INSET:
1928     case OUTSET:
1929         calculateBorderStyleColor(borderStyle, side, color);
1930         FALLTHROUGH;
1931     case SOLID: {
1932         StrokeStyle oldStrokeStyle = graphicsContext.strokeStyle();
1933         ASSERT(x2 >= x1);
1934         ASSERT(y2 >= y1);
1935         if (!adjacentWidth1 && !adjacentWidth2) {
1936             graphicsContext.setStrokeStyle(NoStroke);
1937             graphicsContext.setFillColor(color);
1938             bool wasAntialiased = graphicsContext.shouldAntialias();
1939             graphicsContext.setShouldAntialias(antialias);
1940             drawBorderRect(snapRectToDevicePixels(x1, y1, x2 - x1, y2 - y1, deviceScaleFactor));
1941             graphicsContext.setShouldAntialias(wasAntialiased);
1942             graphicsContext.setStrokeStyle(oldStrokeStyle);
1943             return;
1944         }
1945
1946         // FIXME: These roundings should be replaced by ASSERT(device pixel positioned) when all the callers have transitioned to device pixels.
1947         x1 = roundToDevicePixel(x1, deviceScaleFactor);
1948         y1 = roundToDevicePixel(y1, deviceScaleFactor);
1949         x2 = roundToDevicePixel(x2, deviceScaleFactor);
1950         y2 = roundToDevicePixel(y2, deviceScaleFactor);
1951
1952         Vector<FloatPoint> quad;
1953         quad.reserveInitialCapacity(4);
1954         switch (side) {
1955         case BSTop:
1956             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y1 });
1957             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y2 });
1958             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y2 });
1959             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y1 });
1960             break;
1961         case BSBottom:
1962             quad.uncheckedAppend({ x1 + std::max<float>( adjacentWidth1, 0), y1 });
1963             quad.uncheckedAppend({ x1 + std::max<float>(-adjacentWidth1, 0), y2 });
1964             quad.uncheckedAppend({ x2 - std::max<float>(-adjacentWidth2, 0), y2 });
1965             quad.uncheckedAppend({ x2 - std::max<float>( adjacentWidth2, 0), y1 });
1966             break;
1967         case BSLeft:
1968             quad.uncheckedAppend({ x1, y1 + std::max<float>(-adjacentWidth1, 0) });
1969             quad.uncheckedAppend({ x1, y2 - std::max<float>(-adjacentWidth2, 0) });
1970             quad.uncheckedAppend({ x2, y2 - std::max<float>( adjacentWidth2, 0) });
1971             quad.uncheckedAppend({ x2, y1 + std::max<float>( adjacentWidth1, 0) });
1972             break;
1973         case BSRight:
1974             quad.uncheckedAppend({ x1, y1 + std::max<float>( adjacentWidth1, 0) });
1975             quad.uncheckedAppend({ x1, y2 - std::max<float>( adjacentWidth2, 0) });
1976             quad.uncheckedAppend({ x2, y2 - std::max<float>(-adjacentWidth2, 0) });
1977             quad.uncheckedAppend({ x2, y1 + std::max<float>(-adjacentWidth1, 0) });
1978             break;
1979         }
1980
1981         graphicsContext.setStrokeStyle(NoStroke);
1982         graphicsContext.setFillColor(color);
1983         bool wasAntialiased = graphicsContext.shouldAntialias();
1984         graphicsContext.setShouldAntialias(antialias);
1985         graphicsContext.fillPath(Path::polygonPathFromPoints(quad));
1986         graphicsContext.setShouldAntialias(wasAntialiased);
1987
1988         graphicsContext.setStrokeStyle(oldStrokeStyle);
1989         break;
1990     }
1991     }
1992 }
1993
1994 void RenderElement::paintFocusRing(PaintInfo& paintInfo, const RenderStyle& style, const Vector<LayoutRect>& focusRingRects)
1995 {
1996     ASSERT(style.outlineStyleIsAuto());
1997     float outlineOffset = style.outlineOffset();
1998     Vector<FloatRect> pixelSnappedFocusRingRects;
1999     float deviceScaleFactor = document().deviceScaleFactor();
2000     for (auto rect : focusRingRects) {
2001         rect.inflate(outlineOffset);
2002         pixelSnappedFocusRingRects.append(snapRectToDevicePixels(rect, deviceScaleFactor));
2003     }
2004 #if PLATFORM(MAC)
2005     bool needsRepaint;
2006     if (style.hasBorderRadius()) {
2007         Path path = PathUtilities::pathWithShrinkWrappedRectsForOutline(pixelSnappedFocusRingRects, style.border(), outlineOffset, style.direction(), style.writingMode(),
2008             document().deviceScaleFactor());
2009         if (path.isEmpty()) {
2010             for (auto rect : pixelSnappedFocusRingRects)
2011                 path.addRect(rect);
2012         }
2013         paintInfo.context().drawFocusRing(path, page().focusController().timeSinceFocusWasSet(), needsRepaint);
2014     } else
2015         paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, page().focusController().timeSinceFocusWasSet(), needsRepaint);
2016     if (needsRepaint)
2017         page().focusController().setFocusedElementNeedsRepaint();
2018 #else
2019     paintInfo.context().drawFocusRing(pixelSnappedFocusRingRects, style.outlineWidth(), style.outlineOffset(), style.visitedDependentColor(CSSPropertyOutlineColor));
2020 #endif
2021 }
2022
2023 void RenderElement::paintOutline(PaintInfo& paintInfo, const LayoutRect& paintRect)
2024 {
2025     GraphicsContext& graphicsContext = paintInfo.context();
2026     if (graphicsContext.paintingDisabled())
2027         return;
2028
2029     if (!hasOutline())
2030         return;
2031
2032     auto& styleToUse = style();
2033     float outlineWidth = floorToDevicePixel(styleToUse.outlineWidth(), document().deviceScaleFactor());
2034     float outlineOffset = floorToDevicePixel(styleToUse.outlineOffset(), document().deviceScaleFactor());
2035
2036     // Only paint the focus ring by hand if the theme isn't able to draw it.
2037     if (styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse)) {
2038         Vector<LayoutRect> focusRingRects;
2039         addFocusRingRects(focusRingRects, paintRect.location(), paintInfo.paintContainer);
2040         paintFocusRing(paintInfo, styleToUse, focusRingRects);
2041     }
2042
2043     if (hasOutlineAnnotation() && !styleToUse.outlineStyleIsAuto() && !theme().supportsFocusRing(styleToUse))
2044         addPDFURLRect(paintInfo, paintRect.location());
2045
2046     if (styleToUse.outlineStyleIsAuto() || styleToUse.outlineStyle() == BNONE)
2047         return;
2048
2049     FloatRect outer = paintRect;
2050     outer.inflate(outlineOffset + outlineWidth);
2051     FloatRect inner = outer;
2052     inner.inflate(-outlineWidth);
2053
2054     // FIXME: This prevents outlines from painting inside the object. See bug 12042
2055     if (outer.isEmpty())
2056         return;
2057
2058     EBorderStyle outlineStyle = styleToUse.outlineStyle();
2059     Color outlineColor = styleToUse.visitedDependentColor(CSSPropertyOutlineColor);
2060
2061     bool useTransparencyLayer = !outlineColor.isOpaque();
2062     if (useTransparencyLayer) {
2063         if (outlineStyle == SOLID) {
2064             Path path;
2065             path.addRect(outer);
2066             path.addRect(inner);
2067             graphicsContext.setFillRule(RULE_EVENODD);
2068             graphicsContext.setFillColor(outlineColor);
2069             graphicsContext.fillPath(path);
2070             return;
2071         }
2072         graphicsContext.beginTransparencyLayer(outlineColor.alphaAsFloat());
2073         outlineColor = outlineColor.opaqueColor();
2074     }
2075
2076     float leftOuter = outer.x();
2077     float leftInner = inner.x();
2078     float rightOuter = outer.maxX();
2079     float rightInner = std::min(inner.maxX(), rightOuter);
2080     float topOuter = outer.y();
2081     float topInner = inner.y();
2082     float bottomOuter = outer.maxY();
2083     float bottomInner = std::min(inner.maxY(), bottomOuter);
2084
2085     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(leftInner, bottomOuter)), BSLeft, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2086     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, topOuter), FloatPoint(rightOuter, topInner)), BSTop, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2087     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(rightInner, topOuter), FloatPoint(rightOuter, bottomOuter)), BSRight, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2088     drawLineForBoxSide(graphicsContext, FloatRect(FloatPoint(leftOuter, bottomInner), FloatPoint(rightOuter, bottomOuter)), BSBottom, outlineColor, outlineStyle, outlineWidth, outlineWidth);
2089
2090     if (useTransparencyLayer)
2091         graphicsContext.endTransparencyLayer();
2092 }
2093
2094 void RenderElement::issueRepaintForOutlineAuto(float outlineSize)
2095 {
2096     LayoutRect repaintRect;
2097     Vector<LayoutRect> focusRingRects;
2098     addFocusRingRects(focusRingRects, LayoutPoint(), containerForRepaint());
2099     for (auto rect : focusRingRects) {
2100         rect.inflate(outlineSize);
2101         repaintRect.unite(rect);
2102     }
2103     repaintRectangle(repaintRect);
2104 }
2105
2106 void RenderElement::updateOutlineAutoAncestor(bool hasOutlineAuto)
2107 {
2108     for (auto& child : childrenOfType<RenderObject>(*this)) {
2109         if (hasOutlineAuto == child.hasOutlineAutoAncestor())
2110             continue;
2111         child.setHasOutlineAutoAncestor(hasOutlineAuto);
2112         bool childHasOutlineAuto = child.outlineStyleForRepaint().outlineStyleIsAuto();
2113         if (childHasOutlineAuto)
2114             continue;
2115         if (!is<RenderElement>(child))
2116             continue;
2117         downcast<RenderElement>(child).updateOutlineAutoAncestor(hasOutlineAuto);
2118     }
2119     if (is<RenderBoxModelObject>(*this)) {
2120         if (auto* continuation = downcast<RenderBoxModelObject>(*this).continuation())
2121             continuation->updateOutlineAutoAncestor(hasOutlineAuto);
2122     }
2123 }
2124
2125 bool RenderElement::hasOutlineAnnotation() const
2126 {
2127     return element() && element()->isLink() && document().printing();
2128 }
2129
2130 bool RenderElement::hasSelfPaintingLayer() const
2131 {
2132     if (!hasLayer())
2133         return false;
2134     auto& layerModelObject = downcast<RenderLayerModelObject>(*this);
2135     return layerModelObject.hasSelfPaintingLayer();
2136 }
2137
2138 bool RenderElement::checkForRepaintDuringLayout() const
2139 {
2140     if (document().view()->layoutContext().needsFullRepaint() || !everHadLayout() || hasSelfPaintingLayer())
2141         return false;
2142     return !settings().repaintOutsideLayoutEnabled();
2143 }
2144
2145 RespectImageOrientationEnum RenderElement::shouldRespectImageOrientation() const
2146 {
2147 #if USE(CG) || USE(CAIRO)
2148     // This can only be enabled for ports which honor the orientation flag in their drawing code.
2149     if (document().isImageDocument())
2150         return RespectImageOrientation;
2151 #endif
2152     // Respect the image's orientation if it's being used as a full-page image or it's
2153     // an <img> and the setting to respect it everywhere is set.
2154     return settings().shouldRespectImageOrientation() && is<HTMLImageElement>(element()) ? RespectImageOrientation : DoNotRespectImageOrientation;
2155 }
2156
2157 void RenderElement::adjustFragmentedFlowStateOnContainingBlockChangeIfNeeded()
2158 {
2159     if (fragmentedFlowState() == NotInsideFragmentedFlow)
2160         return;
2161
2162     // Invalidate the containing block caches.
2163     if (is<RenderBlock>(*this))
2164         downcast<RenderBlock>(*this).resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants();
2165     
2166     // Adjust the flow tread state on the subtree.
2167     setFragmentedFlowState(RenderObject::computedFragmentedFlowState(*this));
2168     for (auto& descendant : descendantsOfType<RenderObject>(*this))
2169         descendant.setFragmentedFlowState(RenderObject::computedFragmentedFlowState(descendant));
2170 }
2171
2172 void RenderElement::removeFromRenderFragmentedFlow()
2173 {
2174     ASSERT(fragmentedFlowState() != NotInsideFragmentedFlow);
2175     // Sometimes we remove the element from the flow, but it's not destroyed at that time.
2176     // It's only until later when we actually destroy it and remove all the children from it.
2177     // Currently, that happens for firstLetter elements and list markers.
2178     // Pass in the flow thread so that we don't have to look it up for all the children.
2179     removeFromRenderFragmentedFlowIncludingDescendants(true);
2180 }
2181
2182 void RenderElement::removeFromRenderFragmentedFlowIncludingDescendants(bool shouldUpdateState)
2183 {
2184     // Once we reach another flow thread we don't need to update the flow thread state
2185     // but we have to continue cleanup the flow thread info.
2186     if (isRenderFragmentedFlow())
2187         shouldUpdateState = false;
2188
2189     for (auto& child : childrenOfType<RenderObject>(*this)) {
2190         if (is<RenderElement>(child)) {
2191             downcast<RenderElement>(child).removeFromRenderFragmentedFlowIncludingDescendants(shouldUpdateState);
2192             continue;
2193         }
2194         if (shouldUpdateState)
2195             child.setFragmentedFlowState(NotInsideFragmentedFlow);
2196     }
2197
2198     // We have to ask for our containing flow thread as it may be above the removed sub-tree.
2199     RenderFragmentedFlow* enclosingFragmentedFlow = this->enclosingFragmentedFlow();
2200     while (enclosingFragmentedFlow) {
2201         enclosingFragmentedFlow->removeFlowChildInfo(*this);
2202
2203         if (enclosingFragmentedFlow->fragmentedFlowState() == NotInsideFragmentedFlow)
2204             break;
2205         auto* parent = enclosingFragmentedFlow->parent();
2206         if (!parent)
2207             break;
2208         enclosingFragmentedFlow = parent->enclosingFragmentedFlow();
2209     }
2210     if (is<RenderBlock>(*this))
2211         downcast<RenderBlock>(*this).setCachedEnclosingFragmentedFlowNeedsUpdate();
2212
2213     if (shouldUpdateState)
2214         setFragmentedFlowState(NotInsideFragmentedFlow);
2215 }
2216
2217 void RenderElement::resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants(RenderFragmentedFlow* fragmentedFlow)
2218 {
2219     if (fragmentedFlow)
2220         fragmentedFlow->removeFlowChildInfo(*this);
2221
2222     for (auto& child : childrenOfType<RenderElement>(*this))
2223         child.resetEnclosingFragmentedFlowAndChildInfoIncludingDescendants(fragmentedFlow);
2224 }
2225
2226 #if ENABLE(TEXT_AUTOSIZING)
2227 static RenderObject::BlockContentHeightType includeNonFixedHeight(const RenderObject& renderer)
2228 {
2229     const RenderStyle& style = renderer.style();
2230     if (style.height().type() == Fixed) {
2231         if (is<RenderBlock>(renderer)) {
2232             // For fixed height styles, if the overflow size of the element spills out of the specified
2233             // height, assume we can apply text auto-sizing.
2234             if (style.overflowY() == OVISIBLE
2235                 && style.height().value() < downcast<RenderBlock>(renderer).layoutOverflowRect().maxY())
2236                 return RenderObject::OverflowHeight;
2237         }
2238         return RenderObject::FixedHeight;
2239     }
2240     return RenderObject::FlexibleHeight;
2241 }
2242
2243 void RenderElement::adjustComputedFontSizesOnBlocks(float size, float visibleWidth)
2244 {
2245     Document* document = view().frameView().frame().document();
2246     if (!document)
2247         return;
2248
2249     Vector<int> depthStack;
2250     int currentDepth = 0;
2251     int newFixedDepth = 0;
2252
2253     // We don't apply autosizing to nodes with fixed height normally.
2254     // But we apply it to nodes which are located deep enough
2255     // (nesting depth is greater than some const) inside of a parent block
2256     // which has fixed height but its content overflows intentionally.
2257     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2258         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2259             depthStack.remove(depthStack.size() - 1);
2260         if (newFixedDepth)
2261             depthStack.append(newFixedDepth);
2262
2263         int stackSize = depthStack.size();
2264         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2265             downcast<RenderBlockFlow>(*descendent).adjustComputedFontSizes(size, visibleWidth);
2266         newFixedDepth = 0;
2267     }
2268
2269     // Remove style from auto-sizing table that are no longer valid.
2270     document->textAutoSizing().updateRenderTree();
2271 }
2272
2273 void RenderElement::resetTextAutosizing()
2274 {
2275     Document* document = view().frameView().frame().document();
2276     if (!document)
2277         return;
2278
2279     LOG(TextAutosizing, "RenderElement::resetTextAutosizing()");
2280
2281     document->textAutoSizing().reset();
2282
2283     Vector<int> depthStack;
2284     int currentDepth = 0;
2285     int newFixedDepth = 0;
2286
2287     for (RenderObject* descendent = traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth); descendent; descendent = descendent->traverseNext(this, includeNonFixedHeight, currentDepth, newFixedDepth)) {
2288         while (depthStack.size() > 0 && currentDepth <= depthStack[depthStack.size() - 1])
2289             depthStack.remove(depthStack.size() - 1);
2290         if (newFixedDepth)
2291             depthStack.append(newFixedDepth);
2292
2293         int stackSize = depthStack.size();
2294         if (is<RenderBlockFlow>(*descendent) && !descendent->isListItem() && (!stackSize || currentDepth - depthStack[stackSize - 1] > TextAutoSizingFixedHeightDepth))
2295             downcast<RenderBlockFlow>(*descendent).resetComputedFontSize();
2296         newFixedDepth = 0;
2297     }
2298 }
2299 #endif // ENABLE(TEXT_AUTOSIZING)
2300
2301 }