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