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