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