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