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