1bec8f2f5777913d46cdf087e8ebcd9d80a03887
[WebKit-https.git] / Source / WebCore / rendering / RenderLayer.cpp
1 /*
2  * Copyright (C) 2006-2014 Apple Inc. All rights reserved.
3  *
4  * Portions are Copyright (C) 1998 Netscape Communications Corporation.
5  *
6  * Other contributors:
7  *   Robert O'Callahan <roc+@cs.cmu.edu>
8  *   David Baron <dbaron@fas.harvard.edu>
9  *   Christian Biesinger <cbiesinger@web.de>
10  *   Randall Jesup <rjesup@wgate.com>
11  *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
12  *   Josh Soref <timeless@mac.com>
13  *   Boris Zbarsky <bzbarsky@mit.edu>
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28  *
29  * Alternatively, the contents of this file may be used under the terms
30  * of either the Mozilla Public License Version 1.1, found at
31  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
32  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
33  * (the "GPL"), in which case the provisions of the MPL or the GPL are
34  * applicable instead of those above.  If you wish to allow use of your
35  * version of this file only under the terms of one of those two
36  * licenses (the MPL or the GPL) and not to allow others to use your
37  * version of this file under the LGPL, indicate your decision by
38  * deletingthe provisions above and replace them with the notice and
39  * other provisions required by the MPL or the GPL, as the case may be.
40  * If you do not delete the provisions above, a recipient may use your
41  * version of this file under any of the LGPL, the MPL or the GPL.
42  */
43
44 #include "config.h"
45 #include "RenderLayer.h"
46
47 #include "AnimationController.h"
48 #include "BoxShape.h"
49 #include "CSSPropertyNames.h"
50 #include "Chrome.h"
51 #include "Document.h"
52 #include "DocumentEventQueue.h"
53 #include "Element.h"
54 #include "EventHandler.h"
55 #include "FloatConversion.h"
56 #include "FloatPoint3D.h"
57 #include "FloatRect.h"
58 #include "FloatRoundedRect.h"
59 #include "FlowThreadController.h"
60 #include "FocusController.h"
61 #include "Frame.h"
62 #include "FrameLoader.h"
63 #include "FrameLoaderClient.h"
64 #include "FrameSelection.h"
65 #include "FrameTree.h"
66 #include "FrameView.h"
67 #include "Gradient.h"
68 #include "GraphicsContext.h"
69 #include "HTMLFrameElement.h"
70 #include "HTMLFrameOwnerElement.h"
71 #include "HTMLNames.h"
72 #include "HitTestingTransformState.h"
73 #include "HitTestRequest.h"
74 #include "HitTestResult.h"
75 #include "InspectorInstrumentation.h"
76 #include "OverflowEvent.h"
77 #include "OverlapTestRequestClient.h"
78 #include "Page.h"
79 #include "PlatformMouseEvent.h"
80 #include "RenderFlowThread.h"
81 #include "RenderGeometryMap.h"
82 #include "RenderInline.h"
83 #include "RenderIterator.h"
84 #include "RenderLayerBacking.h"
85 #include "RenderLayerCompositor.h"
86 #include "RenderMarquee.h"
87 #include "RenderMultiColumnFlowThread.h"
88 #include "RenderNamedFlowFragment.h"
89 #include "RenderNamedFlowThread.h"
90 #include "RenderRegion.h"
91 #include "RenderReplica.h"
92 #include "RenderSVGResourceClipper.h"
93 #include "RenderScrollbar.h"
94 #include "RenderScrollbarPart.h"
95 #include "RenderTableCell.h"
96 #include "RenderTableRow.h"
97 #include "RenderTheme.h"
98 #include "RenderTreeAsText.h"
99 #include "RenderView.h"
100 #include "SVGNames.h"
101 #include "ScaleTransformOperation.h"
102 #include "ScrollAnimator.h"
103 #include "Scrollbar.h"
104 #include "ScrollbarTheme.h"
105 #include "ScrollingCoordinator.h"
106 #include "Settings.h"
107 #include "ShadowRoot.h"
108 #include "SourceGraphic.h"
109 #include "StyleProperties.h"
110 #include "StyleResolver.h"
111 #include "TextStream.h"
112 #include "TransformationMatrix.h"
113 #include "TranslateTransformOperation.h"
114 #include <stdio.h>
115 #include <wtf/StdLibExtras.h>
116 #include <wtf/text/CString.h>
117
118 #if ENABLE(CSS_FILTERS)
119 #include "FEColorMatrix.h"
120 #include "FEMerge.h"
121 #include "FilterEffectRenderer.h"
122 #include "RenderLayerFilterInfo.h"
123 #endif
124
125 #define MIN_INTERSECT_FOR_REVEAL 32
126
127 namespace WebCore {
128
129 using namespace HTMLNames;
130
131 bool ClipRect::intersects(const HitTestLocation& hitTestLocation) const
132 {
133     return hitTestLocation.intersects(m_rect);
134 }
135
136 void makeMatrixRenderable(TransformationMatrix& matrix, bool has3DRendering)
137 {
138 #if !ENABLE(3D_RENDERING)
139     UNUSED_PARAM(has3DRendering);
140     matrix.makeAffine();
141 #else
142     if (!has3DRendering)
143         matrix.makeAffine();
144 #endif
145 }
146
147 RenderLayer::RenderLayer(RenderLayerModelObject& rendererLayerModelObject)
148     : m_inResizeMode(false)
149     , m_scrollDimensionsDirty(true)
150     , m_normalFlowListDirty(true)
151     , m_hasSelfPaintingLayerDescendant(false)
152     , m_hasSelfPaintingLayerDescendantDirty(false)
153     , m_hasOutOfFlowPositionedDescendant(false)
154     , m_hasOutOfFlowPositionedDescendantDirty(true)
155     , m_needsCompositedScrolling(false)
156     , m_descendantsAreContiguousInStackingOrder(false)
157     , m_isRootLayer(rendererLayerModelObject.isRenderView())
158     , m_usedTransparency(false)
159     , m_paintingInsideReflection(false)
160     , m_inOverflowRelayout(false)
161     , m_repaintStatus(NeedsNormalRepaint)
162     , m_visibleContentStatusDirty(true)
163     , m_hasVisibleContent(false)
164     , m_visibleDescendantStatusDirty(false)
165     , m_hasVisibleDescendant(false)
166     , m_3DTransformedDescendantStatusDirty(true)
167     , m_has3DTransformedDescendant(false)
168     , m_hasCompositingDescendant(false)
169     , m_hasTransformedAncestor(false)
170     , m_has3DTransformedAncestor(false)
171     , m_indirectCompositingReason(static_cast<unsigned>(IndirectCompositingReason::None))
172     , m_viewportConstrainedNotCompositedReason(NoNotCompositedReason)
173 #if PLATFORM(IOS)
174     , m_adjustForIOSCaretWhenScrolling(false)
175     , m_registeredAsTouchEventListenerForScrolling(false)
176     , m_inUserScroll(false)
177     , m_requiresScrollBoundsOriginUpdate(false)
178 #endif
179     , m_containsDirtyOverlayScrollbars(false)
180     , m_updatingMarqueePosition(false)
181 #if !ASSERT_DISABLED
182     , m_layerListMutationAllowed(true)
183 #endif
184 #if ENABLE(CSS_FILTERS)
185     , m_hasFilterInfo(false)
186 #endif
187 #if ENABLE(CSS_COMPOSITING)
188     , m_blendMode(BlendModeNormal)
189     , m_hasNotIsolatedCompositedBlendingDescendants(false)
190     , m_hasNotIsolatedBlendingDescendants(false)
191     , m_hasNotIsolatedBlendingDescendantsStatusDirty(false)
192 #endif
193     , m_renderer(rendererLayerModelObject)
194     , m_parent(nullptr)
195     , m_previous(nullptr)
196     , m_next(nullptr)
197     , m_first(nullptr)
198     , m_last(nullptr)
199     , m_staticInlinePosition(0)
200     , m_staticBlockPosition(0)
201     , m_enclosingPaginationLayer(nullptr)
202 {
203     m_isNormalFlowOnly = shouldBeNormalFlowOnly();
204     m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
205
206     // Non-stacking containers should have empty z-order lists. As this is already the case,
207     // there is no need to dirty / recompute these lists.
208     m_zOrderListsDirty = isStackingContainer();
209
210     ScrollableArea::setConstrainsScrollingToContentEdge(false);
211
212     if (!renderer().firstChild()) {
213         m_visibleContentStatusDirty = false;
214         m_hasVisibleContent = renderer().style().visibility() == VISIBLE;
215     }
216
217     if (Element* element = renderer().element()) {
218         // We save and restore only the scrollOffset as the other scroll values are recalculated.
219         m_scrollOffset = element->savedLayerScrollOffset();
220         if (!m_scrollOffset.isZero())
221             scrollAnimator()->setCurrentPosition(FloatPoint(m_scrollOffset.width(), m_scrollOffset.height()));
222         element->setSavedLayerScrollOffset(IntSize());
223     }
224 }
225
226 RenderLayer::~RenderLayer()
227 {
228     if (inResizeMode() && !renderer().documentBeingDestroyed())
229         renderer().frame().eventHandler().resizeLayerDestroyed();
230
231     renderer().view().frameView().removeScrollableArea(this);
232
233     if (!renderer().documentBeingDestroyed()) {
234 #if PLATFORM(IOS)
235         unregisterAsTouchEventListenerForScrolling();
236 #endif
237         if (Element* element = renderer().element())
238             element->setSavedLayerScrollOffset(m_scrollOffset);
239     }
240
241     destroyScrollbar(HorizontalScrollbar);
242     destroyScrollbar(VerticalScrollbar);
243
244     if (renderer().frame().page()) {
245         if (ScrollingCoordinator* scrollingCoordinator = renderer().frame().page()->scrollingCoordinator())
246             scrollingCoordinator->willDestroyScrollableArea(this);
247     }
248
249     if (m_reflection)
250         removeReflection();
251     
252 #if ENABLE(CSS_FILTERS)
253     FilterInfo::remove(*this);
254 #endif
255
256     // Child layers will be deleted by their corresponding render objects, so
257     // we don't need to delete them ourselves.
258
259     clearBacking(true);
260 }
261
262 String RenderLayer::name() const
263 {
264     StringBuilder name;
265     name.append(renderer().renderName());
266
267     if (Element* element = renderer().element()) {
268         name.append(' ');
269         name.append(element->tagName());
270
271         if (element->hasID()) {
272             name.appendLiteral(" id=\'");
273             name.append(element->getIdAttribute());
274             name.append('\'');
275         }
276
277         if (element->hasClass()) {
278             name.appendLiteral(" class=\'");
279             for (size_t i = 0; i < element->classNames().size(); ++i) {
280                 if (i > 0)
281                     name.append(' ');
282                 name.append(element->classNames()[i]);
283             }
284             name.append('\'');
285         }
286     }
287
288     if (isReflection())
289         name.appendLiteral(" (reflection)");
290
291     return name.toString();
292 }
293
294 RenderLayerCompositor& RenderLayer::compositor() const
295 {
296     return renderer().view().compositor();
297 }
298
299 void RenderLayer::contentChanged(ContentChangeType changeType)
300 {
301     // This can get called when video becomes accelerated, so the layers may change.
302     if ((changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged) && compositor().updateLayerCompositingState(*this))
303         compositor().setCompositingLayersNeedRebuild();
304
305     if (m_backing)
306         m_backing->contentChanged(changeType);
307 }
308
309 bool RenderLayer::canRender3DTransforms() const
310 {
311     return compositor().canRender3DTransforms();
312 }
313
314 #if ENABLE(CSS_FILTERS)
315
316 bool RenderLayer::paintsWithFilters() const
317 {
318     // FIXME: Eventually there will be cases where we paint with filters even without accelerated compositing,
319     // and this whole function won't be inside the #if below.
320
321     if (!renderer().hasFilter())
322         return false;
323         
324     if (!isComposited())
325         return true;
326
327     if (!m_backing || !m_backing->canCompositeFilters())
328         return true;
329
330     return false;
331 }
332
333 bool RenderLayer::requiresFullLayerImageForFilters() const 
334 {
335     if (!paintsWithFilters())
336         return false;
337     FilterEffectRenderer* renderer = filterRenderer();
338     return renderer && renderer->hasFilterThatMovesPixels();
339 }
340
341 FilterEffectRenderer* RenderLayer::filterRenderer() const
342 {
343     FilterInfo* filterInfo = FilterInfo::getIfExists(*this);
344     return filterInfo ? filterInfo->renderer() : 0;
345 }
346
347 #endif
348
349 void RenderLayer::updateLayerPositionsAfterLayout(const RenderLayer* rootLayer, UpdateLayerPositionsFlags flags)
350 {
351     RenderGeometryMap geometryMap(UseTransforms);
352     if (this != rootLayer)
353         geometryMap.pushMappingsToAncestor(parent(), 0);
354     updateLayerPositions(&geometryMap, flags);
355 }
356
357 void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLayerPositionsFlags flags)
358 {
359     updateLayerPosition(); // For relpositioned layers or non-positioned layers,
360                            // we need to keep in sync, since we may have shifted relative
361                            // to our parent layer.
362     if (geometryMap)
363         geometryMap->pushMappingsToAncestor(this, parent());
364
365     // Clear our cached clip rect information.
366     clearClipRects();
367     
368     if (hasOverflowControls()) {
369         LayoutSize offsetFromRoot;
370         if (geometryMap)
371             offsetFromRoot = LayoutSize(toFloatSize(geometryMap->absolutePoint(FloatPoint())));
372         else {
373             // FIXME: It looks suspicious to call convertToLayerCoords here
374             // as canUseConvertToLayerCoords may be true for an ancestor layer.
375             offsetFromRoot = offsetFromAncestor(root());
376         }
377         positionOverflowControls(roundedIntSize(offsetFromRoot));
378     }
379
380     updateDescendantDependentFlags();
381
382     if (flags & UpdatePagination)
383         updatePagination();
384     else
385         m_enclosingPaginationLayer = nullptr;
386     
387     if (m_hasVisibleContent) {
388         // FIXME: LayoutState does not work with RenderLayers as there is not a 1-to-1
389         // mapping between them and the RenderObjects. It would be neat to enable
390         // LayoutState outside the layout() phase and use it here.
391         ASSERT(!renderer().view().layoutStateEnabled());
392
393         RenderLayerModelObject* repaintContainer = renderer().containerForRepaint();
394         LayoutRect oldRepaintRect = m_repaintRect;
395         LayoutRect oldOutlineBox = m_outlineBox;
396         computeRepaintRects(repaintContainer, geometryMap);
397
398         // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
399         // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
400         if (flags & CheckForRepaint) {
401             if (!renderer().view().printing()) {
402                 bool didRepaint = false;
403                 if (m_repaintStatus & NeedsFullRepaint) {
404                     renderer().repaintUsingContainer(repaintContainer, oldRepaintRect);
405                     if (m_repaintRect != oldRepaintRect) {
406                         renderer().repaintUsingContainer(repaintContainer, m_repaintRect);
407                         didRepaint = true;
408                     }
409                 } else if (shouldRepaintAfterLayout()) {
410                     renderer().repaintAfterLayoutIfNeeded(repaintContainer, oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);
411                     didRepaint = true;
412                 }
413
414                 if (didRepaint && renderer().isRenderNamedFlowFragmentContainer()) {
415                     // If we just repainted a region, we must also repaint the flow thread since it is the one
416                     // doing the actual painting of the flowed content.
417                     RenderNamedFlowFragment* region = toRenderBlockFlow(&renderer())->renderNamedFlowFragment();
418                     if (region->isValid())
419                         region->flowThread()->layer()->repaintIncludingDescendants();
420                 }
421             }
422         }
423     } else
424         clearRepaintRects();
425
426     m_repaintStatus = NeedsNormalRepaint;
427     m_hasTransformedAncestor = flags & SeenTransformedLayer;
428     m_has3DTransformedAncestor = flags & Seen3DTransformedLayer;
429
430     // Go ahead and update the reflection's position and size.
431     if (m_reflection)
432         m_reflection->layout();
433
434     // Clear the IsCompositingUpdateRoot flag once we've found the first compositing layer in this update.
435     bool isUpdateRoot = (flags & IsCompositingUpdateRoot);
436     if (isComposited())
437         flags &= ~IsCompositingUpdateRoot;
438
439     if (renderer().isInFlowRenderFlowThread()) {
440         updatePagination();
441         flags |= UpdatePagination;
442     }
443
444     if (transform()) {
445         flags |= SeenTransformedLayer;
446         if (!transform()->isAffine())
447             flags |= Seen3DTransformedLayer;
448     }
449
450     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
451         child->updateLayerPositions(geometryMap, flags);
452
453     if ((flags & UpdateCompositingLayers) && isComposited()) {
454         RenderLayerBacking::UpdateAfterLayoutFlags updateFlags = RenderLayerBacking::CompositingChildrenOnly;
455         if (flags & NeedsFullRepaintInBacking)
456             updateFlags |= RenderLayerBacking::NeedsFullRepaint;
457         if (isUpdateRoot)
458             updateFlags |= RenderLayerBacking::IsUpdateRoot;
459         backing()->updateAfterLayout(updateFlags);
460     }
461         
462     // With all our children positioned, now update our marquee if we need to.
463     if (m_marquee) {
464         // FIXME: would like to use TemporaryChange<> but it doesn't work with bitfields.
465         bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
466         m_updatingMarqueePosition = true;
467         m_marquee->updateMarqueePosition();
468         m_updatingMarqueePosition = oldUpdatingMarqueePosition;
469     }
470
471     if (geometryMap)
472         geometryMap->popMappingsToAncestor(parent());
473 }
474
475 LayoutRect RenderLayer::repaintRectIncludingNonCompositingDescendants() const
476 {
477     LayoutRect repaintRect = m_repaintRect;
478     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
479         // Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
480         if (child->isComposited())
481             continue;
482
483         repaintRect.unite(child->repaintRectIncludingNonCompositingDescendants());
484     }
485     return repaintRect;
486 }
487
488 void RenderLayer::setAncestorChainHasSelfPaintingLayerDescendant()
489 {
490     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
491         if (!layer->m_hasSelfPaintingLayerDescendantDirty && layer->hasSelfPaintingLayerDescendant())
492             break;
493
494         layer->m_hasSelfPaintingLayerDescendantDirty = false;
495         layer->m_hasSelfPaintingLayerDescendant = true;
496     }
497 }
498
499 void RenderLayer::dirtyAncestorChainHasSelfPaintingLayerDescendantStatus()
500 {
501     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
502         layer->m_hasSelfPaintingLayerDescendantDirty = true;
503         // If we have reached a self-painting layer, we know our parent should have a self-painting descendant
504         // in this case, there is no need to dirty our ancestors further.
505         if (layer->isSelfPaintingLayer()) {
506             ASSERT(!parent() || parent()->m_hasSelfPaintingLayerDescendantDirty || parent()->hasSelfPaintingLayerDescendant());
507             break;
508         }
509     }
510 }
511
512 bool RenderLayer::acceleratedCompositingForOverflowScrollEnabled() const
513 {
514     return renderer().frame().settings().acceleratedCompositingForOverflowScrollEnabled();
515 }
516
517 // If we are a stacking container, then this function will determine if our
518 // descendants for a contiguous block in stacking order. This is required in
519 // order for an element to be safely promoted to a stacking container. It is safe
520 // to become a stacking container if this change would not alter the stacking
521 // order of layers on the page. That can only happen if a non-descendant appear
522 // between us and our descendants in stacking order. Here's an example:
523 //
524 //                                 this
525 //                                /  |  \.
526 //                               A   B   C
527 //                              /\   |   /\.
528 //                             0 -8  D  2  7
529 //                                   |
530 //                                   5
531 //
532 // I've labeled our normal flow descendants A, B, C, and D, our stacking
533 // container descendants with their z indices, and us with 'this' (we're a
534 // stacking container and our zIndex doesn't matter here). These nodes appear in
535 // three lists: posZOrder, negZOrder, and normal flow (keep in mind that normal
536 // flow layers don't overlap). So if we arrange these lists in order we get our
537 // stacking order:
538 //
539 //                     [-8], [A-D], [0, 2, 5, 7]--> pos z-order.
540 //                       |     |
541 //        Neg z-order. <-+     +--> Normal flow descendants.
542 //
543 // We can then assign new, 'stacking' order indices to these elements as follows:
544 //
545 //                     [-8], [A-D], [0, 2, 5, 7]
546 // 'Stacking' indices:  -1     0     1  2  3  4
547 //
548 // Note that the normal flow descendants can share an index because they don't
549 // stack/overlap. Now our problem becomes very simple: a layer can safely become
550 // a stacking container if the stacking-order indices of it and its descendants
551 // appear in a contiguous block in the list of stacking indices. This problem
552 // can be solved very efficiently by calculating the min/max stacking indices in
553 // the subtree, and the number stacking container descendants. Once we have this
554 // information, we know that the subtree's indices form a contiguous block if:
555 //
556 //           maxStackIndex - minStackIndex == numSCDescendants
557 //
558 // So for node A in the example above we would have:
559 //   maxStackIndex = 1
560 //   minStackIndex = -1
561 //   numSCDecendants = 2
562 //
563 // and so,
564 //       maxStackIndex - minStackIndex == numSCDescendants
565 //  ===>                      1 - (-1) == 2
566 //  ===>                             2 == 2
567 //
568 //  Since this is true, A can safely become a stacking container.
569 //  Now, for node C we have:
570 //
571 //   maxStackIndex = 4
572 //   minStackIndex = 0 <-- because C has stacking index 0.
573 //   numSCDecendants = 2
574 //
575 // and so,
576 //       maxStackIndex - minStackIndex == numSCDescendants
577 //  ===>                         4 - 0 == 2
578 //  ===>                             4 == 2
579 //
580 // Since this is false, C cannot be safely promoted to a stacking container. This
581 // happened because of the elements with z-index 5 and 0. Now if 5 had been a
582 // child of C rather than D, and A had no child with Z index 0, we would have had:
583 //
584 //   maxStackIndex = 3
585 //   minStackIndex = 0 <-- because C has stacking index 0.
586 //   numSCDecendants = 3
587 //
588 // and so,
589 //       maxStackIndex - minStackIndex == numSCDescendants
590 //  ===>                         3 - 0 == 3
591 //  ===>                             3 == 3
592 //
593 //  And we would conclude that C could be promoted.
594 void RenderLayer::updateDescendantsAreContiguousInStackingOrder()
595 {
596     if (!isStackingContext() || !acceleratedCompositingForOverflowScrollEnabled())
597         return;
598
599     ASSERT(!m_normalFlowListDirty);
600     ASSERT(!m_zOrderListsDirty);
601
602     std::unique_ptr<Vector<RenderLayer*>> posZOrderList;
603     std::unique_ptr<Vector<RenderLayer*>> negZOrderList;
604     rebuildZOrderLists(StopAtStackingContexts, posZOrderList, negZOrderList);
605
606     // Create a reverse lookup.
607     HashMap<const RenderLayer*, int> lookup;
608
609     if (negZOrderList) {
610         int stackingOrderIndex = -1;
611         size_t listSize = negZOrderList->size();
612         for (size_t i = 0; i < listSize; ++i) {
613             RenderLayer* currentLayer = negZOrderList->at(listSize - i - 1);
614             if (!currentLayer->isStackingContext())
615                 continue;
616             lookup.set(currentLayer, stackingOrderIndex--);
617         }
618     }
619
620     if (posZOrderList) {
621         size_t listSize = posZOrderList->size();
622         int stackingOrderIndex = 1;
623         for (size_t i = 0; i < listSize; ++i) {
624             RenderLayer* currentLayer = posZOrderList->at(i);
625             if (!currentLayer->isStackingContext())
626                 continue;
627             lookup.set(currentLayer, stackingOrderIndex++);
628         }
629     }
630
631     int minIndex = 0;
632     int maxIndex = 0;
633     int count = 0;
634     bool firstIteration = true;
635     updateDescendantsAreContiguousInStackingOrderRecursive(lookup, minIndex, maxIndex, count, firstIteration);
636 }
637
638 void RenderLayer::updateDescendantsAreContiguousInStackingOrderRecursive(const HashMap<const RenderLayer*, int>& lookup, int& minIndex, int& maxIndex, int& count, bool firstIteration)
639 {
640     if (isStackingContext() && !firstIteration) {
641         if (lookup.contains(this)) {
642             minIndex = std::min(minIndex, lookup.get(this));
643             maxIndex = std::max(maxIndex, lookup.get(this));
644             count++;
645         }
646         return;
647     }
648
649     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
650         int childMinIndex = 0;
651         int childMaxIndex = 0;
652         int childCount = 0;
653         child->updateDescendantsAreContiguousInStackingOrderRecursive(lookup, childMinIndex, childMaxIndex, childCount, false);
654         if (childCount) {
655             count += childCount;
656             minIndex = std::min(minIndex, childMinIndex);
657             maxIndex = std::max(maxIndex, childMaxIndex);
658         }
659     }
660
661     if (!isStackingContext()) {
662         bool newValue = maxIndex - minIndex == count;
663         bool didUpdate = newValue != m_descendantsAreContiguousInStackingOrder;
664         m_descendantsAreContiguousInStackingOrder = newValue;
665         if (didUpdate)
666             updateNeedsCompositedScrolling();
667     }
668 }
669
670 void RenderLayer::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)
671 {
672     ASSERT(!m_visibleContentStatusDirty);
673
674     m_repaintRect = renderer().clippedOverflowRectForRepaint(repaintContainer);
675     m_outlineBox = renderer().outlineBoundsForRepaint(repaintContainer, geometryMap);
676 }
677
678
679 void RenderLayer::computeRepaintRectsIncludingDescendants()
680 {
681     // FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
682     // We should make this more efficient.
683     // FIXME: it's wrong to call this when layout is not up-to-date, which we do.
684     computeRepaintRects(renderer().containerForRepaint());
685
686     for (RenderLayer* layer = firstChild(); layer; layer = layer->nextSibling())
687         layer->computeRepaintRectsIncludingDescendants();
688 }
689
690 void RenderLayer::clearRepaintRects()
691 {
692     ASSERT(!m_hasVisibleContent);
693     ASSERT(!m_visibleContentStatusDirty);
694
695     m_repaintRect = LayoutRect();
696     m_outlineBox = LayoutRect();
697 }
698
699 void RenderLayer::updateLayerPositionsAfterDocumentScroll()
700 {
701     ASSERT(this == renderer().view().layer());
702
703     RenderGeometryMap geometryMap(UseTransforms);
704     updateLayerPositionsAfterScroll(&geometryMap);
705 }
706
707 void RenderLayer::updateLayerPositionsAfterOverflowScroll()
708 {
709     RenderGeometryMap geometryMap(UseTransforms);
710     if (this != renderer().view().layer())
711         geometryMap.pushMappingsToAncestor(parent(), 0);
712
713     // FIXME: why is it OK to not check the ancestors of this layer in order to
714     // initialize the HasSeenViewportConstrainedAncestor and HasSeenAncestorWithOverflowClip flags?
715     updateLayerPositionsAfterScroll(&geometryMap, IsOverflowScroll);
716 }
717
718 void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap, UpdateLayerPositionsAfterScrollFlags flags)
719 {
720     // FIXME: This shouldn't be needed, but there are some corner cases where
721     // these flags are still dirty. Update so that the check below is valid.
722     updateDescendantDependentFlags();
723
724     // If we have no visible content and no visible descendants, there is no point recomputing
725     // our rectangles as they will be empty. If our visibility changes, we are expected to
726     // recompute all our positions anyway.
727     if (!m_hasVisibleDescendant && !m_hasVisibleContent)
728         return;
729
730     bool positionChanged = updateLayerPosition();
731     if (positionChanged)
732         flags |= HasChangedAncestor;
733
734     if (geometryMap)
735         geometryMap->pushMappingsToAncestor(this, parent());
736
737     if (flags & HasChangedAncestor || flags & HasSeenViewportConstrainedAncestor || flags & IsOverflowScroll)
738         clearClipRects();
739
740     if (renderer().style().hasViewportConstrainedPosition())
741         flags |= HasSeenViewportConstrainedAncestor;
742
743     if (renderer().hasOverflowClip())
744         flags |= HasSeenAncestorWithOverflowClip;
745
746     if (flags & HasSeenViewportConstrainedAncestor
747         || (flags & IsOverflowScroll && flags & HasSeenAncestorWithOverflowClip)) {
748         // FIXME: We could track the repaint container as we walk down the tree.
749         computeRepaintRects(renderer().containerForRepaint(), geometryMap);
750     } else {
751         // Check that our cached rects are correct.
752         ASSERT(m_repaintRect == renderer().clippedOverflowRectForRepaint(renderer().containerForRepaint()));
753         ASSERT(m_outlineBox == renderer().outlineBoundsForRepaint(renderer().containerForRepaint(), geometryMap));
754     }
755     
756     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
757         child->updateLayerPositionsAfterScroll(geometryMap, flags);
758
759     // We don't update our reflection as scrolling is a translation which does not change the size()
760     // of an object, thus RenderReplica will still repaint itself properly as the layer position was
761     // updated above.
762
763     if (m_marquee) {
764         bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
765         m_updatingMarqueePosition = true;
766         m_marquee->updateMarqueePosition();
767         m_updatingMarqueePosition = oldUpdatingMarqueePosition;
768     }
769
770     if (geometryMap)
771         geometryMap->popMappingsToAncestor(parent());
772 }
773
774 void RenderLayer::positionNewlyCreatedOverflowControls()
775 {
776     if (!backing()->hasUnpositionedOverflowControlsLayers())
777         return;
778
779     RenderGeometryMap geometryMap(UseTransforms);
780     if (this != renderer().view().layer() && parent())
781         geometryMap.pushMappingsToAncestor(parent(), 0);
782
783     LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
784     positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
785 }
786
787 #if ENABLE(CSS_COMPOSITING)
788
789 void RenderLayer::updateBlendMode()
790 {
791     bool hadBlendMode = m_blendMode != BlendModeNormal;
792     if (parent() && hadBlendMode != hasBlendMode()) {
793         if (hasBlendMode())
794             parent()->updateAncestorChainHasBlendingDescendants();
795         else
796             parent()->dirtyAncestorChainHasBlendingDescendants();
797     }
798
799     BlendMode newBlendMode = renderer().style().blendMode();
800     if (newBlendMode != m_blendMode)
801         m_blendMode = newBlendMode;
802 }
803
804 void RenderLayer::updateAncestorChainHasBlendingDescendants()
805 {
806     for (auto layer = this; layer; layer = layer->parent()) {
807         if (!layer->hasNotIsolatedBlendingDescendantsStatusDirty() && layer->hasNotIsolatedBlendingDescendants())
808             break;
809         layer->m_hasNotIsolatedBlendingDescendants = true;
810         layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
811
812         layer->updateSelfPaintingLayer();
813
814         if (layer->isStackingContext())
815             break;
816     }
817 }
818
819 void RenderLayer::dirtyAncestorChainHasBlendingDescendants()
820 {
821     for (auto layer = this; layer; layer = layer->parent()) {
822         if (layer->hasNotIsolatedBlendingDescendantsStatusDirty())
823             break;
824         
825         layer->m_hasNotIsolatedBlendingDescendantsStatusDirty = true;
826
827         if (layer->isStackingContext())
828             break;
829     }
830 }
831 #endif
832
833 void RenderLayer::updateTransform()
834 {
835     // hasTransform() on the renderer is also true when there is transform-style: preserve-3d or perspective set,
836     // so check style too.
837     bool hasTransform = renderer().hasTransform() && renderer().style().hasTransform();
838     bool had3DTransform = has3DTransform();
839
840     bool hadTransform = !!m_transform;
841     if (hasTransform != hadTransform) {
842         if (hasTransform)
843             m_transform = std::make_unique<TransformationMatrix>();
844         else
845             m_transform = nullptr;
846         
847         // Layers with transforms act as clip rects roots, so clear the cached clip rects here.
848         clearClipRectsIncludingDescendants();
849     }
850     
851     if (hasTransform) {
852         RenderBox* box = renderBox();
853         ASSERT(box);
854         m_transform->makeIdentity();
855         box->style().applyTransform(*m_transform, pixelSnappedForPainting(box->borderBoxRect(), box->document().deviceScaleFactor()), RenderStyle::IncludeTransformOrigin);
856         makeMatrixRenderable(*m_transform, canRender3DTransforms());
857     }
858
859     if (had3DTransform != has3DTransform())
860         dirty3DTransformedDescendantStatus();
861 }
862
863 TransformationMatrix RenderLayer::currentTransform(RenderStyle::ApplyTransformOrigin applyOrigin) const
864 {
865     if (!m_transform)
866         return TransformationMatrix();
867
868     RenderBox* box = renderBox();
869     ASSERT(box);
870     FloatRect pixelSnappedBorderRect = pixelSnappedForPainting(box->borderBoxRect(), box->document().deviceScaleFactor());
871     if (renderer().style().isRunningAcceleratedAnimation()) {
872         TransformationMatrix currTransform;
873         RefPtr<RenderStyle> style = renderer().animation().getAnimatedStyleForRenderer(&renderer());
874         style->applyTransform(currTransform, pixelSnappedBorderRect, applyOrigin);
875         makeMatrixRenderable(currTransform, canRender3DTransforms());
876         return currTransform;
877     }
878
879     // m_transform includes transform-origin, so we need to recompute the transform here.
880     if (applyOrigin == RenderStyle::ExcludeTransformOrigin) {
881         TransformationMatrix currTransform;
882         box->style().applyTransform(currTransform, pixelSnappedBorderRect, RenderStyle::ExcludeTransformOrigin);
883         makeMatrixRenderable(currTransform, canRender3DTransforms());
884         return currTransform;
885     }
886
887     return *m_transform;
888 }
889
890 TransformationMatrix RenderLayer::renderableTransform(PaintBehavior paintBehavior) const
891 {
892     if (!m_transform)
893         return TransformationMatrix();
894     
895     if (paintBehavior & PaintBehaviorFlattenCompositingLayers) {
896         TransformationMatrix matrix = *m_transform;
897         makeMatrixRenderable(matrix, false /* flatten 3d */);
898         return matrix;
899     }
900
901     return *m_transform;
902 }
903
904 RenderLayer* RenderLayer::enclosingOverflowClipLayer(IncludeSelfOrNot includeSelf) const
905 {
906     const RenderLayer* layer = (includeSelf == IncludeSelf) ? this : parent();
907     while (layer) {
908         if (layer->renderer().hasOverflowClip())
909             return const_cast<RenderLayer*>(layer);
910
911         layer = layer->parent();
912     }
913     return 0;
914 }
915
916 // FIXME: This is terrible. Bring back a cached bit for this someday. This crawl is going to slow down all
917 // painting of content inside paginated layers.
918 bool RenderLayer::hasCompositedLayerInEnclosingPaginationChain() const
919 {
920     // No enclosing layer means no compositing in the chain.
921     if (!m_enclosingPaginationLayer)
922         return false;
923     
924     // If the enclosing layer is composited, we don't have to check anything in between us and that
925     // layer.
926     if (m_enclosingPaginationLayer->isComposited())
927         return true;
928
929     // If we are the enclosing pagination layer, then we can't be composited or we'd have passed the
930     // previous check.
931     if (m_enclosingPaginationLayer == this)
932         return false;
933
934     // The enclosing paginated layer is our ancestor and is not composited, so we have to check
935     // intermediate layers between us and the enclosing pagination layer. Start with our own layer.
936     if (isComposited())
937         return true;
938     
939     // For normal flow layers, we can recur up the layer tree.
940     if (isNormalFlowOnly())
941         return parent()->hasCompositedLayerInEnclosingPaginationChain();
942     
943     // Otherwise we have to go up the containing block chain. Find the first enclosing
944     // containing block layer ancestor, and check that.
945     RenderView* renderView = &renderer().view();
946     for (RenderBlock* containingBlock = renderer().containingBlock(); containingBlock && containingBlock != renderView; containingBlock = containingBlock->containingBlock()) {
947         if (containingBlock->hasLayer())
948             return containingBlock->layer()->hasCompositedLayerInEnclosingPaginationChain();
949     }
950     return false;
951 }
952
953 void RenderLayer::updatePagination()
954 {
955     m_enclosingPaginationLayer = nullptr;
956     
957     if (!parent())
958         return;
959     
960     // Each layer that is inside a multicolumn flow thread has to be checked individually and
961     // genuinely know if it is going to have to split itself up when painting only its contents (and not any other descendant
962     // layers). We track an enclosingPaginationLayer instead of using a simple bit, since we want to be able to get back
963     // to that layer easily.
964     if (renderer().isInFlowRenderFlowThread()) {
965         m_enclosingPaginationLayer = this;
966         return;
967     }
968
969     if (isNormalFlowOnly()) {
970         // Content inside a transform is not considered to be paginated, since we simply
971         // paint the transform multiple times in each column, so we don't have to use
972         // fragments for the transformed content.
973         if (parent()->hasTransform())
974             m_enclosingPaginationLayer = nullptr;
975         else
976             m_enclosingPaginationLayer = parent()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers);
977         return;
978     }
979
980     // For the new columns code, we want to walk up our containing block chain looking for an enclosing layer. Once
981     // we find one, then we just check its pagination status.
982     RenderView* renderView = &renderer().view();
983     RenderBlock* containingBlock;
984     for (containingBlock = renderer().containingBlock(); containingBlock && containingBlock != renderView; containingBlock = containingBlock->containingBlock()) {
985         if (containingBlock->hasLayer()) {
986             // Content inside a transform is not considered to be paginated, since we simply
987             // paint the transform multiple times in each column, so we don't have to use
988             // fragments for the transformed content.
989             if (containingBlock->layer()->hasTransform())
990                 m_enclosingPaginationLayer = nullptr;
991             else
992                 m_enclosingPaginationLayer = containingBlock->layer()->enclosingPaginationLayer(IncludeCompositedPaginatedLayers);
993             return;
994         }
995     }
996 }
997
998 bool RenderLayer::canBeStackingContainer() const
999 {
1000     if (isStackingContext() || !stackingContainer())
1001         return true;
1002
1003     return m_descendantsAreContiguousInStackingOrder;
1004 }
1005
1006 void RenderLayer::setHasVisibleContent()
1007
1008     if (m_hasVisibleContent && !m_visibleContentStatusDirty) {
1009         ASSERT(!parent() || parent()->hasVisibleDescendant());
1010         return;
1011     }
1012
1013     m_visibleContentStatusDirty = false; 
1014     m_hasVisibleContent = true;
1015     computeRepaintRects(renderer().containerForRepaint());
1016     if (!isNormalFlowOnly()) {
1017         // We don't collect invisible layers in z-order lists if we are not in compositing mode.
1018         // As we became visible, we need to dirty our stacking containers ancestors to be properly
1019         // collected. FIXME: When compositing, we could skip this dirtying phase.
1020         for (RenderLayer* sc = stackingContainer(); sc; sc = sc->stackingContainer()) {
1021             sc->dirtyZOrderLists();
1022             if (sc->hasVisibleContent())
1023                 break;
1024         }
1025     }
1026
1027     if (parent())
1028         parent()->setAncestorChainHasVisibleDescendant();
1029 }
1030
1031 void RenderLayer::dirtyVisibleContentStatus() 
1032
1033     m_visibleContentStatusDirty = true; 
1034     if (parent())
1035         parent()->dirtyAncestorChainVisibleDescendantStatus();
1036 }
1037
1038 void RenderLayer::dirtyAncestorChainVisibleDescendantStatus()
1039 {
1040     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1041         if (layer->m_visibleDescendantStatusDirty)
1042             break;
1043
1044         layer->m_visibleDescendantStatusDirty = true;
1045     }
1046 }
1047
1048 void RenderLayer::setAncestorChainHasVisibleDescendant()
1049 {
1050     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
1051         if (!layer->m_visibleDescendantStatusDirty && layer->hasVisibleDescendant())
1052             break;
1053
1054         layer->m_hasVisibleDescendant = true;
1055         layer->m_visibleDescendantStatusDirty = false;
1056     }
1057 }
1058
1059 void RenderLayer::updateDescendantDependentFlags(HashSet<const RenderObject*>* outOfFlowDescendantContainingBlocks)
1060 {
1061     if (m_visibleDescendantStatusDirty || m_hasSelfPaintingLayerDescendantDirty || m_hasOutOfFlowPositionedDescendantDirty || hasNotIsolatedBlendingDescendantsStatusDirty()) {
1062         bool hasVisibleDescendant = false;
1063         bool hasSelfPaintingLayerDescendant = false;
1064         bool hasOutOfFlowPositionedDescendant = false;
1065 #if ENABLE(CSS_COMPOSITING)
1066         bool hasNotIsolatedBlendingDescendants = false;
1067 #endif
1068
1069         HashSet<const RenderObject*> childOutOfFlowDescendantContainingBlocks;
1070         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
1071             childOutOfFlowDescendantContainingBlocks.clear();
1072             child->updateDescendantDependentFlags(&childOutOfFlowDescendantContainingBlocks);
1073
1074             bool childIsOutOfFlowPositioned = child->renderer().isOutOfFlowPositioned();
1075             if (childIsOutOfFlowPositioned)
1076                 childOutOfFlowDescendantContainingBlocks.add(child->renderer().containingBlock());
1077
1078             if (outOfFlowDescendantContainingBlocks) {
1079                 HashSet<const RenderObject*>::const_iterator it = childOutOfFlowDescendantContainingBlocks.begin();
1080                 for (; it != childOutOfFlowDescendantContainingBlocks.end(); ++it)
1081                     outOfFlowDescendantContainingBlocks->add(*it);
1082             }
1083
1084             hasVisibleDescendant |= child->m_hasVisibleContent || child->m_hasVisibleDescendant;
1085             hasSelfPaintingLayerDescendant |= child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant();
1086             hasOutOfFlowPositionedDescendant |= !childOutOfFlowDescendantContainingBlocks.isEmpty();
1087 #if ENABLE(CSS_COMPOSITING)
1088             hasNotIsolatedBlendingDescendants |= child->hasBlendMode() || (child->hasNotIsolatedBlendingDescendants() && !child->isolatesBlending());
1089 #endif
1090
1091             bool allFlagsSet = hasVisibleDescendant && hasSelfPaintingLayerDescendant && hasOutOfFlowPositionedDescendant;
1092 #if ENABLE(CSS_COMPOSITING)
1093             allFlagsSet &= hasNotIsolatedBlendingDescendants;
1094 #endif
1095             if (allFlagsSet)
1096                 break;
1097         }
1098
1099         if (outOfFlowDescendantContainingBlocks)
1100             outOfFlowDescendantContainingBlocks->remove(&renderer());
1101
1102         m_hasVisibleDescendant = hasVisibleDescendant;
1103         m_visibleDescendantStatusDirty = false;
1104         m_hasSelfPaintingLayerDescendant = hasSelfPaintingLayerDescendant;
1105         m_hasSelfPaintingLayerDescendantDirty = false;
1106
1107         m_hasOutOfFlowPositionedDescendant = hasOutOfFlowPositionedDescendant;
1108         if (m_hasOutOfFlowPositionedDescendantDirty)
1109             updateNeedsCompositedScrolling();
1110
1111         m_hasOutOfFlowPositionedDescendantDirty = false;
1112 #if ENABLE(CSS_COMPOSITING)
1113         m_hasNotIsolatedBlendingDescendants = hasNotIsolatedBlendingDescendants;
1114         if (m_hasNotIsolatedBlendingDescendantsStatusDirty) {
1115             m_hasNotIsolatedBlendingDescendantsStatusDirty = false;
1116             updateSelfPaintingLayer();
1117         }
1118 #endif
1119     }
1120
1121     if (m_visibleContentStatusDirty) {
1122         if (renderer().style().visibility() == VISIBLE)
1123             m_hasVisibleContent = true;
1124         else {
1125             // layer may be hidden but still have some visible content, check for this
1126             m_hasVisibleContent = false;
1127             RenderObject* r = renderer().firstChild();
1128             while (r) {
1129                 if (r->style().visibility() == VISIBLE && !r->hasLayer()) {
1130                     m_hasVisibleContent = true;
1131                     break;
1132                 }
1133                 RenderObject* child = nullptr;
1134                 if (!r->hasLayer() && (child = r->firstChildSlow()))
1135                     r = child;
1136                 else if (r->nextSibling())
1137                     r = r->nextSibling();
1138                 else {
1139                     do {
1140                         r = r->parent();
1141                         if (r == &renderer())
1142                             r = nullptr;
1143                     } while (r && !r->nextSibling());
1144                     if (r)
1145                         r = r->nextSibling();
1146                 }
1147             }
1148         }    
1149         m_visibleContentStatusDirty = false; 
1150     }
1151 }
1152
1153 // Return true if the new clipping behaviour requires layer update.
1154 bool RenderLayer::checkIfDescendantClippingContextNeedsUpdate(bool isClipping)
1155 {
1156     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
1157         RenderLayerBacking* backing = child->backing();
1158         // Layer subtree needs update when new clipping is added or existing clipping is removed.
1159         if (backing && (isClipping || backing->hasAncestorClippingLayer()))
1160             return true;
1161
1162         if (child->checkIfDescendantClippingContextNeedsUpdate(isClipping))
1163             return true;
1164     }
1165     return false;
1166 }
1167
1168 void RenderLayer::dirty3DTransformedDescendantStatus()
1169 {
1170     RenderLayer* curr = stackingContainer();
1171     if (curr)
1172         curr->m_3DTransformedDescendantStatusDirty = true;
1173         
1174     // This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
1175     // Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
1176     while (curr && curr->preserves3D()) {
1177         curr->m_3DTransformedDescendantStatusDirty = true;
1178         curr = curr->stackingContainer();
1179     }
1180 }
1181
1182 // Return true if this layer or any preserve-3d descendants have 3d.
1183 bool RenderLayer::update3DTransformedDescendantStatus()
1184 {
1185     if (m_3DTransformedDescendantStatusDirty) {
1186         m_has3DTransformedDescendant = false;
1187
1188         updateZOrderLists();
1189
1190         // Transformed or preserve-3d descendants can only be in the z-order lists, not
1191         // in the normal flow list, so we only need to check those.
1192         if (Vector<RenderLayer*>* positiveZOrderList = posZOrderList()) {
1193             for (unsigned i = 0; i < positiveZOrderList->size(); ++i)
1194                 m_has3DTransformedDescendant |= positiveZOrderList->at(i)->update3DTransformedDescendantStatus();
1195         }
1196
1197         // Now check our negative z-index children.
1198         if (Vector<RenderLayer*>* negativeZOrderList = negZOrderList()) {
1199             for (unsigned i = 0; i < negativeZOrderList->size(); ++i)
1200                 m_has3DTransformedDescendant |= negativeZOrderList->at(i)->update3DTransformedDescendantStatus();
1201         }
1202         
1203         m_3DTransformedDescendantStatusDirty = false;
1204     }
1205     
1206     // If we live in a 3d hierarchy, then the layer at the root of that hierarchy needs
1207     // the m_has3DTransformedDescendant set.
1208     if (preserves3D())
1209         return has3DTransform() || m_has3DTransformedDescendant;
1210
1211     return has3DTransform();
1212 }
1213
1214 bool RenderLayer::updateLayerPosition()
1215 {
1216     LayoutPoint localPoint;
1217     LayoutSize inlineBoundingBoxOffset; // We don't put this into the RenderLayer x/y for inlines, so we need to subtract it out when done.
1218     if (renderer().isInline() && renderer().isRenderInline()) {
1219         RenderInline& inlineFlow = toRenderInline(renderer());
1220         IntRect lineBox = inlineFlow.linesBoundingBox();
1221         setSize(lineBox.size());
1222         inlineBoundingBoxOffset = toLayoutSize(lineBox.location());
1223         localPoint += inlineBoundingBoxOffset;
1224     } else if (RenderBox* box = renderBox()) {
1225         // FIXME: Is snapping the size really needed here for the RenderBox case?
1226         setSize(pixelSnappedIntSize(box->size(), box->location()));
1227         localPoint += box->topLeftLocationOffset();
1228     }
1229
1230     if (!renderer().isOutOfFlowPositioned() && renderer().parent()) {
1231         // We must adjust our position by walking up the render tree looking for the
1232         // nearest enclosing object with a layer.
1233         RenderElement* curr = renderer().parent();
1234         while (curr && !curr->hasLayer()) {
1235             if (curr->isBox() && !curr->isTableRow()) {
1236                 // Rows and cells share the same coordinate space (that of the section).
1237                 // Omit them when computing our xpos/ypos.
1238                 localPoint += toRenderBox(curr)->topLeftLocationOffset();
1239             }
1240             curr = curr->parent();
1241         }
1242         if (curr->isBox() && curr->isTableRow()) {
1243             // Put ourselves into the row coordinate space.
1244             localPoint -= toRenderBox(curr)->topLeftLocationOffset();
1245         }
1246     }
1247     
1248     // Subtract our parent's scroll offset.
1249     if (renderer().isOutOfFlowPositioned() && enclosingPositionedAncestor()) {
1250         RenderLayer* positionedParent = enclosingPositionedAncestor();
1251
1252         // For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
1253         if (positionedParent->renderer().hasOverflowClip()) {
1254             LayoutSize offset = positionedParent->scrolledContentOffset();
1255             localPoint -= offset;
1256         }
1257         
1258         if (renderer().isOutOfFlowPositioned() && positionedParent->renderer().isInFlowPositioned() && positionedParent->renderer().isRenderInline()) {
1259             LayoutSize offset = toRenderInline(positionedParent->renderer()).offsetForInFlowPositionedInline(&toRenderBox(renderer()));
1260             localPoint += offset;
1261         }
1262     } else if (parent()) {
1263         if (parent()->renderer().hasOverflowClip()) {
1264             IntSize scrollOffset = parent()->scrolledContentOffset();
1265             localPoint -= scrollOffset;
1266         }
1267     }
1268     
1269     bool positionOrOffsetChanged = false;
1270     if (renderer().isInFlowPositioned()) {
1271         LayoutSize newOffset = toRenderBoxModelObject(renderer()).offsetForInFlowPosition();
1272         positionOrOffsetChanged = newOffset != m_offsetForInFlowPosition;
1273         m_offsetForInFlowPosition = newOffset;
1274         localPoint.move(m_offsetForInFlowPosition);
1275     } else {
1276         m_offsetForInFlowPosition = LayoutSize();
1277     }
1278
1279     // FIXME: We'd really like to just get rid of the concept of a layer rectangle and rely on the renderers.
1280     localPoint -= inlineBoundingBoxOffset;
1281     
1282     positionOrOffsetChanged |= location() != localPoint;
1283     setLocation(localPoint);
1284     return positionOrOffsetChanged;
1285 }
1286
1287 TransformationMatrix RenderLayer::perspectiveTransform() const
1288 {
1289     if (!renderer().hasTransform())
1290         return TransformationMatrix();
1291
1292     const RenderStyle& style = renderer().style();
1293     if (!style.hasPerspective())
1294         return TransformationMatrix();
1295
1296     // Maybe fetch the perspective from the backing?
1297     const IntRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
1298     const float boxWidth = borderBox.width();
1299     const float boxHeight = borderBox.height();
1300
1301     float perspectiveOriginX = floatValueForLength(style.perspectiveOriginX(), boxWidth);
1302     float perspectiveOriginY = floatValueForLength(style.perspectiveOriginY(), boxHeight);
1303
1304     // A perspective origin of 0,0 makes the vanishing point in the center of the element.
1305     // We want it to be in the top-left, so subtract half the height and width.
1306     perspectiveOriginX -= boxWidth / 2.0f;
1307     perspectiveOriginY -= boxHeight / 2.0f;
1308     
1309     TransformationMatrix t;
1310     t.translate(perspectiveOriginX, perspectiveOriginY);
1311     t.applyPerspective(style.perspective());
1312     t.translate(-perspectiveOriginX, -perspectiveOriginY);
1313     
1314     return t;
1315 }
1316
1317 FloatPoint RenderLayer::perspectiveOrigin() const
1318 {
1319     if (!renderer().hasTransform())
1320         return FloatPoint();
1321
1322     const LayoutRect borderBox = toRenderBox(renderer()).borderBoxRect();
1323     const RenderStyle& style = renderer().style();
1324
1325     return FloatPoint(floatValueForLength(style.perspectiveOriginX(), borderBox.width()),
1326                       floatValueForLength(style.perspectiveOriginY(), borderBox.height()));
1327 }
1328
1329 RenderLayer* RenderLayer::stackingContainer() const
1330 {
1331     RenderLayer* layer = parent();
1332     while (layer && !layer->isStackingContainer())
1333         layer = layer->parent();
1334
1335     ASSERT(!layer || layer->isStackingContainer());
1336     return layer;
1337 }
1338
1339 static inline bool isPositionedContainer(RenderLayer* layer)
1340 {
1341     return layer->isRootLayer() || layer->renderer().isPositioned() || layer->hasTransform();
1342 }
1343
1344 static inline bool isFixedPositionedContainer(RenderLayer* layer)
1345 {
1346     return layer->isRootLayer() || layer->hasTransform();
1347 }
1348
1349 RenderLayer* RenderLayer::enclosingPositionedAncestor() const
1350 {
1351     RenderLayer* curr = parent();
1352     while (curr && !isPositionedContainer(curr))
1353         curr = curr->parent();
1354
1355     return curr;
1356 }
1357
1358 static RenderLayer* parentLayerCrossFrame(const RenderLayer* layer)
1359 {
1360     ASSERT(layer);
1361     if (layer->parent())
1362         return layer->parent();
1363
1364     HTMLFrameOwnerElement* ownerElement = layer->renderer().document().ownerElement();
1365     if (!ownerElement)
1366         return 0;
1367
1368     RenderElement* ownerRenderer = ownerElement->renderer();
1369     if (!ownerRenderer)
1370         return 0;
1371
1372     return ownerRenderer->enclosingLayer();
1373 }
1374
1375 RenderLayer* RenderLayer::enclosingScrollableLayer() const
1376 {
1377     for (RenderLayer* nextLayer = parentLayerCrossFrame(this); nextLayer; nextLayer = parentLayerCrossFrame(nextLayer)) {
1378         if (nextLayer->renderer().isBox() && toRenderBox(nextLayer->renderer()).canBeScrolledAndHasScrollableArea())
1379             return nextLayer;
1380     }
1381
1382     return 0;
1383 }
1384
1385 IntRect RenderLayer::scrollableAreaBoundingBox() const
1386 {
1387     return renderer().absoluteBoundingBoxRect();
1388 }
1389
1390 bool RenderLayer::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
1391 {
1392     Page* page = renderer().frame().page();
1393     return page && page->settings().forceUpdateScrollbarsOnMainThreadForPerformanceTesting();
1394 }
1395
1396 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
1397 {
1398     RenderLayer* curr = parent();
1399     while (curr && !curr->isRootLayer() && !curr->transform())
1400         curr = curr->parent();
1401
1402     return curr;
1403 }
1404
1405 static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
1406 {
1407     return layer->isNormalFlowOnly() ? layer->parent() : layer->stackingContainer();
1408 }
1409
1410 inline bool RenderLayer::shouldRepaintAfterLayout() const
1411 {
1412     if (m_repaintStatus == NeedsNormalRepaint)
1413         return true;
1414
1415     // Composited layers that were moved during a positioned movement only
1416     // layout, don't need to be repainted. They just need to be recomposited.
1417     ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
1418     return !isComposited() || backing()->paintsIntoCompositedAncestor();
1419 }
1420
1421 static bool compositedWithOwnBackingStore(const RenderLayer* layer)
1422 {
1423     return layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor();
1424 }
1425
1426 RenderLayer* RenderLayer::enclosingCompositingLayer(IncludeSelfOrNot includeSelf) const
1427 {
1428     if (includeSelf == IncludeSelf && isComposited())
1429         return const_cast<RenderLayer*>(this);
1430
1431     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1432         if (curr->isComposited())
1433             return const_cast<RenderLayer*>(curr);
1434     }
1435          
1436     return 0;
1437 }
1438
1439 RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(IncludeSelfOrNot includeSelf) const
1440 {
1441     if (includeSelf == IncludeSelf && isComposited() && !backing()->paintsIntoCompositedAncestor())
1442         return const_cast<RenderLayer*>(this);
1443
1444     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1445         if (compositedWithOwnBackingStore(curr))
1446             return const_cast<RenderLayer*>(curr);
1447     }
1448          
1449     return 0;
1450 }
1451
1452 #if ENABLE(CSS_FILTERS)
1453
1454 RenderLayer* RenderLayer::enclosingFilterLayer(IncludeSelfOrNot includeSelf) const
1455 {
1456     const RenderLayer* curr = (includeSelf == IncludeSelf) ? this : parent();
1457     for (; curr; curr = curr->parent()) {
1458         if (curr->requiresFullLayerImageForFilters())
1459             return const_cast<RenderLayer*>(curr);
1460     }
1461     
1462     return 0;
1463 }
1464
1465 RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
1466 {
1467     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1468         if ((curr != this && curr->requiresFullLayerImageForFilters()) || compositedWithOwnBackingStore(curr) || curr->isRootLayer())
1469             return const_cast<RenderLayer*>(curr);
1470     }
1471     return 0;
1472 }
1473
1474 void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect)
1475 {
1476     if (rect.isEmpty())
1477         return;
1478     
1479     LayoutRect rectForRepaint = rect;
1480     renderer().style().filterOutsets().expandRect(rectForRepaint);
1481
1482     FilterInfo& filterInfo = FilterInfo::get(*this);
1483     filterInfo.expandDirtySourceRect(rectForRepaint);
1484     
1485     RenderLayer* parentLayer = enclosingFilterRepaintLayer();
1486     ASSERT(parentLayer);
1487     FloatQuad repaintQuad(rectForRepaint);
1488     LayoutRect parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
1489
1490     if (parentLayer->isComposited()) {
1491         if (!parentLayer->backing()->paintsIntoWindow()) {
1492             parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
1493             return;
1494         }
1495         // If the painting goes to window, redirect the painting to the parent RenderView.
1496         parentLayer = renderer().view().layer();
1497         parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
1498     }
1499
1500     if (parentLayer->paintsWithFilters()) {
1501         parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect);
1502         return;        
1503     }
1504     
1505     if (parentLayer->isRootLayer()) {
1506         toRenderView(parentLayer->renderer()).repaintViewRectangle(parentLayerRect);
1507         return;
1508     }
1509     
1510     ASSERT_NOT_REACHED();
1511 }
1512
1513 bool RenderLayer::hasAncestorWithFilterOutsets() const
1514 {
1515     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1516         if (curr->renderer().style().hasFilterOutsets())
1517             return true;
1518     }
1519     return false;
1520 }
1521
1522 #endif
1523
1524 RenderLayer* RenderLayer::clippingRootForPainting() const
1525 {
1526     if (isComposited())
1527         return const_cast<RenderLayer*>(this);
1528
1529     const RenderLayer* current = this;
1530     while (current) {
1531         if (current->isRootLayer())
1532             return const_cast<RenderLayer*>(current);
1533
1534         current = compositingContainer(current);
1535         ASSERT(current);
1536         if (current->transform() || compositedWithOwnBackingStore(current))
1537             return const_cast<RenderLayer*>(current);
1538     }
1539
1540     ASSERT_NOT_REACHED();
1541     return 0;
1542 }
1543
1544 LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
1545 {
1546     // We don't use convertToLayerCoords because it doesn't know about transforms
1547     return roundedLayoutPoint(renderer().absoluteToLocal(absolutePoint, UseTransforms));
1548 }
1549
1550 bool RenderLayer::cannotBlitToWindow() const
1551 {
1552     if (isTransparent() || hasReflection() || hasTransform())
1553         return true;
1554     if (!parent())
1555         return false;
1556     return parent()->cannotBlitToWindow();
1557 }
1558
1559 RenderLayer* RenderLayer::transparentPaintingAncestor()
1560 {
1561     if (isComposited())
1562         return 0;
1563
1564     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
1565         if (curr->isComposited())
1566             return 0;
1567         if (curr->isTransparent())
1568             return curr;
1569     }
1570     return 0;
1571 }
1572
1573 enum TransparencyClipBoxBehavior {
1574     PaintingTransparencyClipBox,
1575     HitTestingTransparencyClipBox
1576 };
1577
1578 enum TransparencyClipBoxMode {
1579     DescendantsOfTransparencyClipBox,
1580     RootOfTransparencyClipBox
1581 };
1582
1583 static LayoutRect transparencyClipBox(const RenderLayer&, const RenderLayer* rootLayer, TransparencyClipBoxBehavior, TransparencyClipBoxMode, PaintBehavior = 0);
1584
1585 static void expandClipRectForRegionAndReflection(LayoutRect& clipRect, const RenderLayer& layer, const RenderLayer* rootLayer,
1586     TransparencyClipBoxBehavior transparencyBehavior, PaintBehavior paintBehavior)
1587 {
1588     // If this is a region, then the painting is actually done by its flow thread's layer.
1589     if (layer.renderer().isRenderNamedFlowFragmentContainer()) {
1590         RenderBlockFlow* regionContainer = toRenderBlockFlow(&layer.renderer());
1591         RenderNamedFlowFragment* region = regionContainer->renderNamedFlowFragment();
1592         RenderLayer* flowThreadLayer = region->flowThread()->layer();
1593         if (flowThreadLayer && (!layer.reflection() || layer.reflectionLayer() != flowThreadLayer)) {
1594             LayoutRect flowThreadClipRect = transparencyClipBox(*flowThreadLayer, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior);
1595             LayoutSize moveOffset = (regionContainer->contentBoxRect().location() + layer.offsetFromAncestor(flowThreadLayer)) - region->flowThreadPortionRect().location();
1596             flowThreadClipRect.move(moveOffset);
1597             
1598             clipRect.unite(flowThreadClipRect);
1599         }
1600     }
1601 }
1602
1603 static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, const RenderLayer& layer, const RenderLayer* rootLayer,
1604     TransparencyClipBoxBehavior transparencyBehavior, PaintBehavior paintBehavior)
1605 {
1606     // If we have a mask, then the clip is limited to the border box area (and there is
1607     // no need to examine child layers).
1608     if (!layer.renderer().hasMask()) {
1609         // Note: we don't have to walk z-order lists since transparent elements always establish
1610         // a stacking container. This means we can just walk the layer tree directly.
1611         for (RenderLayer* curr = layer.firstChild(); curr; curr = curr->nextSibling()) {
1612             if (!layer.reflection() || layer.reflectionLayer() != curr)
1613                 clipRect.unite(transparencyClipBox(*curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior));
1614         }
1615     }
1616
1617     expandClipRectForRegionAndReflection(clipRect, layer, rootLayer, transparencyBehavior, paintBehavior);
1618
1619     // If we have a reflection, then we need to account for that when we push the clip.  Reflect our entire
1620     // current transparencyClipBox to catch all child layers.
1621     // FIXME: Accelerated compositing will eventually want to do something smart here to avoid incorporating this
1622     // size into the parent layer.
1623     if (layer.renderer().hasReflection()) {
1624         LayoutSize delta = layer.offsetFromAncestor(rootLayer);
1625         clipRect.move(-delta);
1626         clipRect.unite(layer.renderBox()->reflectedRect(clipRect));
1627         clipRect.move(delta);
1628     }
1629 }
1630
1631 static LayoutRect transparencyClipBox(const RenderLayer& layer, const RenderLayer* rootLayer, TransparencyClipBoxBehavior transparencyBehavior,
1632     TransparencyClipBoxMode transparencyMode, PaintBehavior paintBehavior)
1633 {
1634     // FIXME: Although this function completely ignores CSS-imposed clipping, we did already intersect with the
1635     // paintDirtyRect, and that should cut down on the amount we have to paint.  Still it
1636     // would be better to respect clips.
1637     
1638     if (rootLayer != &layer && ((transparencyBehavior == PaintingTransparencyClipBox && layer.paintsWithTransform(paintBehavior))
1639         || (transparencyBehavior == HitTestingTransparencyClipBox && layer.hasTransform()))) {
1640         // The best we can do here is to use enclosed bounding boxes to establish a "fuzzy" enough clip to encompass
1641         // the transformed layer and all of its children.
1642         RenderLayer::PaginationInclusionMode mode = transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::IncludeCompositedPaginatedLayers : RenderLayer::ExcludeCompositedPaginatedLayers;
1643         const RenderLayer* paginationLayer = transparencyMode == DescendantsOfTransparencyClipBox ? layer.enclosingPaginationLayer(mode) : 0;
1644         const RenderLayer* rootLayerForTransform = paginationLayer ? paginationLayer : rootLayer;
1645         LayoutSize delta = layer.offsetFromAncestor(rootLayerForTransform);
1646
1647         TransformationMatrix transform;
1648         transform.translate(delta.width(), delta.height());
1649         transform = transform * *layer.transform();
1650
1651         // We don't use fragment boxes when collecting a transformed layer's bounding box, since it always
1652         // paints unfragmented.
1653         LayoutRect clipRect = layer.boundingBox(&layer);
1654         expandClipRectForDescendantsAndReflection(clipRect, layer, &layer, transparencyBehavior, paintBehavior);
1655 #if ENABLE(CSS_FILTERS)
1656         layer.renderer().style().filterOutsets().expandRect(clipRect);
1657 #endif
1658         LayoutRect result = transform.mapRect(clipRect);
1659         if (!paginationLayer)
1660             return result;
1661         
1662         // We have to break up the transformed extent across our columns.
1663         // Split our box up into the actual fragment boxes that render in the columns/pages and unite those together to
1664         // get our true bounding box.
1665         RenderFlowThread& enclosingFlowThread = toRenderFlowThread(paginationLayer->renderer());
1666         result = enclosingFlowThread.fragmentsBoundingBox(result);
1667         result.move(paginationLayer->offsetFromAncestor(rootLayer));
1668         return result;
1669     }
1670     
1671     LayoutRect clipRect = layer.boundingBox(rootLayer, layer.offsetFromAncestor(rootLayer), transparencyBehavior == HitTestingTransparencyClipBox ? RenderLayer::UseFragmentBoxesIncludingCompositing : RenderLayer::UseFragmentBoxesExcludingCompositing);
1672     expandClipRectForDescendantsAndReflection(clipRect, layer, rootLayer, transparencyBehavior, paintBehavior);
1673 #if ENABLE(CSS_FILTERS)
1674     layer.renderer().style().filterOutsets().expandRect(clipRect);
1675 #endif
1676     return clipRect;
1677 }
1678
1679 static LayoutRect paintingExtent(const RenderLayer& currentLayer, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
1680 {
1681     return intersection(transparencyClipBox(currentLayer, rootLayer, PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintBehavior), paintDirtyRect);
1682 }
1683
1684 void RenderLayer::beginTransparencyLayers(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, const LayoutRect& dirtyRect)
1685 {
1686     if (context->paintingDisabled() || (paintsWithTransparency(paintingInfo.paintBehavior) && m_usedTransparency))
1687         return;
1688
1689     RenderLayer* ancestor = transparentPaintingAncestor();
1690     if (ancestor)
1691         ancestor->beginTransparencyLayers(context, paintingInfo, dirtyRect);
1692     
1693     if (paintsWithTransparency(paintingInfo.paintBehavior)) {
1694         m_usedTransparency = true;
1695         context->save();
1696         LayoutRect adjustedClipRect = paintingExtent(*this, paintingInfo.rootLayer, dirtyRect, paintingInfo.paintBehavior);
1697         adjustedClipRect.move(paintingInfo.subpixelAccumulation);
1698         FloatRect pixelSnappedClipRect = pixelSnappedForPainting(adjustedClipRect, renderer().document().deviceScaleFactor());
1699         context->clip(pixelSnappedClipRect);
1700
1701 #if ENABLE(CSS_COMPOSITING)
1702         if (hasBlendMode())
1703             context->setCompositeOperation(context->compositeOperation(), blendMode());
1704 #endif
1705
1706         context->beginTransparencyLayer(renderer().opacity());
1707
1708 #if ENABLE(CSS_COMPOSITING)
1709         if (hasBlendMode())
1710             context->setCompositeOperation(context->compositeOperation(), BlendModeNormal);
1711 #endif
1712
1713 #ifdef REVEAL_TRANSPARENCY_LAYERS
1714         context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f), ColorSpaceDeviceRGB);
1715         context->fillRect(pixelSnappedClipRect);
1716 #endif
1717     }
1718 }
1719
1720 #if PLATFORM(IOS)
1721 void RenderLayer::willBeDestroyed()
1722 {
1723     if (RenderLayerBacking* layerBacking = backing())
1724         layerBacking->layerWillBeDestroyed();
1725 }
1726 #endif
1727
1728 void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
1729 {
1730     RenderLayer* prevSibling = beforeChild ? beforeChild->previousSibling() : lastChild();
1731     if (prevSibling) {
1732         child->setPreviousSibling(prevSibling);
1733         prevSibling->setNextSibling(child);
1734         ASSERT(prevSibling != child);
1735     } else
1736         setFirstChild(child);
1737
1738     if (beforeChild) {
1739         beforeChild->setPreviousSibling(child);
1740         child->setNextSibling(beforeChild);
1741         ASSERT(beforeChild != child);
1742     } else
1743         setLastChild(child);
1744
1745     child->setParent(this);
1746
1747     if (child->isNormalFlowOnly())
1748         dirtyNormalFlowList();
1749
1750     if (!child->isNormalFlowOnly() || child->firstChild()) {
1751         // Dirty the z-order list in which we are contained. The stackingContainer() can be null in the
1752         // case where we're building up generated content layers. This is ok, since the lists will start
1753         // off dirty in that case anyway.
1754         child->dirtyStackingContainerZOrderLists();
1755     }
1756
1757     child->updateDescendantDependentFlags();
1758     if (child->m_hasVisibleContent || child->m_hasVisibleDescendant)
1759         setAncestorChainHasVisibleDescendant();
1760
1761     if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
1762         setAncestorChainHasSelfPaintingLayerDescendant();
1763
1764     if (child->renderer().isOutOfFlowPositioned() || child->hasOutOfFlowPositionedDescendant())
1765         setAncestorChainHasOutOfFlowPositionedDescendant(child->renderer().containingBlock());
1766
1767 #if ENABLE(CSS_COMPOSITING)
1768     if (child->hasBlendMode() || (child->hasNotIsolatedBlendingDescendants() && !child->isolatesBlending()))
1769         updateAncestorChainHasBlendingDescendants();
1770 #endif
1771
1772     compositor().layerWasAdded(*this, *child);
1773 }
1774
1775 RenderLayer* RenderLayer::removeChild(RenderLayer* oldChild)
1776 {
1777     if (!renderer().documentBeingDestroyed())
1778         compositor().layerWillBeRemoved(*this, *oldChild);
1779
1780     // remove the child
1781     if (oldChild->previousSibling())
1782         oldChild->previousSibling()->setNextSibling(oldChild->nextSibling());
1783     if (oldChild->nextSibling())
1784         oldChild->nextSibling()->setPreviousSibling(oldChild->previousSibling());
1785
1786     if (m_first == oldChild)
1787         m_first = oldChild->nextSibling();
1788     if (m_last == oldChild)
1789         m_last = oldChild->previousSibling();
1790
1791     if (oldChild->isNormalFlowOnly())
1792         dirtyNormalFlowList();
1793     if (!oldChild->isNormalFlowOnly() || oldChild->firstChild()) { 
1794         // Dirty the z-order list in which we are contained.  When called via the
1795         // reattachment process in removeOnlyThisLayer, the layer may already be disconnected
1796         // from the main layer tree, so we need to null-check the |stackingContainer| value.
1797         oldChild->dirtyStackingContainerZOrderLists();
1798     }
1799
1800     if (oldChild->renderer().isOutOfFlowPositioned() || oldChild->hasOutOfFlowPositionedDescendant())
1801         dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
1802
1803     oldChild->setPreviousSibling(0);
1804     oldChild->setNextSibling(0);
1805     oldChild->setParent(0);
1806     
1807     oldChild->updateDescendantDependentFlags();
1808     if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
1809         dirtyAncestorChainVisibleDescendantStatus();
1810
1811     if (oldChild->isSelfPaintingLayer() || oldChild->hasSelfPaintingLayerDescendant())
1812         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
1813
1814 #if ENABLE(CSS_COMPOSITING)
1815     if (oldChild->hasBlendMode() || (oldChild->hasNotIsolatedBlendingDescendants() && !oldChild->isolatesBlending()))
1816         dirtyAncestorChainHasBlendingDescendants();
1817 #endif
1818
1819     return oldChild;
1820 }
1821
1822 void RenderLayer::removeOnlyThisLayer()
1823 {
1824     if (!m_parent)
1825         return;
1826
1827     // Mark that we are about to lose our layer. This makes render tree
1828     // walks ignore this layer while we're removing it.
1829     renderer().setHasLayer(false);
1830
1831     compositor().layerWillBeRemoved(*m_parent, *this);
1832
1833     // Dirty the clip rects.
1834     clearClipRectsIncludingDescendants();
1835
1836     RenderLayer* nextSib = nextSibling();
1837
1838     // Remove the child reflection layer before moving other child layers.
1839     // The reflection layer should not be moved to the parent.
1840     if (reflection())
1841         removeChild(reflectionLayer());
1842
1843     // Now walk our kids and reattach them to our parent.
1844     RenderLayer* current = m_first;
1845     while (current) {
1846         RenderLayer* next = current->nextSibling();
1847         removeChild(current);
1848         m_parent->addChild(current, nextSib);
1849         current->setRepaintStatus(NeedsFullRepaint);
1850         // updateLayerPositions depends on hasLayer() already being false for proper layout.
1851         ASSERT(!renderer().hasLayer());
1852         current->updateLayerPositions(0); // FIXME: use geometry map.
1853         current = next;
1854     }
1855
1856     // Remove us from the parent.
1857     m_parent->removeChild(this);
1858     renderer().destroyLayer();
1859 }
1860
1861 void RenderLayer::insertOnlyThisLayer()
1862 {
1863     if (!m_parent && renderer().parent()) {
1864         // We need to connect ourselves when our renderer() has a parent.
1865         // Find our enclosingLayer and add ourselves.
1866         RenderLayer* parentLayer = renderer().parent()->enclosingLayer();
1867         ASSERT(parentLayer);
1868         RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer().parent()->findNextLayer(parentLayer, &renderer()) : 0;
1869         parentLayer->addChild(this, beforeChild);
1870     }
1871
1872     // Remove all descendant layers from the hierarchy and add them to the new position.
1873     for (auto& child : childrenOfType<RenderElement>(renderer()))
1874         child.moveLayers(m_parent, this);
1875
1876     // Clear out all the clip rects.
1877     clearClipRectsIncludingDescendants();
1878 }
1879
1880 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation, ColumnOffsetAdjustment adjustForColumns) const
1881 {
1882     LayoutPoint location = convertToLayerCoords(ancestorLayer, roundedLocation, adjustForColumns);
1883     roundedLocation = roundedIntPoint(location);
1884 }
1885
1886 // Returns the layer reached on the walk up towards the ancestor.
1887 static inline const RenderLayer* accumulateOffsetTowardsAncestor(const RenderLayer* layer, const RenderLayer* ancestorLayer, LayoutPoint& location, RenderLayer::ColumnOffsetAdjustment adjustForColumns)
1888 {
1889     ASSERT(ancestorLayer != layer);
1890
1891     const RenderLayerModelObject& renderer = layer->renderer();
1892     EPosition position = renderer.style().position();
1893
1894     // FIXME: Special casing RenderFlowThread so much for fixed positioning here is not great.
1895     RenderFlowThread* fixedFlowThreadContainer = position == FixedPosition ? renderer.flowThreadContainingBlock() : 0;
1896     if (fixedFlowThreadContainer && !fixedFlowThreadContainer->isOutOfFlowPositioned())
1897         fixedFlowThreadContainer = nullptr;
1898
1899     // FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFlowThread
1900     // may need to be revisited in a future patch.
1901     // If the fixed renderer is inside a RenderFlowThread, we should not compute location using localToAbsolute,
1902     // since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
1903     // positioned in a completely different place in the viewport (RenderView).
1904     if (position == FixedPosition && !fixedFlowThreadContainer && (!ancestorLayer || ancestorLayer == renderer.view().layer())) {
1905         // If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
1906         // localToAbsolute() on the RenderView.
1907         FloatPoint absPos = renderer.localToAbsolute(FloatPoint(), IsFixed);
1908         location += LayoutSize(absPos.x(), absPos.y());
1909         return ancestorLayer;
1910     }
1911
1912     // For the fixed positioned elements inside a render flow thread, we should also skip the code path below
1913     // Otherwise, for the case of ancestorLayer == rootLayer and fixed positioned element child of a transformed
1914     // element in render flow thread, we will hit the fixed positioned container before hitting the ancestor layer.
1915     if (position == FixedPosition && !fixedFlowThreadContainer) {
1916         // For a fixed layers, we need to walk up to the root to see if there's a fixed position container
1917         // (e.g. a transformed layer). It's an error to call offsetFromAncestor() across a layer with a transform,
1918         // so we should always find the ancestor at or before we find the fixed position container.
1919         RenderLayer* fixedPositionContainerLayer = nullptr;
1920         bool foundAncestor = false;
1921         for (RenderLayer* currLayer = layer->parent(); currLayer; currLayer = currLayer->parent()) {
1922             if (currLayer == ancestorLayer)
1923                 foundAncestor = true;
1924
1925             if (isFixedPositionedContainer(currLayer)) {
1926                 fixedPositionContainerLayer = currLayer;
1927                 ASSERT_UNUSED(foundAncestor, foundAncestor);
1928                 break;
1929             }
1930         }
1931         
1932         ASSERT(fixedPositionContainerLayer); // We should have hit the RenderView's layer at least.
1933
1934         if (fixedPositionContainerLayer != ancestorLayer) {
1935             LayoutSize fixedContainerCoords = layer->offsetFromAncestor(fixedPositionContainerLayer);
1936             LayoutSize ancestorCoords = ancestorLayer->offsetFromAncestor(fixedPositionContainerLayer);
1937             location += (fixedContainerCoords - ancestorCoords);
1938             return ancestorLayer;
1939         }
1940     }
1941
1942     if (position == FixedPosition && fixedFlowThreadContainer) {
1943         ASSERT(ancestorLayer);
1944         if (ancestorLayer->isOutOfFlowRenderFlowThread()) {
1945             location += toLayoutSize(layer->location());
1946             return ancestorLayer;
1947         }
1948
1949         if (ancestorLayer == renderer.view().layer()) {
1950             // Add location in flow thread coordinates.
1951             location += toLayoutSize(layer->location());
1952
1953             // Add flow thread offset in view coordinates since the view may be scrolled.
1954             FloatPoint absPos = renderer.view().localToAbsolute(FloatPoint(), IsFixed);
1955             location += LayoutSize(absPos.x(), absPos.y());
1956             return ancestorLayer;
1957         }
1958     }
1959
1960     RenderLayer* parentLayer;
1961     if (position == AbsolutePosition || position == FixedPosition) {
1962         // Do what enclosingPositionedAncestor() does, but check for ancestorLayer along the way.
1963         parentLayer = layer->parent();
1964         bool foundAncestorFirst = false;
1965         while (parentLayer) {
1966             // RenderFlowThread is a positioned container, child of RenderView, positioned at (0,0).
1967             // This implies that, for out-of-flow positioned elements inside a RenderFlowThread,
1968             // we are bailing out before reaching root layer.
1969             if (isPositionedContainer(parentLayer))
1970                 break;
1971
1972             if (parentLayer == ancestorLayer) {
1973                 foundAncestorFirst = true;
1974                 break;
1975             }
1976
1977             parentLayer = parentLayer->parent();
1978         }
1979
1980         // We should not reach RenderView layer past the RenderFlowThread layer for any
1981         // children of the RenderFlowThread.
1982         if (renderer.flowThreadContainingBlock() && !layer->isOutOfFlowRenderFlowThread())
1983             ASSERT(parentLayer != renderer.view().layer());
1984
1985         if (foundAncestorFirst) {
1986             // Found ancestorLayer before the abs. positioned container, so compute offset of both relative
1987             // to enclosingPositionedAncestor and subtract.
1988             RenderLayer* positionedAncestor = parentLayer->enclosingPositionedAncestor();
1989             LayoutSize thisCoords = layer->offsetFromAncestor(positionedAncestor);
1990             LayoutSize ancestorCoords = ancestorLayer->offsetFromAncestor(positionedAncestor);
1991             location += (thisCoords - ancestorCoords);
1992             return ancestorLayer;
1993         }
1994     } else
1995         parentLayer = layer->parent();
1996     
1997     if (!parentLayer)
1998         return 0;
1999
2000     location += toLayoutSize(layer->location());
2001
2002     if (adjustForColumns == RenderLayer::AdjustForColumns) {
2003         if (RenderLayer* parentLayer = layer->parent()) {
2004             if (parentLayer->renderer().isRenderMultiColumnFlowThread()) {
2005                 RenderRegion* region = toRenderMultiColumnFlowThread(parentLayer->renderer()).physicalTranslationFromFlowToRegion(location);
2006                 if (region)
2007                     location.moveBy(region->topLeftLocation() + -parentLayer->renderBox()->topLeftLocation());
2008             }
2009         }
2010     }
2011
2012     return parentLayer;
2013 }
2014
2015 LayoutPoint RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, const LayoutPoint& location, ColumnOffsetAdjustment adjustForColumns) const
2016 {
2017     if (ancestorLayer == this)
2018         return location;
2019
2020     const RenderLayer* currLayer = this;
2021     LayoutPoint locationInLayerCoords = location;
2022     while (currLayer && currLayer != ancestorLayer)
2023         currLayer = accumulateOffsetTowardsAncestor(currLayer, ancestorLayer, locationInLayerCoords, adjustForColumns);
2024     return locationInLayerCoords;
2025 }
2026
2027 LayoutSize RenderLayer::offsetFromAncestor(const RenderLayer* ancestorLayer) const
2028 {
2029     return toLayoutSize(convertToLayerCoords(ancestorLayer, LayoutPoint()));
2030 }
2031
2032 #if PLATFORM(IOS)
2033 bool RenderLayer::hasAcceleratedTouchScrolling() const
2034 {
2035 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
2036     if (!scrollsOverflow())
2037         return false;
2038
2039     Settings* settings = renderer().document().settings();
2040     // FIXME: settings should not be null at this point. If you find a reliable way to hit this assertion, please file a bug.
2041     // See <rdar://problem/10266101>.
2042     ASSERT(settings);
2043
2044     return renderer().style().useTouchOverflowScrolling() || (settings && settings->alwaysUseAcceleratedOverflowScroll());
2045 #else
2046     return false;
2047 #endif
2048 }
2049
2050 bool RenderLayer::hasTouchScrollableOverflow() const
2051 {
2052     return hasAcceleratedTouchScrolling() && (hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
2053 }
2054
2055 #if ENABLE(TOUCH_EVENTS)
2056 bool RenderLayer::handleTouchEvent(const PlatformTouchEvent& touchEvent)
2057 {
2058     // If we have accelerated scrolling, let the scrolling be handled outside of WebKit.
2059     if (hasTouchScrollableOverflow())
2060         return false;
2061
2062     return ScrollableArea::handleTouchEvent(touchEvent);
2063 }
2064 #endif
2065
2066 void RenderLayer::registerAsTouchEventListenerForScrolling()
2067 {
2068     if (!renderer().element() || m_registeredAsTouchEventListenerForScrolling)
2069         return;
2070     
2071     renderer().document().addTouchEventListener(renderer().element());
2072     m_registeredAsTouchEventListenerForScrolling = true;
2073 }
2074
2075 void RenderLayer::unregisterAsTouchEventListenerForScrolling()
2076 {
2077     if (!renderer().element() || !m_registeredAsTouchEventListenerForScrolling)
2078         return;
2079
2080     renderer().document().removeTouchEventListener(renderer().element());
2081     m_registeredAsTouchEventListenerForScrolling = false;
2082 }
2083 #endif // PLATFORM(IOS)
2084
2085 bool RenderLayer::usesCompositedScrolling() const
2086 {
2087     return isComposited() && backing()->scrollingLayer();
2088 }
2089
2090 bool RenderLayer::needsCompositedScrolling() const
2091 {
2092     return m_needsCompositedScrolling;
2093 }
2094
2095 void RenderLayer::updateNeedsCompositedScrolling()
2096 {
2097     bool oldNeedsCompositedScrolling = m_needsCompositedScrolling;
2098
2099     if (!renderer().view().frameView().containsScrollableArea(this))
2100         m_needsCompositedScrolling = false;
2101     else {
2102         bool forceUseCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
2103             && canBeStackingContainer()
2104             && !hasOutOfFlowPositionedDescendant();
2105
2106 #if !PLATFORM(IOS) && ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
2107         m_needsCompositedScrolling = forceUseCompositedScrolling || renderer().style().useTouchOverflowScrolling();
2108 #else
2109         // On iOS we don't want to opt into accelerated composited scrolling, which creates scroll bar
2110         // layers in WebCore, because we use UIKit to composite our scroll bars.
2111         m_needsCompositedScrolling = forceUseCompositedScrolling;
2112 #endif
2113     }
2114
2115     if (oldNeedsCompositedScrolling != m_needsCompositedScrolling) {
2116         updateSelfPaintingLayer();
2117         if (isStackingContainer())
2118             dirtyZOrderLists();
2119         else
2120             clearZOrderLists();
2121
2122         dirtyStackingContainerZOrderLists();
2123
2124         compositor().setShouldReevaluateCompositingAfterLayout();
2125         compositor().setCompositingLayersNeedRebuild();
2126     }
2127 }
2128
2129 static inline int adjustedScrollDelta(int beginningDelta) {
2130     // This implemention matches Firefox's.
2131     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
2132     const int speedReducer = 12;
2133
2134     int adjustedDelta = beginningDelta / speedReducer;
2135     if (adjustedDelta > 1)
2136         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
2137     else if (adjustedDelta < -1)
2138         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
2139
2140     return adjustedDelta;
2141 }
2142
2143 static inline IntSize adjustedScrollDelta(const IntSize& delta)
2144 {
2145     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
2146 }
2147
2148 void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
2149 {
2150     IntPoint lastKnownMousePosition = renderer().frame().eventHandler().lastKnownMousePosition();
2151     
2152     // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
2153     static IntPoint previousMousePosition;
2154     if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
2155         lastKnownMousePosition = previousMousePosition;
2156     else
2157         previousMousePosition = lastKnownMousePosition;
2158
2159     IntSize delta = lastKnownMousePosition - sourcePoint;
2160
2161     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
2162         delta.setWidth(0);
2163     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
2164         delta.setHeight(0);
2165
2166     scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
2167 }
2168
2169 void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp, ScrollableArea** scrolledArea)
2170 {
2171     if (delta.isZero())
2172         return;
2173
2174     bool restrictedByLineClamp = false;
2175     if (renderer().parent())
2176         restrictedByLineClamp = !renderer().parent()->style().lineClamp().isNone();
2177
2178     if (renderer().hasOverflowClip() && !restrictedByLineClamp) {
2179         IntSize newScrollOffset = scrollOffset() + delta;
2180         scrollToOffset(newScrollOffset, clamp);
2181         if (scrolledArea)
2182             *scrolledArea = this;
2183
2184         // If this layer can't do the scroll we ask the next layer up that can scroll to try
2185         IntSize remainingScrollOffset = newScrollOffset - scrollOffset();
2186         if (!remainingScrollOffset.isZero() && renderer().parent()) {
2187             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2188                 scrollableLayer->scrollByRecursively(remainingScrollOffset, clamp, scrolledArea);
2189
2190             renderer().frame().eventHandler().updateAutoscrollRenderer();
2191         }
2192     } else {
2193         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
2194         // have an overflow clip. Which means that it is a document node that can be scrolled.
2195         renderer().view().frameView().scrollBy(delta);
2196         if (scrolledArea)
2197             *scrolledArea = &renderer().view().frameView();
2198
2199         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement? 
2200         // https://bugs.webkit.org/show_bug.cgi?id=28237
2201     }
2202 }
2203
2204 IntSize RenderLayer::clampScrollOffset(const IntSize& scrollOffset) const
2205 {
2206     RenderBox* box = renderBox();
2207     ASSERT(box);
2208
2209     int maxX = scrollWidth() - box->pixelSnappedClientWidth();
2210     int maxY = scrollHeight() - box->pixelSnappedClientHeight();
2211
2212     int x = std::max(std::min(scrollOffset.width(), maxX), 0);
2213     int y = std::max(std::min(scrollOffset.height(), maxY), 0);
2214     return IntSize(x, y);
2215 }
2216
2217 void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
2218 {
2219     IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
2220     if (newScrollOffset != this->scrollOffset())
2221         scrollToOffsetWithoutAnimation(IntPoint(newScrollOffset));
2222 }
2223
2224 void RenderLayer::scrollTo(int x, int y)
2225 {
2226     RenderBox* box = renderBox();
2227     if (!box)
2228         return;
2229
2230     if (box->style().overflowX() != OMARQUEE) {
2231         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
2232         if (m_scrollDimensionsDirty)
2233             computeScrollDimensions();
2234 #if PLATFORM(IOS)
2235         if (adjustForIOSCaretWhenScrolling()) {
2236             int maxX = scrollWidth() - box->clientWidth();
2237             if (x > maxX - caretWidth) {
2238                 x += caretWidth;
2239                 if (x <= caretWidth)
2240                     x = 0;
2241             } else if (x < m_scrollOffset.width() - caretWidth)
2242                 x -= caretWidth;
2243         }
2244 #endif
2245     }
2246     
2247     // FIXME: Eventually, we will want to perform a blit.  For now never
2248     // blit, since the check for blitting is going to be very
2249     // complicated (since it will involve testing whether our layer
2250     // is either occluded by another layer or clipped by an enclosing
2251     // layer or contains fixed backgrounds, etc.).
2252     IntSize newScrollOffset = IntSize(x - scrollOrigin().x(), y - scrollOrigin().y());
2253     if (m_scrollOffset == newScrollOffset) {
2254 #if PLATFORM(IOS)
2255         if (m_requiresScrollBoundsOriginUpdate)
2256             updateCompositingLayersAfterScroll();
2257 #endif
2258         return;
2259     }
2260     
2261     IntPoint oldPosition = IntPoint(m_scrollOffset);
2262     m_scrollOffset = newScrollOffset;
2263
2264     InspectorInstrumentation::willScrollLayer(&renderer().frame());
2265
2266     RenderView& view = renderer().view();
2267
2268     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
2269     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
2270     bool inLayout = view.frameView().isInLayout();
2271     if (!inLayout) {
2272         // If we're in the middle of layout, we'll just update layers once layout has finished.
2273         updateLayerPositionsAfterOverflowScroll();
2274         // Update regions, scrolling may change the clip of a particular region.
2275 #if ENABLE(DASHBOARD_SUPPORT)
2276         view.frameView().updateAnnotatedRegions();
2277 #endif
2278         view.frameView().updateWidgetPositions();
2279
2280         if (!m_updatingMarqueePosition) {
2281             // Avoid updating compositing layers if, higher on the stack, we're already updating layer
2282             // positions. Updating layer positions requires a full walk of up-to-date RenderLayers, and
2283             // in this case we're still updating their positions; we'll update compositing layers later
2284             // when that completes.
2285             updateCompositingLayersAfterScroll();
2286         }
2287
2288 #if PLATFORM(IOS) && ENABLE(TOUCH_EVENTS)
2289         renderer().document().dirtyTouchEventRects();
2290 #endif
2291     }
2292
2293     Frame& frame = renderer().frame();
2294     RenderLayerModelObject* repaintContainer = renderer().containerForRepaint();
2295     // The caret rect needs to be invalidated after scrolling
2296     frame.selection().setCaretRectNeedsUpdate();
2297
2298     FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_repaintRect);
2299     if (repaintContainer)
2300         quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
2301     frame.eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
2302
2303     bool requiresRepaint = true;
2304     if (compositor().inCompositingMode() && usesCompositedScrolling())
2305         requiresRepaint = false;
2306
2307     // Just schedule a full repaint of our object.
2308     if (requiresRepaint)
2309         renderer().repaintUsingContainer(repaintContainer, m_repaintRect);
2310
2311     // Schedule the scroll and scroll-related DOM events.
2312     if (Element* element = renderer().element()) {
2313         element->document().eventQueue().enqueueOrDispatchScrollEvent(*element);
2314         element->document().sendWillRevealEdgeEventsIfNeeded(oldPosition, IntPoint(newScrollOffset), visibleContentRect(), contentsSize(), element);
2315     }
2316
2317     InspectorInstrumentation::didScrollLayer(&frame);
2318     if (scrollsOverflow())
2319         frame.loader().client().didChangeScrollOffset();
2320
2321     renderer().view().resumePausedImageAnimationsIfNeeded();
2322 }
2323
2324 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView) 
2325 {
2326     // If scrollbars aren't explicitly forbidden, permit scrolling.
2327     if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
2328         return true;
2329
2330     // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
2331     if (frameView->wasScrolledByUser())
2332         return false;
2333
2334     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
2335     // like navigation to an anchor.
2336     return !frameView->frame().eventHandler().autoscrollInProgress();
2337 }
2338
2339 void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
2340 {
2341     RenderLayer* parentLayer = nullptr;
2342     LayoutRect newRect = rect;
2343
2344     // We may end up propagating a scroll event. It is important that we suspend events until 
2345     // the end of the function since they could delete the layer or the layer's renderer().
2346     FrameView& frameView = renderer().view().frameView();
2347
2348     bool restrictedByLineClamp = false;
2349     if (renderer().parent()) {
2350         parentLayer = renderer().parent()->enclosingLayer();
2351         restrictedByLineClamp = !renderer().parent()->style().lineClamp().isNone();
2352     }
2353
2354     if (renderer().hasOverflowClip() && !restrictedByLineClamp) {
2355         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
2356         // This will prevent us from revealing text hidden by the slider in Safari RSS.
2357         RenderBox* box = renderBox();
2358         ASSERT(box);
2359         LayoutRect localExposeRect(box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
2360         LayoutRect layerBounds(0, 0, box->clientWidth(), box->clientHeight());
2361         LayoutRect r = getRectToExpose(layerBounds, layerBounds, localExposeRect, alignX, alignY);
2362
2363         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset() + toIntSize(roundedIntRect(r).location()));
2364         if (clampedScrollOffset != scrollOffset()) {
2365             IntSize oldScrollOffset = scrollOffset();
2366             scrollToOffset(clampedScrollOffset);
2367             IntSize scrollOffsetDifference = scrollOffset() - oldScrollOffset;
2368             localExposeRect.move(-scrollOffsetDifference);
2369             newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
2370         }
2371     } else if (!parentLayer && renderer().isBox() && renderBox()->canBeProgramaticallyScrolled()) {
2372         Element* ownerElement = renderer().document().ownerElement();
2373
2374         if (ownerElement && ownerElement->renderer()) {
2375             HTMLFrameElementBase* frameElementBase = nullptr;
2376
2377             if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
2378                 frameElementBase = toHTMLFrameElementBase(ownerElement);
2379
2380             if (frameElementAndViewPermitScroll(frameElementBase, &frameView)) {
2381                 LayoutRect viewRect = frameView.visibleContentRect(LegacyIOSDocumentVisibleRect);
2382                 LayoutRect exposeRect = getRectToExpose(viewRect, viewRect, rect, alignX, alignY);
2383
2384                 int xOffset = roundToInt(exposeRect.x());
2385                 int yOffset = roundToInt(exposeRect.y());
2386                 // Adjust offsets if they're outside of the allowable range.
2387                 xOffset = std::max(0, std::min(frameView.contentsWidth(), xOffset));
2388                 yOffset = std::max(0, std::min(frameView.contentsHeight(), yOffset));
2389
2390                 frameView.setScrollPosition(IntPoint(xOffset, yOffset));
2391                 if (frameView.safeToPropagateScrollToParent()) {
2392                     parentLayer = ownerElement->renderer()->enclosingLayer();
2393                     // FIXME: This doesn't correctly convert the rect to
2394                     // absolute coordinates in the parent.
2395                     newRect.setX(rect.x() - frameView.scrollX() + frameView.x());
2396                     newRect.setY(rect.y() - frameView.scrollY() + frameView.y());
2397                 } else
2398                     parentLayer = nullptr;
2399             }
2400         } else {
2401 #if !PLATFORM(IOS)
2402             LayoutRect viewRect = frameView.visibleContentRect();
2403             LayoutRect visibleRectRelativeToDocument = viewRect;
2404             IntSize documentScrollOffsetRelativeToScrollableAreaOrigin = frameView.documentScrollOffsetRelativeToScrollableAreaOrigin();
2405             visibleRectRelativeToDocument.setLocation(IntPoint(documentScrollOffsetRelativeToScrollableAreaOrigin.width(), documentScrollOffsetRelativeToScrollableAreaOrigin.height()));
2406 #else
2407             LayoutRect viewRect = frameView.unobscuredContentRect();
2408             LayoutRect visibleRectRelativeToDocument = viewRect;
2409 #endif
2410
2411             LayoutRect r = getRectToExpose(viewRect, visibleRectRelativeToDocument, rect, alignX, alignY);
2412                 
2413             frameView.setScrollPosition(roundedIntPoint(r.location()));
2414
2415             // This is the outermost view of a web page, so after scrolling this view we
2416             // scroll its container by calling Page::scrollRectIntoView.
2417             // This only has an effect on the Mac platform in applications
2418             // that put web views into scrolling containers, such as Mac OS X Mail.
2419             // The canAutoscroll function in EventHandler also knows about this.
2420             if (Page* page = frameView.frame().page())
2421                 page->chrome().scrollRectIntoView(pixelSnappedIntRect(rect));
2422         }
2423     }
2424     
2425     if (renderer().frame().eventHandler().autoscrollInProgress())
2426         parentLayer = enclosingScrollableLayer();
2427
2428     if (parentLayer)
2429         parentLayer->scrollRectToVisible(newRect, alignX, alignY);
2430 }
2431
2432 void RenderLayer::updateCompositingLayersAfterScroll()
2433 {
2434     if (compositor().inCompositingMode()) {
2435         // Our stacking container is guaranteed to contain all of our descendants that may need
2436         // repositioning, so update compositing layers from there.
2437         if (RenderLayer* compositingAncestor = stackingContainer()->enclosingCompositingLayer()) {
2438             if (usesCompositedScrolling() && !hasOutOfFlowPositionedDescendant())
2439                 compositor().updateCompositingLayers(CompositingUpdateOnCompositedScroll, compositingAncestor);
2440             else
2441                 compositor().updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
2442         }
2443     }
2444 }
2445
2446 LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &visibleRectRelativeToDocument, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
2447 {
2448     // Determine the appropriate X behavior.
2449     ScrollBehavior scrollX;
2450     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
2451     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
2452     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
2453         // If the rectangle is fully visible, use the specified visible behavior.
2454         // If the rectangle is partially visible, but over a certain threshold,
2455         // then treat it as fully visible to avoid unnecessary horizontal scrolling
2456         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2457     else if (intersectWidth == visibleRect.width()) {
2458         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
2459         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2460         if (scrollX == alignCenter)
2461             scrollX = noScroll;
2462     } else if (intersectWidth > 0)
2463         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
2464         scrollX = ScrollAlignment::getPartialBehavior(alignX);
2465     else
2466         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
2467     // If we're trying to align to the closest edge, and the exposeRect is further right
2468     // than the visibleRect, and not bigger than the visible area, then align with the right.
2469     if (scrollX == alignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
2470         scrollX = alignRight;
2471
2472     // Given the X behavior, compute the X coordinate.
2473     LayoutUnit x;
2474     if (scrollX == noScroll) 
2475         x = visibleRect.x();
2476     else if (scrollX == alignRight)
2477         x = exposeRect.maxX() - visibleRect.width();
2478     else if (scrollX == alignCenter)
2479         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
2480     else
2481         x = exposeRect.x();
2482
2483     // Determine the appropriate Y behavior.
2484     ScrollBehavior scrollY;
2485     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
2486     LayoutUnit intersectHeight = intersection(visibleRectRelativeToDocument, exposeRectY).height();
2487     if (intersectHeight == exposeRect.height())
2488         // If the rectangle is fully visible, use the specified visible behavior.
2489         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
2490     else if (intersectHeight == visibleRect.height()) {
2491         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
2492         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
2493         if (scrollY == alignCenter)
2494             scrollY = noScroll;
2495     } else if (intersectHeight > 0)
2496         // If the rectangle is partially visible, use the specified partial behavior
2497         scrollY = ScrollAlignment::getPartialBehavior(alignY);
2498     else
2499         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
2500     // If we're trying to align to the closest edge, and the exposeRect is further down
2501     // than the visibleRect, and not bigger than the visible area, then align with the bottom.
2502     if (scrollY == alignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
2503         scrollY = alignBottom;
2504
2505     // Given the Y behavior, compute the Y coordinate.
2506     LayoutUnit y;
2507     if (scrollY == noScroll) 
2508         y = visibleRect.y();
2509     else if (scrollY == alignBottom)
2510         y = exposeRect.maxY() - visibleRect.height();
2511     else if (scrollY == alignCenter)
2512         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
2513     else
2514         y = exposeRect.y();
2515
2516     return LayoutRect(LayoutPoint(x, y), visibleRect.size());
2517 }
2518
2519 void RenderLayer::autoscroll(const IntPoint& position)
2520 {
2521     IntPoint currentDocumentPosition = renderer().view().frameView().windowToContents(position);
2522     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
2523 }
2524
2525 bool RenderLayer::canResize() const
2526 {
2527     // We need a special case for <iframe> because they never have
2528     // hasOverflowClip(). However, they do "implicitly" clip their contents, so
2529     // we want to allow resizing them also.
2530     return (renderer().hasOverflowClip() || renderer().isRenderIFrame()) && renderer().style().resize() != RESIZE_NONE;
2531 }
2532
2533 void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
2534 {
2535     // FIXME: This should be possible on generated content but is not right now.
2536     if (!inResizeMode() || !canResize() || !renderer().element())
2537         return;
2538
2539     // FIXME: The only case where renderer->element()->renderer() != renderer is with continuations. Do they matter here?
2540     // If they do it would still be better to deal with them explicitly.
2541     Element* element = renderer().element();
2542     RenderBox* renderer = toRenderBox(element->renderer());
2543
2544     Document& document = element->document();
2545     if (!document.frame()->eventHandler().mousePressed())
2546         return;
2547
2548     float zoomFactor = renderer->style().effectiveZoom();
2549
2550     LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(evt.position()));
2551     newOffset.setWidth(newOffset.width() / zoomFactor);
2552     newOffset.setHeight(newOffset.height() / zoomFactor);
2553     
2554     LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
2555     LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
2556     element->setMinimumSizeForResizing(minimumSize);
2557     
2558     LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
2559     if (renderer->style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
2560         newOffset.setWidth(-newOffset.width());
2561         adjustedOldOffset.setWidth(-adjustedOldOffset.width());
2562     }
2563     
2564     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
2565
2566     StyledElement* styledElement = toStyledElement(element);
2567     bool isBoxSizingBorder = renderer->style().boxSizing() == BORDER_BOX;
2568
2569     EResize resize = renderer->style().resize();
2570     if (resize != RESIZE_VERTICAL && difference.width()) {
2571         if (element->isFormControlElement()) {
2572             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
2573             styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, renderer->marginLeft() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2574             styledElement->setInlineStyleProperty(CSSPropertyMarginRight, renderer->marginRight() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2575         }
2576         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? LayoutUnit() : renderer->horizontalBorderAndPaddingExtent());
2577         baseWidth = baseWidth / zoomFactor;
2578         styledElement->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSPrimitiveValue::CSS_PX);
2579     }
2580
2581     if (resize != RESIZE_HORIZONTAL && difference.height()) {
2582         if (element->isFormControlElement()) {
2583             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
2584             styledElement->setInlineStyleProperty(CSSPropertyMarginTop, renderer->marginTop() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2585             styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, renderer->marginBottom() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2586         }
2587         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? LayoutUnit() : renderer->verticalBorderAndPaddingExtent());
2588         baseHeight = baseHeight / zoomFactor;
2589         styledElement->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSPrimitiveValue::CSS_PX);
2590     }
2591
2592     document.updateLayout();
2593
2594     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
2595 }
2596
2597 int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
2598 {
2599     Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_hBar : m_vBar).get();
2600     return scrollbar ? (scrollbar->totalSize() - scrollbar->visibleSize()) : 0;
2601 }
2602
2603 void RenderLayer::setScrollOffset(const IntPoint& offset)
2604 {
2605     scrollTo(offset.x(), offset.y());
2606 }
2607
2608 int RenderLayer::scrollPosition(Scrollbar* scrollbar) const
2609 {
2610     if (scrollbar->orientation() == HorizontalScrollbar)
2611         return scrollXOffset();
2612     if (scrollbar->orientation() == VerticalScrollbar)
2613         return scrollYOffset();
2614     return 0;
2615 }
2616
2617 IntPoint RenderLayer::scrollPosition() const
2618 {
2619     return IntPoint(m_scrollOffset);
2620 }
2621
2622 IntPoint RenderLayer::minimumScrollPosition() const
2623 {
2624     return -scrollOrigin();
2625 }
2626
2627 IntPoint RenderLayer::maximumScrollPosition() const
2628 {
2629     // FIXME: m_scrollSize may not be up-to-date if m_scrollDimensionsDirty is true.
2630     return -scrollOrigin() + roundedIntSize(m_scrollSize) - visibleContentRectIncludingScrollbars(ContentsVisibleRect).size();
2631 }
2632
2633 IntRect RenderLayer::visibleContentRectInternal(VisibleContentRectIncludesScrollbars scrollbarInclusion, VisibleContentRectBehavior) const
2634 {
2635     int verticalScrollbarWidth = 0;
2636     int horizontalScrollbarHeight = 0;
2637     if (showsOverflowControls() && scrollbarInclusion == IncludeScrollbars) {
2638         verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
2639         horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
2640     }
2641     
2642     return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
2643                    IntSize(std::max(0, m_layerSize.width() - verticalScrollbarWidth),
2644                            std::max(0, m_layerSize.height() - horizontalScrollbarHeight)));
2645 }
2646
2647 IntSize RenderLayer::overhangAmount() const
2648 {
2649     return IntSize();
2650 }
2651
2652 bool RenderLayer::isActive() const
2653 {
2654     Page* page = renderer().frame().page();
2655     return page && page->focusController().isActive();
2656 }
2657
2658 static int cornerStart(const RenderLayer* layer, int minX, int maxX, int thickness)
2659 {
2660     if (layer->renderer().style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2661         return minX + layer->renderer().style().borderLeftWidth();
2662     return maxX - thickness - layer->renderer().style().borderRightWidth();
2663 }
2664
2665 static LayoutRect cornerRect(const RenderLayer* layer, const LayoutRect& bounds)
2666 {
2667     int horizontalThickness;
2668     int verticalThickness;
2669     if (!layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2670         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
2671         // even when they don't exist in order to set the resizer square size properly.
2672         horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
2673         verticalThickness = horizontalThickness;
2674     } else if (layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2675         horizontalThickness = layer->verticalScrollbar()->width();
2676         verticalThickness = horizontalThickness;
2677     } else if (layer->horizontalScrollbar() && !layer->verticalScrollbar()) {
2678         verticalThickness = layer->horizontalScrollbar()->height();
2679         horizontalThickness = verticalThickness;
2680     } else {
2681         horizontalThickness = layer->verticalScrollbar()->width();
2682         verticalThickness = layer->horizontalScrollbar()->height();
2683     }
2684     return LayoutRect(cornerStart(layer, bounds.x(), bounds.maxX(), horizontalThickness),
2685         bounds.maxY() - verticalThickness - layer->renderer().style().borderBottomWidth(),
2686         horizontalThickness, verticalThickness);
2687 }
2688
2689 IntRect RenderLayer::scrollCornerRect() const
2690 {
2691     // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
2692     // This happens when:
2693     // (a) A resizer is present and at least one scrollbar is present
2694     // (b) Both scrollbars are present.
2695     bool hasHorizontalBar = horizontalScrollbar();
2696     bool hasVerticalBar = verticalScrollbar();
2697     bool hasResizer = renderer().style().resize() != RESIZE_NONE;
2698     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
2699         return pixelSnappedIntRect(cornerRect(this, renderBox()->borderBoxRect()));
2700     return IntRect();
2701 }
2702
2703 static LayoutRect resizerCornerRect(const RenderLayer* layer, const LayoutRect& bounds)
2704 {
2705     ASSERT(layer->renderer().isBox());
2706     if (layer->renderer().style().resize() == RESIZE_NONE)
2707         return LayoutRect();
2708     return cornerRect(layer, bounds);
2709 }
2710
2711 LayoutRect RenderLayer::scrollCornerAndResizerRect() const
2712 {
2713     RenderBox* box = renderBox();
2714     if (!box)
2715         return LayoutRect();
2716     LayoutRect scrollCornerAndResizer = scrollCornerRect();
2717     if (scrollCornerAndResizer.isEmpty())
2718         scrollCornerAndResizer = resizerCornerRect(this, box->borderBoxRect());
2719     return scrollCornerAndResizer;
2720 }
2721
2722 bool RenderLayer::isScrollCornerVisible() const
2723 {
2724     ASSERT(renderer().isBox());
2725     return !scrollCornerRect().isEmpty();
2726 }
2727
2728 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
2729 {
2730     IntRect rect = scrollbarRect;
2731     rect.move(scrollbarOffset(scrollbar));
2732
2733     return renderer().view().frameView().convertFromRendererToContainingView(&renderer(), rect);
2734 }
2735
2736 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
2737 {
2738     IntRect rect = renderer().view().frameView().convertFromContainingViewToRenderer(&renderer(), parentRect);
2739     rect.move(-scrollbarOffset(scrollbar));
2740     return rect;
2741 }
2742
2743 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
2744 {
2745     IntPoint point = scrollbarPoint;
2746     point.move(scrollbarOffset(scrollbar));
2747     return renderer().view().frameView().convertFromRendererToContainingView(&renderer(), point);
2748 }
2749
2750 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
2751 {
2752     IntPoint point = renderer().view().frameView().convertFromContainingViewToRenderer(&renderer(), parentPoint);
2753     point.move(-scrollbarOffset(scrollbar));
2754     return point;
2755 }
2756
2757 IntSize RenderLayer::visibleSize() const
2758 {
2759     if (!renderer().isBox())
2760         return IntSize();
2761
2762     return IntSize(renderBox()->pixelSnappedClientWidth(), renderBox()->pixelSnappedClientHeight());
2763 }
2764
2765 IntSize RenderLayer::contentsSize() const
2766 {
2767     return IntSize(scrollWidth(), scrollHeight());
2768 }
2769
2770 IntSize RenderLayer::scrollableContentsSize() const
2771 {
2772     IntSize contentsSize = this->contentsSize();
2773
2774     if (!hasScrollableHorizontalOverflow())
2775         contentsSize.setWidth(std::min(contentsSize.width(), visibleSize().width()));
2776
2777     if (!hasScrollableVerticalOverflow())
2778         contentsSize.setHeight(std::min(contentsSize.height(), visibleSize().height()));
2779
2780     return contentsSize;
2781 }
2782
2783 bool RenderLayer::shouldSuspendScrollAnimations() const
2784 {
2785     return renderer().view().frameView().shouldSuspendScrollAnimations();
2786 }
2787
2788 #if PLATFORM(IOS)
2789 void RenderLayer::didStartScroll()
2790 {
2791     if (Page* page = renderer().frame().page())
2792         page->chrome().client().didStartOverflowScroll();
2793 }
2794
2795 void RenderLayer::didEndScroll()
2796 {
2797     if (Page* page = renderer().frame().page())
2798         page->chrome().client().didEndOverflowScroll();
2799 }
2800     
2801 void RenderLayer::didUpdateScroll()
2802 {
2803     // Send this notification when we scroll, since this is how we keep selection updated.
2804     if (Page* page = renderer().frame().page())
2805         page->chrome().client().didLayout(ChromeClient::Scroll);
2806 }
2807 #endif
2808
2809 IntPoint RenderLayer::lastKnownMousePosition() const
2810 {
2811     return renderer().frame().eventHandler().lastKnownMousePosition();
2812 }
2813
2814 bool RenderLayer::isHandlingWheelEvent() const
2815 {
2816     return renderer().frame().eventHandler().isHandlingWheelEvent();
2817 }
2818
2819 IntRect RenderLayer::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const
2820 {
2821     if (!m_hBar)
2822         return IntRect();
2823
2824     const RenderBox* box = renderBox();
2825     const IntRect& scrollCorner = scrollCornerRect();
2826
2827     return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
2828         borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
2829         borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
2830         m_hBar->height());
2831 }
2832
2833 IntRect RenderLayer::rectForVerticalScrollbar(const IntRect& borderBoxRect) const
2834 {
2835     if (!m_vBar)
2836         return IntRect();
2837
2838     const RenderBox* box = renderBox();
2839     const IntRect& scrollCorner = scrollCornerRect();
2840
2841     return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
2842         borderBoxRect.y() + box->borderTop(),
2843         m_vBar->width(),
2844         borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
2845 }
2846
2847 LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
2848 {
2849     const RenderBox* box = renderBox();
2850     if (renderer().style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2851         return minX + box->borderLeft();
2852     return maxX - box->borderRight() - m_vBar->width();
2853 }
2854
2855 LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
2856 {
2857     const RenderBox* box = renderBox();
2858     int x = minX + box->borderLeft();
2859     if (renderer().style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2860         x += m_vBar ? m_vBar->width() : roundToInt(resizerCornerRect(this, box->borderBoxRect()).width());
2861     return x;
2862 }
2863
2864 IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
2865 {
2866     RenderBox* box = renderBox();
2867
2868     if (scrollbar == m_vBar.get())
2869         return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
2870
2871     if (scrollbar == m_hBar.get())
2872         return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2873     
2874     ASSERT_NOT_REACHED();
2875     return IntSize();
2876 }
2877
2878 void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
2879 {
2880     if (!showsOverflowControls())
2881         return;
2882
2883     if (scrollbar == m_vBar.get()) {
2884         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2885             layer->setNeedsDisplayInRect(rect);
2886             return;
2887         }
2888     } else {
2889         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2890             layer->setNeedsDisplayInRect(rect);
2891             return;
2892         }
2893     }
2894
2895     IntRect scrollRect = rect;
2896     RenderBox* box = renderBox();
2897     ASSERT(box);
2898     // If we are not yet inserted into the tree, there is no need to repaint.
2899     if (!box->parent())
2900         return;
2901
2902     if (scrollbar == m_vBar.get())
2903         scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
2904     else
2905         scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2906     LayoutRect repaintRect = scrollRect;
2907     renderBox()->flipForWritingMode(repaintRect);
2908     renderer().repaintRectangle(repaintRect);
2909 }
2910
2911 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
2912 {
2913     if (!showsOverflowControls())
2914         return;
2915
2916     if (GraphicsLayer* layer = layerForScrollCorner()) {
2917         layer->setNeedsDisplayInRect(rect);
2918         return;
2919     }
2920
2921     if (m_scrollCorner)
2922         m_scrollCorner->repaintRectangle(rect);
2923     if (m_resizer)
2924         m_resizer->repaintRectangle(rect);
2925 }
2926
2927 static inline RenderElement* rendererForScrollbar(RenderLayerModelObject& renderer)
2928 {
2929     if (Element* element = renderer.element()) {
2930         if (ShadowRoot* shadowRoot = element->containingShadowRoot()) {
2931             if (shadowRoot->type() == ShadowRoot::UserAgentShadowRoot)
2932                 return shadowRoot->hostElement()->renderer();
2933         }
2934     }
2935
2936     return &renderer;
2937 }
2938
2939 PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
2940 {
2941     RefPtr<Scrollbar> widget;
2942     RenderElement* actualRenderer = rendererForScrollbar(renderer());
2943     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style().hasPseudoStyle(SCROLLBAR);
2944     if (hasCustomScrollbarStyle)
2945         widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->element());
2946     else {
2947         widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
2948         didAddScrollbar(widget.get(), orientation);
2949     }
2950     renderer().view().frameView().addChild(widget.get());
2951     return widget.release();
2952 }
2953
2954 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
2955 {
2956     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
2957     if (!scrollbar)
2958         return;
2959
2960     if (!scrollbar->isCustomScrollbar())
2961         willRemoveScrollbar(scrollbar.get(), orientation);
2962
2963     scrollbar->removeFromParent();
2964     scrollbar->disconnectFromScrollableArea();
2965     scrollbar = nullptr;
2966 }
2967
2968 bool RenderLayer::scrollsOverflow() const
2969 {
2970     if (!renderer().isBox())
2971         return false;
2972
2973     return toRenderBox(renderer()).scrollsOverflow();
2974 }
2975
2976 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
2977 {
2978     if (hasScrollbar == hasHorizontalScrollbar())
2979         return;
2980
2981     if (hasScrollbar)
2982         m_hBar = createScrollbar(HorizontalScrollbar);
2983     else
2984         destroyScrollbar(HorizontalScrollbar);
2985
2986     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2987     if (m_hBar)
2988         m_hBar->styleChanged();
2989     if (m_vBar)
2990         m_vBar->styleChanged();
2991
2992     // Force an update since we know the scrollbars have changed things.
2993 #if ENABLE(DASHBOARD_SUPPORT)
2994     if (renderer().document().hasAnnotatedRegions())
2995         renderer().document().setAnnotatedRegionsDirty(true);
2996 #endif
2997 }
2998
2999 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
3000 {
3001     if (hasScrollbar == hasVerticalScrollbar())
3002         return;
3003
3004     if (hasScrollbar)
3005         m_vBar = createScrollbar(VerticalScrollbar);
3006     else
3007         destroyScrollbar(VerticalScrollbar);
3008
3009      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
3010     if (m_hBar)
3011         m_hBar->styleChanged();
3012     if (m_vBar)
3013         m_vBar->styleChanged();
3014
3015     // Force an update since we know the scrollbars have changed things.
3016 #if ENABLE(DASHBOARD_SUPPORT)
3017     if (renderer().document().hasAnnotatedRegions())
3018         renderer().document().setAnnotatedRegionsDirty(true);
3019 #endif
3020 }
3021
3022 ScrollableArea* RenderLayer::enclosingScrollableArea() const
3023 {
3024     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
3025         return scrollableLayer;
3026
3027     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
3028     // if the frame view isn't scrollable.
3029     return 0;
3030 }
3031
3032 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
3033 {
3034     if (!m_vBar
3035         || !showsOverflowControls()
3036         || (m_vBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_vBar->shouldParticipateInHitTesting())))
3037         return 0;
3038
3039     return m_vBar->width();
3040 }
3041
3042 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
3043 {
3044     if (!m_hBar
3045         || !showsOverflowControls()
3046         || (m_hBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_hBar->shouldParticipateInHitTesting())))
3047         return 0;
3048
3049     return m_hBar->height();
3050 }
3051
3052 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
3053 {
3054     // Currently the resize corner is either the bottom right corner or the bottom left corner.
3055     // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
3056     IntSize elementSize = size();
3057     if (renderer().style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
3058         elementSize.setWidth(0);
3059     IntPoint resizerPoint = IntPoint(elementSize);
3060     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
3061     return localPoint - resizerPoint;
3062 }
3063
3064 bool RenderLayer::hasOverflowControls() const
3065 {
3066     return m_hBar || m_vBar || m_scrollCorner || renderer().style().resize() != RESIZE_NONE;
3067 }
3068
3069 void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
3070 {
3071     if (!m_hBar && !m_vBar && !canResize())
3072         return;
3073     
3074     RenderBox* box = renderBox();
3075     if (!box)
3076         return;
3077
3078     const IntRect borderBox = box->pixelSnappedBorderBoxRect();
3079     const IntRect& scrollCorner = scrollCornerRect();
3080     IntRect absBounds(borderBox.location() + offsetFromRoot, borderBox.size());
3081     if (m_vBar) {
3082         IntRect vBarRect = rectForVerticalScrollbar(borderBox);
3083         vBarRect.move(offsetFromRoot);
3084         m_vBar->setFrameRect(vBarRect);
3085     }
3086     
3087     if (m_hBar) {
3088         IntRect hBarRect = rectForHorizontalScrollbar(borderBox);
3089         hBarRect.move(offsetFromRoot);
3090         m_hBar->setFrameRect(hBarRect);
3091     }
3092     
3093     if (m_scrollCorner)
3094         m_scrollCorner->setFrameRect(scrollCorner);
3095     if (m_resizer)
3096         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
3097
3098     if (isComposited())
3099         backing()->positionOverflowControlsLayers();
3100 }
3101
3102 int RenderLayer::scrollWidth() const
3103 {
3104     ASSERT(renderBox());
3105     if (m_scrollDimensionsDirty)
3106         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3107     return snapSizeToPixel(m_scrollSize.width(), renderBox()->clientLeft() + renderBox()->x());
3108 }
3109
3110 int RenderLayer::scrollHeight() const
3111 {
3112     ASSERT(renderBox());
3113     if (m_scrollDimensionsDirty)
3114         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3115     return snapSizeToPixel(m_scrollSize.height(), renderBox()->clientTop() + renderBox()->y());
3116 }
3117
3118 LayoutUnit RenderLayer::overflowTop() const
3119 {
3120     RenderBox* box = renderBox();
3121     LayoutRect overflowRect(box->layoutOverflowRect());
3122     box->flipForWritingMode(overflowRect);
3123     return overflowRect.y();
3124 }
3125
3126 LayoutUnit RenderLayer::overflowBottom() const
3127 {
3128     RenderBox* box = renderBox();
3129     LayoutRect overflowRect(box->layoutOverflowRect());
3130     box->flipForWritingMode(overflowRect);
3131     return overflowRect.maxY();
3132 }
3133
3134 LayoutUnit RenderLayer::overflowLeft() const
3135 {
3136     RenderBox* box = renderBox();
3137     LayoutRect overflowRect(box->layoutOverflowRect());
3138     box->flipForWritingMode(overflowRect);
3139     return overflowRect.x();
3140 }
3141
3142 LayoutUnit RenderLayer::overflowRight() const
3143 {
3144     RenderBox* box = renderBox();
3145     LayoutRect overflowRect(box->layoutOverflowRect());
3146     box->flipForWritingMode(overflowRect);
3147     return overflowRect.maxX();
3148 }
3149
3150 void RenderLayer::computeScrollDimensions()
3151 {
3152     RenderBox* box = renderBox();
3153     ASSERT(box);
3154
3155     m_scrollDimensionsDirty = false;
3156
3157     m_scrollSize.setWidth(overflowRight() - overflowLeft());
3158     m_scrollSize.setHeight(overflowBottom() - overflowTop());
3159
3160     int scrollableLeftOverflow = overflowLeft() - box->borderLeft();
3161     int scrollableTopOverflow = overflowTop() - box->borderTop();
3162     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
3163 }
3164
3165 bool RenderLayer::hasScrollableHorizontalOverflow() const
3166 {
3167     return hasHorizontalOverflow() && renderBox()->scrollsOverflowX();
3168 }
3169
3170 bool RenderLayer::hasScrollableVerticalOverflow() const
3171 {
3172     return hasVerticalOverflow() && renderBox()->scrollsOverflowY();
3173 }
3174
3175 bool RenderLayer::hasHorizontalOverflow() const
3176 {
3177     ASSERT(!m_scrollDimensionsDirty);
3178
3179     return scrollWidth() > renderBox()->pixelSnappedClientWidth();
3180 }
3181
3182 bool RenderLayer::hasVerticalOverflow() const
3183 {
3184     ASSERT(!m_scrollDimensionsDirty);
3185
3186     return scrollHeight() > renderBox()->pixelSnappedClientHeight();
3187 }
3188
3189 void RenderLayer::updateScrollbarsAfterLayout()
3190 {
3191     RenderBox* box = renderBox();
3192     ASSERT(box);
3193
3194     // List box parts handle the scrollbars by themselves so we have nothing to do.
3195     if (box->style().appearance() == ListboxPart)
3196         return;
3197
3198     bool hasHorizontalOverflow = this->hasHorizontalOverflow();
3199     bool hasVerticalOverflow = this->hasVerticalOverflow();
3200
3201     // overflow:scroll should just enable/disable.
3202     if (renderer().style().overflowX() == OSCROLL)
3203         m_hBar->setEnabled(hasHorizontalOverflow);
3204     if (renderer().style().overflowY() == OSCROLL)
3205         m_vBar->setEnabled(hasVerticalOverflow);
3206
3207     // overflow:auto may need to lay out again if scrollbars got added/removed.
3208     bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
3209     bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
3210
3211     if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
3212         if (box->hasAutoHorizontalScrollbar())
3213             setHasHorizontalScrollbar(hasHorizontalOverflow);
3214         if (box->hasAutoVerticalScrollbar())
3215             setHasVerticalScrollbar(hasVerticalOverflow);
3216
3217         updateSelfPaintingLayer();
3218
3219         // Force an update since we know the scrollbars have changed things.
3220 #if ENABLE(DASHBOARD_SUPPORT)
3221         if (renderer().document().hasAnnotatedRegions())
3222             renderer().document().setAnnotatedRegionsDirty(true);
3223 #endif
3224
3225         renderer().repaint();
3226
3227         if (renderer().style().overflowX() == OAUTO || renderer().style().overflowY() == OAUTO) {
3228             if (!m_inOverflowRelayout) {
3229                 // Our proprietary overflow: overlay value doesn't trigger a layout.
3230                 m_inOverflowRelayout = true;
3231                 renderer().setNeedsLayout(MarkOnlyThis);
3232                 if (renderer().isRenderBlock()) {
3233                     RenderBlock& block = toRenderBlock(renderer());
3234                     block.scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
3235                     block.layoutBlock(true);
3236                 } else
3237                     renderer().layout();
3238                 m_inOverflowRelayout = false;
3239             }
3240         }
3241     }
3242
3243     // Set up the range (and page step/line step).
3244     if (m_hBar) {
3245         int clientWidth = box->pixelSnappedClientWidth();
3246         int pageStep = std::max(std::max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
3247         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3248         m_hBar->setProportion(clientWidth, m_scrollSize.width().round());
3249     }
3250     if (m_vBar) {
3251         int clientHeight = box->pixelSnappedClientHeight();
3252         int pageStep = std::max(std::max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
3253         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3254         m_vBar->setProportion(clientHeight, m_scrollSize.height().round());
3255     }
3256
3257     updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
3258 }
3259
3260 void RenderLayer::updateScrollInfoAfterLayout()
3261 {
3262     RenderBox* box = renderBox();
3263     if (!box)
3264         return;
3265
3266     m_scrollDimensionsDirty = true;
3267     IntSize originalScrollOffset = scrollOffset();
3268
3269     computeScrollDimensions();
3270
3271     if (box->style().overflowX() != OMARQUEE) {
3272         // Layout may cause us to be at an invalid scroll position. In this case we need
3273         // to pull our scroll offsets back to the max (or push them up to the min).
3274         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset());
3275 #if PLATFORM(IOS)
3276         // FIXME: This looks wrong. The caret adjust mode should only be enabled on editing related entry points.
3277         // This code was added to fix an issue where the text insertion point would always be drawn on the right edge
3278         // of a text field whose content overflowed its bounds. See <rdar://problem/15579797> for more details.
3279         setAdjustForIOSCaretWhenScrolling(true);
3280 #endif
3281         if (clampedScrollOffset != scrollOffset())
3282             scrollToOffset(clampedScrollOffset);
3283
3284 #if PLATFORM(IOS)
3285         setAdjustForIOSCaretWhenScrolling(false);
3286 #endif
3287     }
3288
3289     updateScrollbarsAfterLayout();
3290
3291     if (originalScrollOffset != scrollOffset())
3292         scrollToOffsetWithoutAnimation(IntPoint(scrollOffset()));
3293
3294     // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
3295     if (compositor().updateLayerCompositingState(*this))
3296         compositor().setCompositingLayersNeedRebuild();
3297 }
3298
3299 bool RenderLayer::overflowControlsIntersectRect(const IntRect& localRect) const
3300 {
3301     const IntRect borderBox = renderBox()->pixelSnappedBorderBoxRect();
3302
3303     if (rectForHorizontalScrollbar(borderBox).intersects(localRect))
3304         return true;
3305
3306     if (rectForVerticalScrollbar(borderBox).intersects(localRect))
3307         return true;
3308
3309     if (scrollCornerRect().intersects(localRect))
3310         return true;
3311     
3312     if (resizerCornerRect(this, borderBox).intersects(localRect))
3313         return true;
3314
3315     return false;
3316 }
3317
3318 bool RenderLayer::showsOverflowControls() const
3319 {
3320 #if PLATFORM(IOS)
3321     // Don't render (custom) scrollbars if we have accelerated scrolling.
3322     if (hasAcceleratedTouchScrolling())
3323         return false;
3324 #endif
3325
3326     return true;
3327 }
3328
3329 void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
3330 {
3331     // Don't do anything if we have no overflow.
3332     if (!renderer().hasOverflowClip())
3333         return;
3334
3335     if (!showsOverflowControls())
3336         return;
3337
3338     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
3339     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
3340     // will be false, and we should just tell the root layer that there are overlay scrollbars
3341     // that need to be painted. That will cause the second pass through the layer tree to run,
3342     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
3343     // second pass doesn't need to re-enter the RenderTree to get it right.
3344     if (hasOverlayScrollbars() && !paintingOverlayControls) {
3345         m_cachedOverlayScrollbarOffset = paintOffset;
3346
3347         // It's not necessary to do the second pass if the scrollbars paint into layers.
3348         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
3349             return;
3350         IntRect localDamgeRect = damageRect;
3351         localDamgeRect.moveBy(-paintOffset);
3352         if (!overflowControlsIntersectRect(localDamgeRect))
3353             return;
3354
3355         RenderLayer* paintingRoot = enclosingCompositingLayer();
3356         if (!paintingRoot)
3357             paintingRoot = renderer().view().layer();
3358
3359         paintingRoot->setContainsDirtyOverlayScrollbars(true);
3360         return;
3361     }
3362
3363     // This check is required to avoid painting custom CSS scrollbars twice.
3364     if (paintingOverlayControls && !hasOverlayScrollbars())
3365         return;
3366
3367     IntPoint adjustedPaintOffset = paintOffset;
3368     if (paintingOverlayControls)
3369         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
3370
3371     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
3372     // widgets can move without layout occurring (most notably when you scroll a document that
3373     // contains fixed positioned elements).
3374     positionOverflowControls(toIntSize(adjustedPaintOffset));
3375
3376     // Now that we're sure the scrollbars are in the right place, paint them.
3377     if (m_hBar && !layerForHorizontalScrollbar())
3378         m_hBar->paint(context, damageRect);
3379     if (m_vBar && !layerForVerticalScrollbar())
3380         m_vBar->paint(context, damageRect);
3381
3382     if (layerForScrollCorner())
3383         return;
3384
3385     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
3386     // edge of the box.
3387     paintScrollCorner(context, adjustedPaintOffset, damageRect);
3388     
3389     // Paint our resizer last, since it sits on top of the scroll corner.
3390     paintResizer(context, adjustedPaintOffset, damageRect);
3391 }
3392
3393 void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
3394 {
3395     RenderBox* box = renderBox();
3396     ASSERT(box);
3397
3398     IntRect absRect = scrollCornerRect();
3399     absRect.moveBy(paintOffset);
3400     if (!absRect.intersects(damageRect))
3401         return;
3402
3403     if (context->updatingControlTints()) {
3404         updateScrollCornerStyle();
3405         return;
3406     }
3407
3408     if (m_scrollCorner) {
3409         m_scrollCorner->paintIntoRect(context, paintOffset, absRect);
3410         return;
3411     }
3412
3413     // We don't want to paint white if we have overlay scrollbars, since we need
3414     // to see what is behind it.
3415     if (!hasOverlayScrollbars())
3416         context->fillRect(absRect, Color::white, box->style().colorSpace());
3417 }
3418
3419 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, const LayoutRect& resizerCornerRect)
3420 {
3421     RefPtr<Image> resizeCornerImage;
3422     FloatSize cornerResizerSize;
3423     if (renderer().document().deviceScaleFactor() >= 2) {
3424         DEPRECATED_DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
3425         resizeCornerImage = resizeCornerImageHiRes;
3426         cornerResizerSize = resizeCornerImage->size();
3427         cornerResizerSize.scale(0.5f);
3428     } else {
3429         DEPRECATED_DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
3430         resizeCornerImage = resizeCornerImageLoRes;
3431         cornerResizerSize = resizeCornerImage->size();
3432     }
3433
3434     if (renderer().style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
3435         context->save();
3436         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
3437         context->scale(FloatSize(-1.0, 1.0));
3438         context->drawImage(resizeCornerImage.get(), renderer().style().colorSpace(), FloatRect(FloatPoint(), cornerResizerSize));
3439         context->restore();
3440         return;
3441     }
3442     FloatRect imageRect = pixelSnappedForPainting(LayoutRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize), renderer().document().deviceScaleFactor());
3443     context->drawImage(resizeCornerImage.get(), renderer().style().colorSpace(), imageRect);
3444 }
3445
3446 void RenderLayer::paintResizer(GraphicsContext* context, const LayoutPoint& paintOffset, const LayoutRect& damageRect)
3447 {
3448     if (renderer().style().resize() == RESIZE_NONE)
3449         return;
3450
3451     RenderBox* box = renderBox();
3452     ASSERT(box);
3453
3454     LayoutRect absRect = resizerCornerRect(this, box->borderBoxRect());
3455     absRect.moveBy(paintOffset);
3456     if (!absRect.intersects(damageRect))
3457         return;
3458
3459     if (context->updatingControlTints()) {
3460         updateResizerStyle();
3461         return;
3462     }
3463     
3464     if (m_resizer) {
3465         m_resizer->paintIntoRect(context, paintOffset, absRect);
3466         return;
3467     }
3468
3469     drawPlatformResizerImage(context, absRect);
3470
3471     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
3472     // Clipping will exclude the right and bottom edges of this frame.
3473     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
3474         GraphicsContextStateSaver stateSaver(*context);
3475         context->clip(absRect);
3476         LayoutRect largerCorner = absRect;
3477         largerCorner.setSize(LayoutSize(largerCorner.width() + LayoutUnit::fromPixel(1), largerCorner.height() + LayoutUnit::fromPixel(1)));
3478         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
3479         context->setStrokeThickness(1.0f);
3480         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
3481         context->drawRect(pixelSnappedIntRect(largerCorner));
3482     }
3483 }
3484
3485 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
3486 {
3487     if (!canResize())
3488         return false;
3489     
3490     RenderBox* box = renderBox();
3491     ASSERT(box);
3492
3493     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
3494
3495     IntRect localBounds(0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
3496     return resizerCornerRect(this, localBounds).contains(localPoint);
3497 }
3498
3499 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
3500 {
3501     if (!m_hBar && !m_vBar && !canResize())
3502         return false;
3503
3504     RenderBox* box = renderBox();
3505     ASSERT(box);
3506     
3507     IntRect resizeControlRect;
3508     if (renderer().style().resize() != RESIZE_NONE) {
3509         resizeControlRect = pixelSnappedIntRect(resizerCornerRect(this, box->borderBoxRect()));
3510         if (resizeControlRect.contains(localPoint))
3511             return true;
3512     }
3513
3514     int resizeControlSize = std::max(resizeControlRect.height(), 0);
3515
3516     // FIXME: We should hit test the m_scrollCorner and pass it back through the result.
3517
3518     if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
3519         LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
3520                             box->borderTop(),
3521                             m_vBar->width(),
3522                             box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
3523         if (vBarRect.contains(localPoint)) {
3524             result.setScrollbar(m_vBar.get());
3525             return true;
3526         }
3527     }
3528
3529     resizeControlSize = std::max(resizeControlRect.width(), 0);
3530     if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
3531         LayoutRect hBarRect(horizontalScrollbarStart(0),
3532                             box->height() - box->borderBottom() - m_hBar->height(),
3533                             box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
3534                             m_hBar->height());
3535         if (hBarRect.contains(localPoint)) {
3536             result.setScrollbar(m_hBar.get());
3537             return true;
3538         }
3539     }
3540
3541     return false;
3542 }
3543
3544 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
3545 {
3546     return ScrollableArea::scroll(direction, granularity, multiplier);
3547 }
3548
3549 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, const LayoutSize& subpixelAccumulation, PaintBehavior paintBehavior, RenderObject* subtreePaintRoot, PaintLayerFlags paintFlags)
3550 {
3551     OverlapTestRequestMap overlapTestRequests;
3552
3553     LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, subpixelAccumulation, subtreePaintRoot, &overlapTestRequests);
3554     paintLayer(context, paintingInfo, paintFlags);
3555
3556     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
3557     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
3558         it->key->setOverlapTestResult(false);
3559 }
3560
3561 void RenderLayer::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* subtreePaintRoot)
3562 {
3563     if (!m_containsDirtyOverlayScrollbars)
3564         return;
3565
3566     LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, LayoutSize(), subtreePaintRoot);
3567     paintLayer(context, paintingInfo, PaintLayerPaintingOverlayScrollbars);
3568
3569     m_containsDirtyOverlayScrollbars = false;
3570 }
3571
3572 static bool inContainingBlockChain(RenderLayer* startLayer, RenderLayer* endLayer)
3573 {
3574     if (startLayer == endLayer)
3575         return true;
3576     
3577     RenderView* view = &startLayer->renderer().view();
3578     for (RenderBlock* currentBlock = startLayer->renderer().containingBlock(); currentBlock && currentBlock != view; currentBlock = currentBlock->containingBlock()) {
3579         if (currentBlock->layer() == endLayer)
3580             return true;
3581     }
3582     
3583     return false;
3584 }
3585
3586 void RenderLayer::clipToRect(const LayerPaintingInfo& paintingInfo, GraphicsContext* context, const ClipRect& clipRect, BorderRadiusClippingRule rule)
3587 {
3588     float deviceScaleFactor = renderer().document().deviceScaleFactor();
3589     if (clipRect.hasRadius()) {
3590         context->save();
3591         
3592         // If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
3593         // any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
3594         // containing block chain so we check that also.
3595         for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
3596             if (layer->renderer().hasOverflowClip() && layer->renderer().style().hasBorderRadius() && inContainingBlockChain(this, layer)) {
3597                 LayoutRect adjustedClipRect = LayoutRect(toLayoutPoint(layer->offsetFromAncestor(paintingInfo.rootLayer)), layer->size());
3598                 adjustedClipRect.move(paintingInfo.subpixelAccumulation);
3599                 context->clipRoundedRect(layer->renderer().style().getRoundedInnerBorderFor(adjustedClipRect).pixelSnappedRoundedRectForPainting(deviceScaleFactor));
3600             }
3601             
3602             if (layer == paintingInfo.rootLayer)
3603                 break;
3604         }
3605     } else if (clipRect.rect() != paintingInfo.paintDirtyRect) {
3606         context->save();
3607         LayoutRect adjustedClipRect = clipRect.rect();
3608         adjustedClipRect.move(paintingInfo.subpixelAccumulation);
3609         context->clip(pixelSnappedForPainting(adjustedClipRect, deviceScaleFactor));
3610     }
3611 }
3612
3613 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
3614 {
3615     if (clipRect.rect() != paintDirtyRect || clipRect.hasRadius())
3616         context->restore();
3617 }
3618
3619 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
3620 {
3621     Vector<OverlapTestRequestClient*> overlappedRequestClients;
3622     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
3623     LayoutRect boundingBox = layer->boundingBox(rootLayer, layer->offsetFromAncestor(rootLayer));
3624     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
3625         if (!boundingBox.intersects(it->value))
3626             continue;
3627
3628         it->key->setOverlapTestResult(true);
3629         overlappedRequestClients.append(it->key);
3630     }
3631     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
3632         overlapTestRequests.remove(overlappedRequestClients[i]);
3633 }
3634
3635 static inline bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
3636 {
3637     return paintingReflection && !layer->has3DTransform();
3638 }
3639     
3640 static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
3641 {
3642     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
3643     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
3644     // will do a full repaint().
3645     if (layer->renderer().document().didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer().isRoot())
3646         return true;
3647
3648     // Avoid painting all layers if the document is in a state where visual updates aren't allowed.
3649     // A full repaint will occur in Document::implicitClose() if painting is suppressed here.
3650     if (!layer->renderer().document().visualUpdatesAllowed())
3651         return true;
3652
3653     return false;
3654 }
3655
3656 static inline bool paintForFixedRootBackground(const RenderLayer* layer, RenderLayer::PaintLayerFlags paintFlags)
3657 {
3658     return layer->renderer().isRoot() && (paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
3659 }
3660
3661 void RenderLayer::paintLayer(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3662 {
3663     if (isComposited()) {
3664         // The updatingControlTints() painting pass goes through compositing layers,
3665         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
3666         if (context->updatingControlTints() || (paintingInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers))
3667             paintFlags |= PaintLayerTemporaryClipRects;
3668         else if (!backing()->paintsIntoWindow()
3669             && !backing()->paintsIntoCompositedAncestor()
3670             && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)
3671             && !paintForFixedRootBackground(this, paintFlags)) {
3672             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
3673             return;
3674         }
3675     } else if (viewportConstrainedNotCompositedReason() == NotCompositedForBoundsOutOfView) {
3676         // Don't paint out-of-view viewport constrained layers (when doing prepainting) because they will never be visible
3677         // unless their position or viewport size is changed.
3678         ASSERT(renderer().style().position() == FixedPosition);
3679         return;
3680     }
3681
3682     // Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
3683     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
3684         return;
3685
3686     if (shouldSuppressPaintingLayer(this))
3687         return;
3688     
3689     // If this layer is totally invisible then there is nothing to paint.
3690     if (!renderer().opacity())
3691         return;
3692
3693     // Don't paint the layer if the renderer doesn't belong to this region.
3694     // This is true as long as we clamp the range of a box to its containing block range.
3695
3696     // Disable named flow region information for in flow threads such as multi-col.
3697     std::unique_ptr<CurrentRenderFlowThreadDisabler> flowThreadDisabler;
3698     if (enclosingPaginationLayer(ExcludeCompositedPaginatedLayers))
3699         flowThreadDisabler = std::make_unique<CurrentRenderFlowThreadDisabler>(&renderer().view());
3700
3701     RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
3702     if (namedFlowFragment) {
3703         ASSERT(namedFlowFragment->isValid());
3704         if (!namedFlowFragment->flowThread()->objectShouldFragmentInFlowRegion(&renderer(), namedFlowFragment))
3705             return;
3706     }
3707
3708     if (paintsWithTransparency(paintingInfo.paintBehavior))
3709         paintFlags |= PaintLayerHaveTransparency;
3710
3711     // PaintLayerAppliedTransform is used in RenderReplica, to avoid applying the transform twice.
3712     if (paintsWithTransform(paintingInfo.paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
3713         TransformationMatrix layerTransform = renderableTransform(paintingInfo.paintBehavior);
3714         // If the transform can't be inverted, then don't paint anything.
3715         if (!layerTransform.isInvertible())
3716             return;
3717
3718         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
3719         // layer from the parent now, assuming there is a parent
3720         if (paintFlags & PaintLayerHaveTransparency) {
3721             if (parent())
3722                 parent()->beginTransparencyLayers(context, paintingInfo, paintingInfo.paintDirtyRect);
3723             else
3724                 beginTransparencyLayers(context, paintingInfo, paintingInfo.paintDirtyRect);
3725         }
3726
3727         if (enclosingPaginationLayer(ExcludeCompositedPaginatedLayers)) {
3728             paintTransformedLayerIntoFragments(context, paintingInfo, paintFlags);
3729             return;
3730         }
3731
3732         // Make sure the parent's clip rects have been calculated.
3733         ClipRect clipRect = paintingInfo.paintDirtyRect;
3734         if (parent()) {
3735             ClipRectsContext clipRectsContext(paintingInfo.rootLayer, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
3736                 IgnoreOverlayScrollbarSize, (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip);
3737             clipRect = backgroundClipRect(clipRectsContext);
3738             clipRect.intersect(paintingInfo.paintDirtyRect);
3739         
3740             // Push the parent coordinate space's clip.
3741             parent()->clipToRect(paintingInfo, context, clipRect);
3742         }
3743
3744         paintLayerByApplyingTransform(context, paintingInfo, paintFlags);
3745
3746         // Restore the clip.
3747         if (parent())
3748             parent()->restoreClip(context, paintingInfo.paintDirtyRect, clipRect);
3749
3750         return;
3751     }
3752     
3753     paintLayerContentsAndReflection(context, paintingInfo, paintFlags);
3754 }
3755
3756 void RenderLayer::paintLayerContentsAndReflection(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3757 {
3758     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3759
3760     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3761
3762     // Paint the reflection first if we have one.
3763     if (m_reflection && !m_paintingInsideReflection) {
3764         // Mark that we are now inside replica painting.
3765         m_paintingInsideReflection = true;
3766         reflectionLayer()->paintLayer(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
3767         m_paintingInsideReflection = false;
3768     }
3769
3770     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
3771     paintLayerContents(context, paintingInfo, localPaintFlags);
3772 }
3773
3774 bool RenderLayer::setupFontSubpixelQuantization(GraphicsContext* context, bool& didQuantizeFonts)
3775 {
3776     if (context->paintingDisabled())
3777         return false;
3778
3779     bool scrollingOnMainThread = true;
3780 #if ENABLE(ASYNC_SCROLLING)
3781     if (Page* page = renderer().frame().page()) {
3782         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3783             scrollingOnMainThread = scrollingCoordinator->shouldUpdateScrollLayerPositionSynchronously();
3784     }
3785 #endif
3786
3787     // FIXME: We shouldn't have to disable subpixel quantization for overflow clips or subframes once we scroll those
3788     // things on the scrolling thread.
3789     bool contentsScrollByPainting = (renderer().hasOverflowClip() && !usesCompositedScrolling()) || (renderer().frame().ownerElement());
3790     bool isZooming = false;
3791     if (Page* page = renderer().frame().page())
3792         isZooming = !page->chrome().client().hasStablePageScaleFactor();
3793     if (scrollingOnMainThread || contentsScrollByPainting || isZooming) {
3794         didQuantizeFonts = context->shouldSubpixelQuantizeFonts();
3795         context->setShouldSubpixelQuantizeFonts(false);
3796         return true;
3797     }
3798     return false;
3799 }
3800
3801 template <class ReferenceBoxClipPathOperation>
3802 static inline LayoutRect computeReferenceBox(const RenderObject& renderer, const ReferenceBoxClipPathOperation& clippingPath, const LayoutSize& offsetFromRoot, const LayoutRect& rootRelativeBounds)
3803 {
3804     // FIXME: Support different reference boxes for inline content.
3805     // https://bugs.webkit.org/show_bug.cgi?id=129047
3806     if (!renderer.isBox())
3807         return rootRelativeBounds;
3808
3809     LayoutRect referenceBox;
3810     const RenderBox& box = toRenderBox(renderer);
3811     switch (clippingPath.referenceBox()) {
3812     case ContentBox:
3813         referenceBox = box.contentBoxRect();
3814         referenceBox.move(offsetFromRoot);
3815         break;
3816     case PaddingBox:
3817         referenceBox = box.paddingBoxRect();
3818         referenceBox.move(offsetFromRoot);
3819         break;
3820     // FIXME: Support margin-box. Use bounding client rect for now.
3821     // https://bugs.webkit.org/show_bug.cgi?id=127984
3822     case MarginBox:
3823     // fill, stroke, view-box compute to border-box for HTML elements.
3824     case Fill:
3825     case Stroke:
3826     case ViewBox:
3827     case BorderBox:
3828     case BoxMissing:
3829         referenceBox = box.borderBoxRect();
3830         referenceBox.move(offsetFromRoot);
3831         break;
3832     }
3833
3834     return referenceBox;
3835 }
3836
3837 bool RenderLayer::setupClipPath(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, const LayoutSize& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed)
3838 {
3839     if (!renderer().hasClipPath() || context->paintingDisabled())
3840         return false;
3841
3842     if (!rootRelativeBoundsComputed) {
3843         rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, offsetFromRoot, 0);
3844         rootRelativeBoundsComputed = true;
3845     }
3846
3847     RenderStyle& style = renderer().style();
3848     ASSERT(style.clipPath());
3849     if (style.clipPath()->type() == ClipPathOperation::Shape) {
3850         ShapeClipPathOperation& clippingPath = toShapeClipPathOperation(*(style.clipPath()));
3851
3852         LayoutRect referenceBox = computeReferenceBox(renderer(), clippingPath, offsetFromRoot, rootRelativeBounds);
3853         context->save();
3854         context->clipPath(clippingPath.pathForReferenceRect(referenceBox), clippingPath.windRule());
3855         return true;
3856     }
3857
3858     if (style.clipPath()->type() == ClipPathOperation::Box && renderer().isBox()) {
3859         BoxClipPathOperation& clippingPath = toBoxClipPathOperation(*(style.clipPath()));
3860
3861         RoundedRect shapeRect = computeRoundedRectForBoxShape(clippingPath.referenceBox(), toRenderBox(renderer()));
3862         shapeRect.move(offsetFromRoot);
3863
3864         context->save();
3865         context->clipPath(clippingPath.pathForReferenceRect(shapeRect), RULE_NONZERO);
3866         return true;
3867     }
3868
3869     if (style.clipPath()->type() == ClipPathOperation::Reference) {
3870         ReferenceClipPathOperation* referenceClipPathOperation = static_cast<ReferenceClipPathOperation*>(style.clipPath());
3871         Element* element = renderer().document().getElementById(referenceClipPathOperation->fragment());
3872         if (element && element->hasTagName(SVGNames::clipPathTag) && element->renderer()) {
3873             // FIXME: This should use a safer cast such as toRenderSVGResourceContainer().
3874             // FIXME: Should this do a context->save() and return true so we restore the context?
3875             static_cast<RenderSVGResourceClipper*>(element->renderer())->applyClippingToContext(renderer(), rootRelativeBounds, paintingInfo.paintDirtyRect, context);
3876         }
3877     }
3878
3879     return false;
3880 }
3881
3882 #if ENABLE(CSS_FILTERS)
3883
3884 std::unique_ptr<FilterEffectRendererHelper> RenderLayer::setupFilters(GraphicsContext* context, LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags, const LayoutSize& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed)
3885 {
3886     if (context->paintingDisabled())
3887         return nullptr;
3888
3889     if (paintFlags & PaintLayerPaintingOverlayScrollbars)
3890         return nullptr;
3891
3892     FilterInfo* filterInfo = FilterInfo::getIfExists(*this);
3893     bool hasPaintedFilter = filterInfo && filterInfo->renderer() && paintsWithFilters();
3894     if (!hasPaintedFilter)
3895         return nullptr;
3896
3897     auto filterPainter = std::make_unique<FilterEffectRendererHelper>(hasPaintedFilter);
3898     if (!filterPainter->haveFilterEffect())
3899         return nullptr;
3900     
3901     LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
3902     filterRepaintRect.move(offsetFromRoot);
3903
3904     if (!rootRelativeBoundsComputed) {
3905         rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, offsetFromRoot, 0);
3906         rootRelativeBoundsComputed = true;
3907     }
3908
3909     if (filterPainter->prepareFilterEffect(this, enclosingIntRect(rootRelativeBounds), enclosingIntRect(paintingInfo.paintDirtyRect), enclosingIntRect(filterRepaintRect))) {
3910         // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
3911         filterInfo->resetDirtySourceRect();
3912
3913         if (!filterPainter->beginFilterEffect())
3914             return nullptr;
3915
3916         // Check that we didn't fail to allocate the graphics context for the offscreen buffer.
3917         ASSERT(filterPainter->hasStartedFilterEffect());
3918
3919         paintingInfo.paintDirtyRect = filterPainter->repaintRect();
3920         // If the filter needs the full source image, we need to avoid using the clip rectangles.
3921         // Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
3922         // Note that we will still apply the clipping on the final rendering of the filter.
3923         paintingInfo.clipToDirtyRect = !filterInfo->renderer()->hasFilterThatMovesPixels();
3924         return filterPainter;
3925     }
3926     return nullptr;
3927 }
3928
3929 GraphicsContext* RenderLayer::applyFilters(FilterEffectRendererHelper* filterPainter, GraphicsContext* originalContext, LayerPaintingInfo& paintingInfo, LayerFragments& layerFragments)
3930 {
3931     ASSERT(filterPainter->hasStartedFilterEffect());
3932     // Apply the correct clipping (ie. overflow: hidden).
3933     // FIXME: It is incorrect to just clip to the damageRect here once multiple fragments are involved.
3934     ClipRect backgroundRect = layerFragments.isEmpty() ? ClipRect() : layerFragments[0].backgroundRect;
3935     clipToRect(paintingInfo, originalContext, backgroundRect);
3936     filterPainter->applyFilterEffect(originalContext);
3937     restoreClip(originalContext, paintingInfo.paintDirtyRect, backgroundRect);
3938     return originalContext;
3939 }
3940
3941 #endif
3942
3943 // Helper for the sorting of layers by z-index.
3944 static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
3945 {
3946     return first->zIndex() < second->zIndex();
3947 }
3948
3949 // Paint the layers associated with the fixed positioned elements in named flows.
3950 // These layers should not be painted in a similar way as the other elements collected in
3951 // named flows - regions -> named flows - since we do not want them to be clipped to the
3952 // regions viewport.
3953 void RenderLayer::paintFixedLayersInNamedFlows(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3954 {
3955     if (!isRootLayer())
3956         return;
3957
3958     // Get the named flows for the view
3959     if (!renderer().view().hasRenderNamedFlowThreads())
3960         return;
3961
3962     // Ensure the flow threads hierarchy