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