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