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