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