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