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