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