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