6e44d5e9e7ace4d1e789471c68b910503e71da45
[WebKit-https.git] / Source / WebCore / rendering / RenderLayer.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
3  *
4  * Portions are Copyright (C) 1998 Netscape Communications Corporation.
5  *
6  * Other contributors:
7  *   Robert O'Callahan <roc+@cs.cmu.edu>
8  *   David Baron <dbaron@fas.harvard.edu>
9  *   Christian Biesinger <cbiesinger@web.de>
10  *   Randall Jesup <rjesup@wgate.com>
11  *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
12  *   Josh Soref <timeless@mac.com>
13  *   Boris Zbarsky <bzbarsky@mit.edu>
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28  *
29  * Alternatively, the contents of this file may be used under the terms
30  * of either the Mozilla Public License Version 1.1, found at
31  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
32  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
33  * (the "GPL"), in which case the provisions of the MPL or the GPL are
34  * applicable instead of those above.  If you wish to allow use of your
35  * version of this file only under the terms of one of those two
36  * licenses (the MPL or the GPL) and not to allow others to use your
37  * version of this file under the LGPL, indicate your decision by
38  * deletingthe provisions above and replace them with the notice and
39  * other provisions required by the MPL or the GPL, as the case may be.
40  * If you do not delete the provisions above, a recipient may use your
41  * version of this file under any of the LGPL, the MPL or the GPL.
42  */
43
44 #include "config.h"
45 #include "RenderLayer.h"
46
47 #include "AnimationController.h"
48 #include "ColumnInfo.h"
49 #include "CSSPropertyNames.h"
50 #include "Chrome.h"
51 #include "Document.h"
52 #include "DocumentEventQueue.h"
53 #include "Element.h"
54 #include "EventHandler.h"
55 #include "FeatureObserver.h"
56 #include "FloatConversion.h"
57 #include "FloatPoint3D.h"
58 #include "FloatRect.h"
59 #include "FlowThreadController.h"
60 #include "FocusController.h"
61 #include "Frame.h"
62 #include "FrameLoader.h"
63 #include "FrameLoaderClient.h"
64 #include "FrameSelection.h"
65 #include "FrameTree.h"
66 #include "FrameView.h"
67 #include "Gradient.h"
68 #include "GraphicsContext.h"
69 #include "HTMLFrameElement.h"
70 #include "HTMLFrameOwnerElement.h"
71 #include "HTMLNames.h"
72 #include "HistogramSupport.h"
73 #include "HitTestingTransformState.h"
74 #include "HitTestRequest.h"
75 #include "HitTestResult.h"
76 #include "InspectorInstrumentation.h"
77 #include "OverflowEvent.h"
78 #include "OverlapTestRequestClient.h"
79 #include "Page.h"
80 #include "PlatformMouseEvent.h"
81 #include "RenderArena.h"
82 #include "RenderFlowThread.h"
83 #include "RenderGeometryMap.h"
84 #include "RenderInline.h"
85 #include "RenderMarquee.h"
86 #include "RenderNamedFlowThread.h"
87 #include "RenderReplica.h"
88 #include "RenderSVGResourceClipper.h"
89 #include "RenderScrollbar.h"
90 #include "RenderScrollbarPart.h"
91 #include "RenderTableCell.h"
92 #include "RenderTableRow.h"
93 #include "RenderTheme.h"
94 #include "RenderTreeAsText.h"
95 #include "RenderView.h"
96 #include "ScaleTransformOperation.h"
97 #include "ScrollAnimator.h"
98 #include "Scrollbar.h"
99 #include "ScrollbarTheme.h"
100 #include "ScrollingCoordinator.h"
101 #include "Settings.h"
102 #include "ShadowRoot.h"
103 #include "SourceGraphic.h"
104 #include "StylePropertySet.h"
105 #include "StyleResolver.h"
106 #include "TextStream.h"
107 #include "TransformationMatrix.h"
108 #include "TranslateTransformOperation.h"
109 #include <wtf/StdLibExtras.h>
110 #include <wtf/text/CString.h>
111
112 #if ENABLE(CSS_FILTERS)
113 #include "FEColorMatrix.h"
114 #include "FEMerge.h"
115 #include "FilterEffectRenderer.h"
116 #include "RenderLayerFilterInfo.h"
117 #endif
118
119 #if USE(ACCELERATED_COMPOSITING)
120 #include "RenderLayerBacking.h"
121 #include "RenderLayerCompositor.h"
122 #endif
123
124 #if ENABLE(SVG)
125 #include "SVGNames.h"
126 #endif
127
128 #if ENABLE(CSS_SHADERS) && USE(3D_GRAPHICS)
129 #include "CustomFilterGlobalContext.h"
130 #include "CustomFilterOperation.h"
131 #include "CustomFilterValidatedProgram.h"
132 #include "ValidatedCustomFilterOperation.h"
133 #endif
134
135 #define MIN_INTERSECT_FOR_REVEAL 32
136
137 using namespace std;
138
139 namespace WebCore {
140
141 using namespace HTMLNames;
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                 RenderObject* child;
1142                 if (!r->hasLayer() && (child = r->firstChildSlow()))
1143                     r = child;
1144                 else if (r->nextSibling())
1145                     r = r->nextSibling();
1146                 else {
1147                     do {
1148                         r = r->parent();
1149                         if (r == &renderer())
1150                             r = 0;
1151                     } while (r && !r->nextSibling());
1152                     if (r)
1153                         r = r->nextSibling();
1154                 }
1155             }
1156         }    
1157         m_visibleContentStatusDirty = false; 
1158     }
1159 }
1160
1161 #if USE(ACCELERATED_COMPOSITING)
1162 // Return true if clipping change requires layer update.
1163 bool RenderLayer::updateDescendantClippingContext(bool addClipping)
1164 {
1165     bool layerNeedsRebuild = false;
1166     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
1167         RenderLayerBacking* backing = child->backing();
1168         // Update layer context when new clipping is added or existing clipping is removed.
1169         if (backing && (addClipping || backing->hasAncestorClippingLayer())) {
1170             if (backing->updateAncestorClippingLayer(compositor().clippedByAncestor(*child)))
1171                 layerNeedsRebuild = true;
1172         }
1173
1174         if (child->updateDescendantClippingContext(addClipping))
1175             layerNeedsRebuild = true;
1176     }
1177     return layerNeedsRebuild;
1178 }
1179 #endif
1180
1181 void RenderLayer::dirty3DTransformedDescendantStatus()
1182 {
1183     RenderLayer* curr = stackingContainer();
1184     if (curr)
1185         curr->m_3DTransformedDescendantStatusDirty = true;
1186         
1187     // This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
1188     // Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
1189     while (curr && curr->preserves3D()) {
1190         curr->m_3DTransformedDescendantStatusDirty = true;
1191         curr = curr->stackingContainer();
1192     }
1193 }
1194
1195 // Return true if this layer or any preserve-3d descendants have 3d.
1196 bool RenderLayer::update3DTransformedDescendantStatus()
1197 {
1198     if (m_3DTransformedDescendantStatusDirty) {
1199         m_has3DTransformedDescendant = false;
1200
1201         updateZOrderLists();
1202
1203         // Transformed or preserve-3d descendants can only be in the z-order lists, not
1204         // in the normal flow list, so we only need to check those.
1205         if (Vector<RenderLayer*>* positiveZOrderList = posZOrderList()) {
1206             for (unsigned i = 0; i < positiveZOrderList->size(); ++i)
1207                 m_has3DTransformedDescendant |= positiveZOrderList->at(i)->update3DTransformedDescendantStatus();
1208         }
1209
1210         // Now check our negative z-index children.
1211         if (Vector<RenderLayer*>* negativeZOrderList = negZOrderList()) {
1212             for (unsigned i = 0; i < negativeZOrderList->size(); ++i)
1213                 m_has3DTransformedDescendant |= negativeZOrderList->at(i)->update3DTransformedDescendantStatus();
1214         }
1215         
1216         m_3DTransformedDescendantStatusDirty = false;
1217     }
1218     
1219     // If we live in a 3d hierarchy, then the layer at the root of that hierarchy needs
1220     // the m_has3DTransformedDescendant set.
1221     if (preserves3D())
1222         return has3DTransform() || m_has3DTransformedDescendant;
1223
1224     return has3DTransform();
1225 }
1226
1227 bool RenderLayer::updateLayerPosition()
1228 {
1229     LayoutPoint localPoint;
1230     LayoutSize inlineBoundingBoxOffset; // We don't put this into the RenderLayer x/y for inlines, so we need to subtract it out when done.
1231     if (renderer().isInline() && renderer().isRenderInline()) {
1232         RenderInline& inlineFlow = toRenderInline(renderer());
1233         IntRect lineBox = inlineFlow.linesBoundingBox();
1234         setSize(lineBox.size());
1235         inlineBoundingBoxOffset = toSize(lineBox.location());
1236         localPoint += inlineBoundingBoxOffset;
1237     } else if (RenderBox* box = renderBox()) {
1238         // FIXME: Is snapping the size really needed here for the RenderBox case?
1239         setSize(pixelSnappedIntSize(box->size(), box->location()));
1240         localPoint += box->topLeftLocationOffset();
1241     }
1242
1243     if (!renderer().isOutOfFlowPositioned() && renderer().parent()) {
1244         // We must adjust our position by walking up the render tree looking for the
1245         // nearest enclosing object with a layer.
1246         RenderElement* curr = renderer().parent();
1247         while (curr && !curr->hasLayer()) {
1248             if (curr->isBox() && !curr->isTableRow()) {
1249                 // Rows and cells share the same coordinate space (that of the section).
1250                 // Omit them when computing our xpos/ypos.
1251                 localPoint += toRenderBox(curr)->topLeftLocationOffset();
1252             }
1253             curr = curr->parent();
1254         }
1255         if (curr->isBox() && curr->isTableRow()) {
1256             // Put ourselves into the row coordinate space.
1257             localPoint -= toRenderBox(curr)->topLeftLocationOffset();
1258         }
1259     }
1260     
1261     // Subtract our parent's scroll offset.
1262     if (renderer().isOutOfFlowPositioned() && enclosingPositionedAncestor()) {
1263         RenderLayer* positionedParent = enclosingPositionedAncestor();
1264
1265         // For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
1266         if (positionedParent->renderer().hasOverflowClip()) {
1267             LayoutSize offset = positionedParent->scrolledContentOffset();
1268             localPoint -= offset;
1269         }
1270         
1271         if (renderer().isOutOfFlowPositioned() && positionedParent->renderer().isInFlowPositioned() && positionedParent->renderer().isRenderInline()) {
1272             LayoutSize offset = toRenderInline(positionedParent->renderer()).offsetForInFlowPositionedInline(&toRenderBox(renderer()));
1273             localPoint += offset;
1274         }
1275     } else if (parent()) {
1276         if (parent()->renderer().hasOverflowClip()) {
1277             IntSize scrollOffset = parent()->scrolledContentOffset();
1278             localPoint -= scrollOffset;
1279         }
1280     }
1281     
1282     bool positionOrOffsetChanged = false;
1283     if (renderer().isInFlowPositioned()) {
1284         LayoutSize newOffset = toRenderBoxModelObject(renderer()).offsetForInFlowPosition();
1285         positionOrOffsetChanged = newOffset != m_offsetForInFlowPosition;
1286         m_offsetForInFlowPosition = newOffset;
1287         localPoint.move(m_offsetForInFlowPosition);
1288     } else {
1289         m_offsetForInFlowPosition = LayoutSize();
1290     }
1291
1292     // FIXME: We'd really like to just get rid of the concept of a layer rectangle and rely on the renderers.
1293     localPoint -= inlineBoundingBoxOffset;
1294     
1295     positionOrOffsetChanged |= location() != localPoint;
1296     setLocation(localPoint);
1297     return positionOrOffsetChanged;
1298 }
1299
1300 TransformationMatrix RenderLayer::perspectiveTransform() const
1301 {
1302     if (!renderer().hasTransform())
1303         return TransformationMatrix();
1304
1305     RenderStyle* style = renderer().style();
1306     if (!style->hasPerspective())
1307         return TransformationMatrix();
1308
1309     // Maybe fetch the perspective from the backing?
1310     const IntRect borderBox = toRenderBox(renderer()).pixelSnappedBorderBoxRect();
1311     const float boxWidth = borderBox.width();
1312     const float boxHeight = borderBox.height();
1313
1314     float perspectiveOriginX = floatValueForLength(style->perspectiveOriginX(), boxWidth);
1315     float perspectiveOriginY = floatValueForLength(style->perspectiveOriginY(), boxHeight);
1316
1317     // A perspective origin of 0,0 makes the vanishing point in the center of the element.
1318     // We want it to be in the top-left, so subtract half the height and width.
1319     perspectiveOriginX -= boxWidth / 2.0f;
1320     perspectiveOriginY -= boxHeight / 2.0f;
1321     
1322     TransformationMatrix t;
1323     t.translate(perspectiveOriginX, perspectiveOriginY);
1324     t.applyPerspective(style->perspective());
1325     t.translate(-perspectiveOriginX, -perspectiveOriginY);
1326     
1327     return t;
1328 }
1329
1330 FloatPoint RenderLayer::perspectiveOrigin() const
1331 {
1332     if (!renderer().hasTransform())
1333         return FloatPoint();
1334
1335     const LayoutRect borderBox = toRenderBox(renderer()).borderBoxRect();
1336     RenderStyle* style = renderer().style();
1337
1338     return FloatPoint(floatValueForLength(style->perspectiveOriginX(), borderBox.width()),
1339                       floatValueForLength(style->perspectiveOriginY(), borderBox.height()));
1340 }
1341
1342 RenderLayer* RenderLayer::stackingContainer() const
1343 {
1344     RenderLayer* layer = parent();
1345     while (layer && !layer->isStackingContainer())
1346         layer = layer->parent();
1347
1348     ASSERT(!layer || layer->isStackingContainer());
1349     return layer;
1350 }
1351
1352 static inline bool isPositionedContainer(RenderLayer* layer)
1353 {
1354     return layer->isRootLayer() || layer->renderer().isPositioned() || layer->hasTransform();
1355 }
1356
1357 static inline bool isFixedPositionedContainer(RenderLayer* layer)
1358 {
1359     return layer->isRootLayer() || layer->hasTransform();
1360 }
1361
1362 RenderLayer* RenderLayer::enclosingPositionedAncestor() const
1363 {
1364     RenderLayer* curr = parent();
1365     while (curr && !isPositionedContainer(curr))
1366         curr = curr->parent();
1367
1368     return curr;
1369 }
1370
1371 static RenderLayer* parentLayerCrossFrame(const RenderLayer* layer)
1372 {
1373     ASSERT(layer);
1374     if (layer->parent())
1375         return layer->parent();
1376
1377     HTMLFrameOwnerElement* ownerElement = layer->renderer().document().ownerElement();
1378     if (!ownerElement)
1379         return 0;
1380
1381     RenderElement* ownerRenderer = ownerElement->renderer();
1382     if (!ownerRenderer)
1383         return 0;
1384
1385     return ownerRenderer->enclosingLayer();
1386 }
1387
1388 RenderLayer* RenderLayer::enclosingScrollableLayer() const
1389 {
1390     for (RenderLayer* nextLayer = parentLayerCrossFrame(this); nextLayer; nextLayer = parentLayerCrossFrame(nextLayer)) {
1391         if (nextLayer->renderer().isBox() && toRenderBox(nextLayer->renderer()).canBeScrolledAndHasScrollableArea())
1392             return nextLayer;
1393     }
1394
1395     return 0;
1396 }
1397
1398 IntRect RenderLayer::scrollableAreaBoundingBox() const
1399 {
1400     return renderer().absoluteBoundingBoxRect();
1401 }
1402
1403 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
1404 {
1405     RenderLayer* curr = parent();
1406     while (curr && !curr->isRootLayer() && !curr->transform())
1407         curr = curr->parent();
1408
1409     return curr;
1410 }
1411
1412 static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
1413 {
1414     return layer->isNormalFlowOnly() ? layer->parent() : layer->stackingContainer();
1415 }
1416
1417 inline bool RenderLayer::shouldRepaintAfterLayout() const
1418 {
1419 #if USE(ACCELERATED_COMPOSITING)
1420     if (m_repaintStatus == NeedsNormalRepaint)
1421         return true;
1422
1423     // Composited layers that were moved during a positioned movement only
1424     // layout, don't need to be repainted. They just need to be recomposited.
1425     ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
1426     return !isComposited();
1427 #else
1428     return true;
1429 #endif
1430 }
1431
1432 #if USE(ACCELERATED_COMPOSITING)
1433
1434 static bool compositedWithOwnBackingStore(const RenderLayer* layer)
1435 {
1436     return layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor();
1437 }
1438
1439 RenderLayer* RenderLayer::enclosingCompositingLayer(IncludeSelfOrNot includeSelf) const
1440 {
1441     if (includeSelf == IncludeSelf && isComposited())
1442         return const_cast<RenderLayer*>(this);
1443
1444     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1445         if (curr->isComposited())
1446             return const_cast<RenderLayer*>(curr);
1447     }
1448          
1449     return 0;
1450 }
1451
1452 RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(IncludeSelfOrNot includeSelf) const
1453 {
1454     if (includeSelf == IncludeSelf && isComposited() && !backing()->paintsIntoCompositedAncestor())
1455         return const_cast<RenderLayer*>(this);
1456
1457     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1458         if (compositedWithOwnBackingStore(curr))
1459             return const_cast<RenderLayer*>(curr);
1460     }
1461          
1462     return 0;
1463 }
1464
1465 #endif
1466
1467 #if ENABLE(CSS_FILTERS)
1468
1469 RenderLayer* RenderLayer::enclosingFilterLayer(IncludeSelfOrNot includeSelf) const
1470 {
1471     const RenderLayer* curr = (includeSelf == IncludeSelf) ? this : parent();
1472     for (; curr; curr = curr->parent()) {
1473         if (curr->requiresFullLayerImageForFilters())
1474             return const_cast<RenderLayer*>(curr);
1475     }
1476     
1477     return 0;
1478 }
1479
1480 RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
1481 {
1482     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1483         if ((curr != this && curr->requiresFullLayerImageForFilters())
1484 #if USE(ACCELERATED_COMPOSITING)
1485             || compositedWithOwnBackingStore(curr)
1486 #endif
1487             || curr->isRootLayer()
1488         )
1489             return const_cast<RenderLayer*>(curr);
1490     }
1491     return 0;
1492 }
1493
1494 void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect, bool immediate)
1495 {
1496     if (rect.isEmpty())
1497         return;
1498     
1499     LayoutRect rectForRepaint = rect;
1500     renderer().style()->filterOutsets().expandRect(rectForRepaint);
1501
1502     FilterInfo& filterInfo = FilterInfo::get(*this);
1503     filterInfo.expandDirtySourceRect(rectForRepaint);
1504     
1505 #if ENABLE(CSS_SHADERS)
1506     ASSERT(filterInfo.renderer());
1507     if (filterInfo.renderer()->hasCustomShaderFilter()) {
1508         // If we have at least one custom shader, we need to update the whole bounding box of the layer, because the
1509         // shader can address any ouput pixel.
1510         // Note: This is only for output rect, so there's no need to expand the dirty source rect.
1511         rectForRepaint.unite(calculateLayerBounds(this));
1512     }
1513 #endif
1514     
1515     RenderLayer* parentLayer = enclosingFilterRepaintLayer();
1516     ASSERT(parentLayer);
1517     FloatQuad repaintQuad(rectForRepaint);
1518     LayoutRect parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
1519     
1520 #if USE(ACCELERATED_COMPOSITING)
1521     if (parentLayer->isComposited()) {
1522         if (!parentLayer->backing()->paintsIntoWindow()) {
1523             parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
1524             return;
1525         }
1526         // If the painting goes to window, redirect the painting to the parent RenderView.
1527         parentLayer = renderer().view().layer();
1528         parentLayerRect = renderer().localToContainerQuad(repaintQuad, &parentLayer->renderer()).enclosingBoundingBox();
1529     }
1530 #endif
1531
1532     if (parentLayer->paintsWithFilters()) {
1533         parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect, immediate);
1534         return;        
1535     }
1536     
1537     if (parentLayer->isRootLayer()) {
1538         toRenderView(parentLayer->renderer()).repaintViewRectangle(parentLayerRect, immediate);
1539         return;
1540     }
1541     
1542     ASSERT_NOT_REACHED();
1543 }
1544
1545 bool RenderLayer::hasAncestorWithFilterOutsets() const
1546 {
1547     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1548         if (curr->renderer().style()->hasFilterOutsets())
1549             return true;
1550     }
1551     return false;
1552 }
1553
1554 #endif
1555
1556 RenderLayer* RenderLayer::clippingRootForPainting() const
1557 {
1558 #if USE(ACCELERATED_COMPOSITING)
1559     if (isComposited())
1560         return const_cast<RenderLayer*>(this);
1561 #endif
1562
1563     const RenderLayer* current = this;
1564     while (current) {
1565         if (current->isRootLayer())
1566             return const_cast<RenderLayer*>(current);
1567
1568         current = compositingContainer(current);
1569         ASSERT(current);
1570         if (current->transform()
1571 #if USE(ACCELERATED_COMPOSITING)
1572             || compositedWithOwnBackingStore(current)
1573 #endif
1574         )
1575             return const_cast<RenderLayer*>(current);
1576     }
1577
1578     ASSERT_NOT_REACHED();
1579     return 0;
1580 }
1581
1582 LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
1583 {
1584     // We don't use convertToLayerCoords because it doesn't know about transforms
1585     return roundedLayoutPoint(renderer().absoluteToLocal(absolutePoint, UseTransforms));
1586 }
1587
1588 bool RenderLayer::cannotBlitToWindow() const
1589 {
1590     if (isTransparent() || hasReflection() || hasTransform())
1591         return true;
1592     if (!parent())
1593         return false;
1594     return parent()->cannotBlitToWindow();
1595 }
1596
1597 bool RenderLayer::isTransparent() const
1598 {
1599 #if ENABLE(SVG)
1600     if (renderer().element() && renderer().element()->namespaceURI() == SVGNames::svgNamespaceURI)
1601         return false;
1602 #endif
1603     return renderer().isTransparent() || renderer().hasMask();
1604 }
1605
1606 RenderLayer* RenderLayer::transparentPaintingAncestor()
1607 {
1608     if (isComposited())
1609         return 0;
1610
1611     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
1612         if (curr->isComposited())
1613             return 0;
1614         if (curr->isTransparent())
1615             return curr;
1616     }
1617     return 0;
1618 }
1619
1620 enum TransparencyClipBoxBehavior {
1621     PaintingTransparencyClipBox,
1622     HitTestingTransparencyClipBox
1623 };
1624
1625 enum TransparencyClipBoxMode {
1626     DescendantsOfTransparencyClipBox,
1627     RootOfTransparencyClipBox
1628 };
1629
1630 static LayoutRect transparencyClipBox(const RenderLayer*, const RenderLayer* rootLayer, TransparencyClipBoxBehavior, TransparencyClipBoxMode, PaintBehavior = 0);
1631
1632 static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, const RenderLayer* layer, const RenderLayer* rootLayer,
1633     TransparencyClipBoxBehavior transparencyBehavior, PaintBehavior paintBehavior)
1634 {
1635     // If we have a mask, then the clip is limited to the border box area (and there is
1636     // no need to examine child layers).
1637     if (!layer->renderer().hasMask()) {
1638         // Note: we don't have to walk z-order lists since transparent elements always establish
1639         // a stacking container. This means we can just walk the layer tree directly.
1640         for (RenderLayer* curr = layer->firstChild(); curr; curr = curr->nextSibling()) {
1641             if (!layer->reflection() || layer->reflectionLayer() != curr)
1642                 clipRect.unite(transparencyClipBox(curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior));
1643         }
1644     }
1645
1646     // If we have a reflection, then we need to account for that when we push the clip.  Reflect our entire
1647     // current transparencyClipBox to catch all child layers.
1648     // FIXME: Accelerated compositing will eventually want to do something smart here to avoid incorporating this
1649     // size into the parent layer.
1650     if (layer->renderer().hasReflection()) {
1651         LayoutPoint delta;
1652         layer->convertToLayerCoords(rootLayer, delta);
1653         clipRect.move(-delta.x(), -delta.y());
1654         clipRect.unite(layer->renderBox()->reflectedRect(clipRect));
1655         clipRect.moveBy(delta);
1656     }
1657 }
1658
1659 static LayoutRect transparencyClipBox(const RenderLayer* layer, const RenderLayer* rootLayer, TransparencyClipBoxBehavior transparencyBehavior,
1660     TransparencyClipBoxMode transparencyMode, PaintBehavior paintBehavior)
1661 {
1662     // FIXME: Although this function completely ignores CSS-imposed clipping, we did already intersect with the
1663     // paintDirtyRect, and that should cut down on the amount we have to paint.  Still it
1664     // would be better to respect clips.
1665     
1666     if (rootLayer != layer && ((transparencyBehavior == PaintingTransparencyClipBox && layer->paintsWithTransform(paintBehavior))
1667         || (transparencyBehavior == HitTestingTransparencyClipBox && layer->hasTransform()))) {
1668         // The best we can do here is to use enclosed bounding boxes to establish a "fuzzy" enough clip to encompass
1669         // the transformed layer and all of its children.
1670         const RenderLayer* paginationLayer = transparencyMode == DescendantsOfTransparencyClipBox ? layer->enclosingPaginationLayer() : 0;
1671         const RenderLayer* rootLayerForTransform = paginationLayer ? paginationLayer : rootLayer;
1672         LayoutPoint delta;
1673         layer->convertToLayerCoords(rootLayerForTransform, delta);
1674
1675         TransformationMatrix transform;
1676         transform.translate(delta.x(), delta.y());
1677         transform = transform * *layer->transform();
1678
1679         // We don't use fragment boxes when collecting a transformed layer's bounding box, since it always
1680         // paints unfragmented.
1681         LayoutRect clipRect = layer->boundingBox(layer);
1682         expandClipRectForDescendantsAndReflection(clipRect, layer, layer, transparencyBehavior, paintBehavior);
1683 #if ENABLE(CSS_FILTERS)
1684         layer->renderer().style()->filterOutsets().expandRect(clipRect);
1685 #endif
1686         LayoutRect result = transform.mapRect(clipRect);
1687         if (!paginationLayer)
1688             return result;
1689         
1690         // We have to break up the transformed extent across our columns.
1691         // Split our box up into the actual fragment boxes that render in the columns/pages and unite those together to
1692         // get our true bounding box.
1693         RenderFlowThread& enclosingFlowThread = toRenderFlowThread(paginationLayer->renderer());
1694         result = enclosingFlowThread.fragmentsBoundingBox(result);
1695         
1696         LayoutPoint rootLayerDelta;
1697         paginationLayer->convertToLayerCoords(rootLayer, rootLayerDelta);
1698         result.moveBy(rootLayerDelta);
1699         return result;
1700     }
1701     
1702     LayoutRect clipRect = layer->boundingBox(rootLayer, RenderLayer::UseFragmentBoxes);
1703     expandClipRectForDescendantsAndReflection(clipRect, layer, rootLayer, transparencyBehavior, paintBehavior);
1704 #if ENABLE(CSS_FILTERS)
1705     layer->renderer().style()->filterOutsets().expandRect(clipRect);
1706 #endif
1707     return clipRect;
1708 }
1709
1710 LayoutRect RenderLayer::paintingExtent(const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
1711 {
1712     return intersection(transparencyClipBox(this, rootLayer, PaintingTransparencyClipBox, RootOfTransparencyClipBox, paintBehavior), paintDirtyRect);
1713 }
1714
1715 void RenderLayer::beginTransparencyLayers(GraphicsContext* context, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
1716 {
1717     if (context->paintingDisabled() || (paintsWithTransparency(paintBehavior) && m_usedTransparency))
1718         return;
1719     
1720     RenderLayer* ancestor = transparentPaintingAncestor();
1721     if (ancestor)
1722         ancestor->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
1723     
1724     if (paintsWithTransparency(paintBehavior)) {
1725         m_usedTransparency = true;
1726         context->save();
1727         LayoutRect clipRect = paintingExtent(rootLayer, paintDirtyRect, paintBehavior);
1728         context->clip(clipRect);
1729         context->beginTransparencyLayer(renderer().opacity());
1730 #ifdef REVEAL_TRANSPARENCY_LAYERS
1731         context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f), ColorSpaceDeviceRGB);
1732         context->fillRect(clipRect);
1733 #endif
1734     }
1735 }
1736
1737 void* RenderLayer::operator new(size_t sz, RenderArena& renderArena)
1738 {
1739     return renderArena.allocate(sz);
1740 }
1741
1742 void RenderLayer::operator delete(void* ptr, size_t sz)
1743 {
1744     // Stash size where destroy can find it.
1745     *(size_t *)ptr = sz;
1746 }
1747
1748 void RenderLayer::destroy(RenderArena& renderArena)
1749 {
1750     delete this;
1751
1752     // Recover the size left there for us by operator delete and free the memory.
1753     renderArena.free(*(size_t *)this, this);
1754 }
1755
1756 void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
1757 {
1758     RenderLayer* prevSibling = beforeChild ? beforeChild->previousSibling() : lastChild();
1759     if (prevSibling) {
1760         child->setPreviousSibling(prevSibling);
1761         prevSibling->setNextSibling(child);
1762         ASSERT(prevSibling != child);
1763     } else
1764         setFirstChild(child);
1765
1766     if (beforeChild) {
1767         beforeChild->setPreviousSibling(child);
1768         child->setNextSibling(beforeChild);
1769         ASSERT(beforeChild != child);
1770     } else
1771         setLastChild(child);
1772
1773     child->setParent(this);
1774
1775     if (child->isNormalFlowOnly())
1776         dirtyNormalFlowList();
1777
1778     if (!child->isNormalFlowOnly() || child->firstChild()) {
1779         // Dirty the z-order list in which we are contained. The stackingContainer() can be null in the
1780         // case where we're building up generated content layers. This is ok, since the lists will start
1781         // off dirty in that case anyway.
1782         child->dirtyStackingContainerZOrderLists();
1783     }
1784
1785     child->updateDescendantDependentFlags();
1786     if (child->m_hasVisibleContent || child->m_hasVisibleDescendant)
1787         setAncestorChainHasVisibleDescendant();
1788
1789     if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
1790         setAncestorChainHasSelfPaintingLayerDescendant();
1791
1792     if (child->renderer().isOutOfFlowPositioned() || child->hasOutOfFlowPositionedDescendant())
1793         setAncestorChainHasOutOfFlowPositionedDescendant(child->renderer().containingBlock());
1794
1795 #if USE(ACCELERATED_COMPOSITING)
1796     compositor().layerWasAdded(*this, *child);
1797 #endif
1798 }
1799
1800 RenderLayer* RenderLayer::removeChild(RenderLayer* oldChild)
1801 {
1802 #if USE(ACCELERATED_COMPOSITING)
1803     if (!renderer().documentBeingDestroyed())
1804         compositor().layerWillBeRemoved(*this, *oldChild);
1805 #endif
1806
1807     // remove the child
1808     if (oldChild->previousSibling())
1809         oldChild->previousSibling()->setNextSibling(oldChild->nextSibling());
1810     if (oldChild->nextSibling())
1811         oldChild->nextSibling()->setPreviousSibling(oldChild->previousSibling());
1812
1813     if (m_first == oldChild)
1814         m_first = oldChild->nextSibling();
1815     if (m_last == oldChild)
1816         m_last = oldChild->previousSibling();
1817
1818     if (oldChild->isNormalFlowOnly())
1819         dirtyNormalFlowList();
1820     if (!oldChild->isNormalFlowOnly() || oldChild->firstChild()) { 
1821         // Dirty the z-order list in which we are contained.  When called via the
1822         // reattachment process in removeOnlyThisLayer, the layer may already be disconnected
1823         // from the main layer tree, so we need to null-check the |stackingContainer| value.
1824         oldChild->dirtyStackingContainerZOrderLists();
1825     }
1826
1827     if (oldChild->renderer().isOutOfFlowPositioned() || oldChild->hasOutOfFlowPositionedDescendant())
1828         dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
1829
1830     oldChild->setPreviousSibling(0);
1831     oldChild->setNextSibling(0);
1832     oldChild->setParent(0);
1833     
1834     oldChild->updateDescendantDependentFlags();
1835     if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
1836         dirtyAncestorChainVisibleDescendantStatus();
1837
1838     if (oldChild->isSelfPaintingLayer() || oldChild->hasSelfPaintingLayerDescendant())
1839         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
1840
1841     return oldChild;
1842 }
1843
1844 void RenderLayer::removeOnlyThisLayer()
1845 {
1846     if (!m_parent)
1847         return;
1848
1849     // Mark that we are about to lose our layer. This makes render tree
1850     // walks ignore this layer while we're removing it.
1851     renderer().setHasLayer(false);
1852
1853 #if USE(ACCELERATED_COMPOSITING)
1854     compositor().layerWillBeRemoved(*m_parent, *this);
1855 #endif
1856
1857     // Dirty the clip rects.
1858     clearClipRectsIncludingDescendants();
1859
1860     RenderLayer* nextSib = nextSibling();
1861
1862     // Remove the child reflection layer before moving other child layers.
1863     // The reflection layer should not be moved to the parent.
1864     if (reflection())
1865         removeChild(reflectionLayer());
1866
1867     // Now walk our kids and reattach them to our parent.
1868     RenderLayer* current = m_first;
1869     while (current) {
1870         RenderLayer* next = current->nextSibling();
1871         removeChild(current);
1872         m_parent->addChild(current, nextSib);
1873         current->setRepaintStatus(NeedsFullRepaint);
1874         // updateLayerPositions depends on hasLayer() already being false for proper layout.
1875         ASSERT(!renderer().hasLayer());
1876         current->updateLayerPositions(0); // FIXME: use geometry map.
1877         current = next;
1878     }
1879
1880     // Remove us from the parent.
1881     m_parent->removeChild(this);
1882     renderer().destroyLayer();
1883 }
1884
1885 void RenderLayer::insertOnlyThisLayer()
1886 {
1887     if (!m_parent && renderer().parent()) {
1888         // We need to connect ourselves when our renderer() has a parent.
1889         // Find our enclosingLayer and add ourselves.
1890         RenderLayer* parentLayer = renderer().parent()->enclosingLayer();
1891         ASSERT(parentLayer);
1892         RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer().parent()->findNextLayer(parentLayer, &renderer()) : 0;
1893         parentLayer->addChild(this, beforeChild);
1894     }
1895
1896     // Remove all descendant layers from the hierarchy and add them to the new position.
1897     for (RenderObject* curr = renderer().firstChild(); curr; curr = curr->nextSibling()) {
1898         if (curr->isRenderElement())
1899             toRenderElement(curr)->moveLayers(m_parent, this);
1900     }
1901
1902     // Clear out all the clip rects.
1903     clearClipRectsIncludingDescendants();
1904 }
1905
1906 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation, ColumnOffsetAdjustment adjustForColumns) const
1907 {
1908     LayoutPoint location = roundedLocation;
1909     convertToLayerCoords(ancestorLayer, location, adjustForColumns);
1910     roundedLocation = roundedIntPoint(location);
1911 }
1912
1913 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntRect& roundedRect, ColumnOffsetAdjustment adjustForColumns) const
1914 {
1915     LayoutRect rect = roundedRect;
1916     convertToLayerCoords(ancestorLayer, rect, adjustForColumns);
1917     roundedRect = pixelSnappedIntRect(rect);
1918 }
1919
1920 // Returns the layer reached on the walk up towards the ancestor.
1921 static inline const RenderLayer* accumulateOffsetTowardsAncestor(const RenderLayer* layer, const RenderLayer* ancestorLayer, LayoutPoint& location, RenderLayer::ColumnOffsetAdjustment adjustForColumns)
1922 {
1923     ASSERT(ancestorLayer != layer);
1924
1925     const RenderLayerModelObject& renderer = layer->renderer();
1926     EPosition position = renderer.style()->position();
1927
1928     // FIXME: Special casing RenderFlowThread so much for fixed positioning here is not great.
1929     RenderFlowThread* fixedFlowThreadContainer = position == FixedPosition ? renderer.flowThreadContainingBlock() : 0;
1930     if (fixedFlowThreadContainer && !fixedFlowThreadContainer->isOutOfFlowPositioned())
1931         fixedFlowThreadContainer = 0;
1932
1933     // FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFlowThread
1934     // may need to be revisited in a future patch.
1935     // If the fixed renderer is inside a RenderFlowThread, we should not compute location using localToAbsolute,
1936     // since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
1937     // positioned in a completely different place in the viewport (RenderView).
1938     if (position == FixedPosition && !fixedFlowThreadContainer && (!ancestorLayer || ancestorLayer == renderer.view().layer())) {
1939         // If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
1940         // localToAbsolute() on the RenderView.
1941         FloatPoint absPos = renderer.localToAbsolute(FloatPoint(), IsFixed);
1942         location += LayoutSize(absPos.x(), absPos.y());
1943         return ancestorLayer;
1944     }
1945
1946     // For the fixed positioned elements inside a render flow thread, we should also skip the code path below
1947     // Otherwise, for the case of ancestorLayer == rootLayer and fixed positioned element child of a transformed
1948     // element in render flow thread, we will hit the fixed positioned container before hitting the ancestor layer.
1949     if (position == FixedPosition && !fixedFlowThreadContainer) {
1950         // For a fixed layers, we need to walk up to the root to see if there's a fixed position container
1951         // (e.g. a transformed layer). It's an error to call convertToLayerCoords() across a layer with a transform,
1952         // so we should always find the ancestor at or before we find the fixed position container.
1953         RenderLayer* fixedPositionContainerLayer = 0;
1954         bool foundAncestor = false;
1955         for (RenderLayer* currLayer = layer->parent(); currLayer; currLayer = currLayer->parent()) {
1956             if (currLayer == ancestorLayer)
1957                 foundAncestor = true;
1958
1959             if (isFixedPositionedContainer(currLayer)) {
1960                 fixedPositionContainerLayer = currLayer;
1961                 ASSERT_UNUSED(foundAncestor, foundAncestor);
1962                 break;
1963             }
1964         }
1965         
1966         ASSERT(fixedPositionContainerLayer); // We should have hit the RenderView's layer at least.
1967
1968         if (fixedPositionContainerLayer != ancestorLayer) {
1969             LayoutPoint fixedContainerCoords;
1970             layer->convertToLayerCoords(fixedPositionContainerLayer, fixedContainerCoords);
1971
1972             LayoutPoint ancestorCoords;
1973             ancestorLayer->convertToLayerCoords(fixedPositionContainerLayer, ancestorCoords);
1974
1975             location += (fixedContainerCoords - ancestorCoords);
1976             return ancestorLayer;
1977         }
1978     }
1979
1980     if (position == FixedPosition && fixedFlowThreadContainer) {
1981         ASSERT(ancestorLayer);
1982         if (ancestorLayer->isOutOfFlowRenderFlowThread()) {
1983             location += toSize(layer->location());
1984             return ancestorLayer;
1985         }
1986
1987         if (ancestorLayer == renderer.view().layer()) {
1988             // Add location in flow thread coordinates.
1989             location += toSize(layer->location());
1990
1991             // Add flow thread offset in view coordinates since the view may be scrolled.
1992             FloatPoint absPos = renderer.view().localToAbsolute(FloatPoint(), IsFixed);
1993             location += LayoutSize(absPos.x(), absPos.y());
1994             return ancestorLayer;
1995         }
1996     }
1997
1998     RenderLayer* parentLayer;
1999     if (position == AbsolutePosition || position == FixedPosition) {
2000         // Do what enclosingPositionedAncestor() does, but check for ancestorLayer along the way.
2001         parentLayer = layer->parent();
2002         bool foundAncestorFirst = false;
2003         while (parentLayer) {
2004             // RenderFlowThread is a positioned container, child of RenderView, positioned at (0,0).
2005             // This implies that, for out-of-flow positioned elements inside a RenderFlowThread,
2006             // we are bailing out before reaching root layer.
2007             if (isPositionedContainer(parentLayer))
2008                 break;
2009
2010             if (parentLayer == ancestorLayer) {
2011                 foundAncestorFirst = true;
2012                 break;
2013             }
2014
2015             parentLayer = parentLayer->parent();
2016         }
2017
2018         // We should not reach RenderView layer past the RenderFlowThread layer for any
2019         // children of the RenderFlowThread.
2020         if (renderer.flowThreadContainingBlock() && !layer->isOutOfFlowRenderFlowThread())
2021             ASSERT(parentLayer != renderer.view().layer());
2022
2023         if (foundAncestorFirst) {
2024             // Found ancestorLayer before the abs. positioned container, so compute offset of both relative
2025             // to enclosingPositionedAncestor and subtract.
2026             RenderLayer* positionedAncestor = parentLayer->enclosingPositionedAncestor();
2027
2028             LayoutPoint thisCoords;
2029             layer->convertToLayerCoords(positionedAncestor, thisCoords);
2030             
2031             LayoutPoint ancestorCoords;
2032             ancestorLayer->convertToLayerCoords(positionedAncestor, ancestorCoords);
2033
2034             location += (thisCoords - ancestorCoords);
2035             return ancestorLayer;
2036         }
2037     } else
2038         parentLayer = layer->parent();
2039     
2040     if (!parentLayer)
2041         return 0;
2042
2043     location += toSize(layer->location());
2044
2045     if (adjustForColumns == RenderLayer::AdjustForColumns) {
2046         if (RenderLayer* parentLayer = layer->parent()) {
2047             LayoutSize layerColumnOffset;
2048             parentLayer->renderer().adjustForColumns(layerColumnOffset, location);
2049             location += layerColumnOffset;
2050         }
2051     }
2052
2053     return parentLayer;
2054 }
2055
2056 void RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutPoint& location, ColumnOffsetAdjustment adjustForColumns) const
2057 {
2058     if (ancestorLayer == this)
2059         return;
2060
2061     const RenderLayer* currLayer = this;
2062     while (currLayer && currLayer != ancestorLayer)
2063         currLayer = accumulateOffsetTowardsAncestor(currLayer, ancestorLayer, location, adjustForColumns);
2064 }
2065
2066 void RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutRect& rect, ColumnOffsetAdjustment adjustForColumns) const
2067 {
2068     LayoutPoint delta;
2069     convertToLayerCoords(ancestorLayer, delta, adjustForColumns);
2070     rect.move(-delta.x(), -delta.y());
2071 }
2072
2073 #if USE(ACCELERATED_COMPOSITING)
2074
2075 bool RenderLayer::usesCompositedScrolling() const
2076 {
2077     return isComposited() && backing()->scrollingLayer();
2078 }
2079
2080 bool RenderLayer::needsCompositedScrolling() const
2081 {
2082     return m_needsCompositedScrolling;
2083 }
2084
2085 void RenderLayer::updateNeedsCompositedScrolling()
2086 {
2087     bool oldNeedsCompositedScrolling = m_needsCompositedScrolling;
2088
2089     if (!renderer().view().frameView().containsScrollableArea(this))
2090         m_needsCompositedScrolling = false;
2091     else {
2092         bool forceUseCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
2093             && canBeStackingContainer()
2094             && !hasOutOfFlowPositionedDescendant();
2095
2096 #if ENABLE(ACCELERATED_OVERFLOW_SCROLLING)
2097         m_needsCompositedScrolling = forceUseCompositedScrolling || renderer().style()->useTouchOverflowScrolling();
2098 #else
2099         m_needsCompositedScrolling = forceUseCompositedScrolling;
2100 #endif
2101         // We gather a boolean value for use with Google UMA histograms to
2102         // quantify the actual effects of a set of patches attempting to
2103         // relax composited scrolling requirements, thereby increasing the
2104         // number of composited overflow divs.
2105         if (acceleratedCompositingForOverflowScrollEnabled())
2106             HistogramSupport::histogramEnumeration("Renderer.NeedsCompositedScrolling", m_needsCompositedScrolling, 2);
2107     }
2108
2109     if (oldNeedsCompositedScrolling != m_needsCompositedScrolling) {
2110         updateSelfPaintingLayer();
2111         if (isStackingContainer())
2112             dirtyZOrderLists();
2113         else
2114             clearZOrderLists();
2115
2116         dirtyStackingContainerZOrderLists();
2117
2118         compositor().setShouldReevaluateCompositingAfterLayout();
2119         compositor().setCompositingLayersNeedRebuild();
2120     }
2121 }
2122
2123 #endif
2124
2125 static inline int adjustedScrollDelta(int beginningDelta) {
2126     // This implemention matches Firefox's.
2127     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
2128     const int speedReducer = 12;
2129
2130     int adjustedDelta = beginningDelta / speedReducer;
2131     if (adjustedDelta > 1)
2132         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
2133     else if (adjustedDelta < -1)
2134         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
2135
2136     return adjustedDelta;
2137 }
2138
2139 static inline IntSize adjustedScrollDelta(const IntSize& delta)
2140 {
2141     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
2142 }
2143
2144 void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
2145 {
2146     IntPoint lastKnownMousePosition = renderer().frame().eventHandler().lastKnownMousePosition();
2147     
2148     // 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
2149     static IntPoint previousMousePosition;
2150     if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
2151         lastKnownMousePosition = previousMousePosition;
2152     else
2153         previousMousePosition = lastKnownMousePosition;
2154
2155     IntSize delta = lastKnownMousePosition - sourcePoint;
2156
2157     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
2158         delta.setWidth(0);
2159     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
2160         delta.setHeight(0);
2161
2162     scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
2163 }
2164
2165 void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp, ScrollableArea** scrolledArea)
2166 {
2167     if (delta.isZero())
2168         return;
2169
2170     bool restrictedByLineClamp = false;
2171     if (renderer().parent())
2172         restrictedByLineClamp = !renderer().parent()->style()->lineClamp().isNone();
2173
2174     if (renderer().hasOverflowClip() && !restrictedByLineClamp) {
2175         IntSize newScrollOffset = scrollOffset() + delta;
2176         scrollToOffset(newScrollOffset, clamp);
2177         if (scrolledArea)
2178             *scrolledArea = this;
2179
2180         // If this layer can't do the scroll we ask the next layer up that can scroll to try
2181         IntSize remainingScrollOffset = newScrollOffset - scrollOffset();
2182         if (!remainingScrollOffset.isZero() && renderer().parent()) {
2183             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2184                 scrollableLayer->scrollByRecursively(remainingScrollOffset, clamp, scrolledArea);
2185
2186             renderer().frame().eventHandler().updateAutoscrollRenderer();
2187         }
2188     } else {
2189         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
2190         // have an overflow clip. Which means that it is a document node that can be scrolled.
2191         renderer().view().frameView().scrollBy(delta);
2192         if (scrolledArea)
2193             *scrolledArea = &renderer().view().frameView();
2194
2195         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement? 
2196         // https://bugs.webkit.org/show_bug.cgi?id=28237
2197     }
2198 }
2199
2200 IntSize RenderLayer::clampScrollOffset(const IntSize& scrollOffset) const
2201 {
2202     RenderBox* box = renderBox();
2203     ASSERT(box);
2204
2205     int maxX = scrollWidth() - box->pixelSnappedClientWidth();
2206     int maxY = scrollHeight() - box->pixelSnappedClientHeight();
2207
2208     int x = max(min(scrollOffset.width(), maxX), 0);
2209     int y = max(min(scrollOffset.height(), maxY), 0);
2210     return IntSize(x, y);
2211 }
2212
2213 void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
2214 {
2215     IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
2216     if (newScrollOffset != this->scrollOffset())
2217         scrollToOffsetWithoutAnimation(IntPoint(newScrollOffset));
2218 }
2219
2220 void RenderLayer::scrollTo(int x, int y)
2221 {
2222     RenderBox* box = renderBox();
2223     if (!box)
2224         return;
2225
2226     if (box->style()->overflowX() != OMARQUEE) {
2227         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
2228         if (m_scrollDimensionsDirty)
2229             computeScrollDimensions();
2230     }
2231     
2232     // FIXME: Eventually, we will want to perform a blit.  For now never
2233     // blit, since the check for blitting is going to be very
2234     // complicated (since it will involve testing whether our layer
2235     // is either occluded by another layer or clipped by an enclosing
2236     // layer or contains fixed backgrounds, etc.).
2237     IntSize newScrollOffset = IntSize(x - scrollOrigin().x(), y - scrollOrigin().y());
2238     if (m_scrollOffset == newScrollOffset)
2239         return;
2240     m_scrollOffset = newScrollOffset;
2241
2242     InspectorInstrumentation::willScrollLayer(&renderer().frame());
2243
2244     RenderView& view = renderer().view();
2245
2246     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
2247     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
2248     bool inLayout = view.frameView().isInLayout();
2249     if (!inLayout) {
2250         // If we're in the middle of layout, we'll just update layers once layout has finished.
2251         updateLayerPositionsAfterOverflowScroll();
2252         // Update regions, scrolling may change the clip of a particular region.
2253 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2254         view.frameView().updateAnnotatedRegions();
2255 #endif
2256         view.frameView().updateWidgetPositions();
2257
2258         if (!m_updatingMarqueePosition) {
2259             // Avoid updating compositing layers if, higher on the stack, we're already updating layer
2260             // positions. Updating layer positions requires a full walk of up-to-date RenderLayers, and
2261             // in this case we're still updating their positions; we'll update compositing layers later
2262             // when that completes.
2263             updateCompositingLayersAfterScroll();
2264         }
2265     }
2266
2267     Frame& frame = renderer().frame();
2268     RenderLayerModelObject* repaintContainer = renderer().containerForRepaint();
2269     // The caret rect needs to be invalidated after scrolling
2270     frame.selection().setCaretRectNeedsUpdate();
2271
2272     FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_repaintRect);
2273     if (repaintContainer)
2274         quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
2275     frame.eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
2276
2277     bool requiresRepaint = true;
2278
2279 #if USE(ACCELERATED_COMPOSITING)
2280     if (compositor().inCompositingMode() && usesCompositedScrolling())
2281         requiresRepaint = false;
2282 #endif
2283
2284     // Just schedule a full repaint of our object.
2285     if (requiresRepaint)
2286         renderer().repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));
2287
2288     // Schedule the scroll DOM event.
2289     if (Element* element = renderer().element())
2290         element->document().eventQueue().enqueueOrDispatchScrollEvent(*element);
2291
2292     InspectorInstrumentation::didScrollLayer(&frame);
2293     if (scrollsOverflow())
2294         frame.loader().client().didChangeScrollOffset();
2295 }
2296
2297 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView) 
2298 {
2299     // If scrollbars aren't explicitly forbidden, permit scrolling.
2300     if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
2301         return true;
2302
2303     // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
2304     if (frameView->wasScrolledByUser())
2305         return false;
2306
2307     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
2308     // like navigation to an anchor.
2309     return !frameView->frame().eventHandler().autoscrollInProgress();
2310 }
2311
2312 void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
2313 {
2314     RenderLayer* parentLayer = 0;
2315     LayoutRect newRect = rect;
2316
2317     // We may end up propagating a scroll event. It is important that we suspend events until 
2318     // the end of the function since they could delete the layer or the layer's renderer().
2319     FrameView& frameView = renderer().view().frameView();
2320     frameView.pauseScheduledEvents();
2321
2322     bool restrictedByLineClamp = false;
2323     if (renderer().parent()) {
2324         parentLayer = renderer().parent()->enclosingLayer();
2325         restrictedByLineClamp = !renderer().parent()->style()->lineClamp().isNone();
2326     }
2327
2328     if (renderer().hasOverflowClip() && !restrictedByLineClamp) {
2329         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
2330         // This will prevent us from revealing text hidden by the slider in Safari RSS.
2331         RenderBox* box = renderBox();
2332         ASSERT(box);
2333         LayoutRect localExposeRect(box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
2334         LayoutRect layerBounds(0, 0, box->clientWidth(), box->clientHeight());
2335         LayoutRect r = getRectToExpose(layerBounds, layerBounds, localExposeRect, alignX, alignY);
2336
2337         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset() + toIntSize(roundedIntRect(r).location()));
2338         if (clampedScrollOffset != scrollOffset()) {
2339             IntSize oldScrollOffset = scrollOffset();
2340             scrollToOffset(clampedScrollOffset);
2341             IntSize scrollOffsetDifference = scrollOffset() - oldScrollOffset;
2342             localExposeRect.move(-scrollOffsetDifference);
2343             newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
2344         }
2345     } else if (!parentLayer && renderer().isBox() && renderBox()->canBeProgramaticallyScrolled()) {
2346         Element* ownerElement = renderer().document().ownerElement();
2347
2348         if (ownerElement && ownerElement->renderer()) {
2349             HTMLFrameElementBase* frameElementBase = 0;
2350
2351             if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
2352                 frameElementBase = toHTMLFrameElementBase(ownerElement);
2353
2354             if (frameElementAndViewPermitScroll(frameElementBase, &frameView)) {
2355                 LayoutRect viewRect = frameView.visibleContentRect();
2356                 LayoutRect exposeRect = getRectToExpose(viewRect, viewRect, rect, alignX, alignY);
2357
2358                 int xOffset = roundToInt(exposeRect.x());
2359                 int yOffset = roundToInt(exposeRect.y());
2360                 // Adjust offsets if they're outside of the allowable range.
2361                 xOffset = max(0, min(frameView.contentsWidth(), xOffset));
2362                 yOffset = max(0, min(frameView.contentsHeight(), yOffset));
2363
2364                 frameView.setScrollPosition(IntPoint(xOffset, yOffset));
2365                 if (frameView.safeToPropagateScrollToParent()) {
2366                     parentLayer = ownerElement->renderer()->enclosingLayer();
2367                     // FIXME: This doesn't correctly convert the rect to
2368                     // absolute coordinates in the parent.
2369                     newRect.setX(rect.x() - frameView.scrollX() + frameView.x());
2370                     newRect.setY(rect.y() - frameView.scrollY() + frameView.y());
2371                 } else
2372                     parentLayer = 0;
2373             }
2374         } else {
2375             LayoutRect viewRect = frameView.visibleContentRect();
2376             LayoutRect visibleRectRelativeToDocument = viewRect;
2377             IntSize scrollOffsetRelativeToDocument = frameView.scrollOffsetRelativeToDocument();
2378             visibleRectRelativeToDocument.setLocation(IntPoint(scrollOffsetRelativeToDocument.width(), scrollOffsetRelativeToDocument.height()));
2379
2380             LayoutRect r = getRectToExpose(viewRect, visibleRectRelativeToDocument, rect, alignX, alignY);
2381                 
2382             frameView.setScrollPosition(roundedIntPoint(r.location()));
2383
2384             // This is the outermost view of a web page, so after scrolling this view we
2385             // scroll its container by calling Page::scrollRectIntoView.
2386             // This only has an effect on the Mac platform in applications
2387             // that put web views into scrolling containers, such as Mac OS X Mail.
2388             // The canAutoscroll function in EventHandler also knows about this.
2389             if (Page* page = frameView.frame().page())
2390                 page->chrome().scrollRectIntoView(pixelSnappedIntRect(rect));
2391         }
2392     }
2393     
2394     if (renderer().frame().eventHandler().autoscrollInProgress())
2395         parentLayer = enclosingScrollableLayer();
2396
2397     if (parentLayer)
2398         parentLayer->scrollRectToVisible(newRect, alignX, alignY);
2399
2400     frameView.resumeScheduledEvents();
2401 }
2402
2403 void RenderLayer::updateCompositingLayersAfterScroll()
2404 {
2405 #if USE(ACCELERATED_COMPOSITING)
2406     if (compositor().inCompositingMode()) {
2407         // Our stacking container is guaranteed to contain all of our descendants that may need
2408         // repositioning, so update compositing layers from there.
2409         if (RenderLayer* compositingAncestor = stackingContainer()->enclosingCompositingLayer()) {
2410             if (usesCompositedScrolling() && !hasOutOfFlowPositionedDescendant())
2411                 compositor().updateCompositingLayers(CompositingUpdateOnCompositedScroll, compositingAncestor);
2412             else
2413                 compositor().updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
2414         }
2415     }
2416 #endif
2417 }
2418
2419 LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &visibleRectRelativeToDocument, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
2420 {
2421     // Determine the appropriate X behavior.
2422     ScrollBehavior scrollX;
2423     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
2424     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
2425     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
2426         // If the rectangle is fully visible, use the specified visible behavior.
2427         // If the rectangle is partially visible, but over a certain threshold,
2428         // then treat it as fully visible to avoid unnecessary horizontal scrolling
2429         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2430     else if (intersectWidth == visibleRect.width()) {
2431         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
2432         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
2433         if (scrollX == alignCenter)
2434             scrollX = noScroll;
2435     } else if (intersectWidth > 0)
2436         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
2437         scrollX = ScrollAlignment::getPartialBehavior(alignX);
2438     else
2439         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
2440     // If we're trying to align to the closest edge, and the exposeRect is further right
2441     // than the visibleRect, and not bigger than the visible area, then align with the right.
2442     if (scrollX == alignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
2443         scrollX = alignRight;
2444
2445     // Given the X behavior, compute the X coordinate.
2446     LayoutUnit x;
2447     if (scrollX == noScroll) 
2448         x = visibleRect.x();
2449     else if (scrollX == alignRight)
2450         x = exposeRect.maxX() - visibleRect.width();
2451     else if (scrollX == alignCenter)
2452         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
2453     else
2454         x = exposeRect.x();
2455
2456     // Determine the appropriate Y behavior.
2457     ScrollBehavior scrollY;
2458     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
2459     LayoutUnit intersectHeight = intersection(visibleRectRelativeToDocument, exposeRectY).height();
2460     if (intersectHeight == exposeRect.height())
2461         // If the rectangle is fully visible, use the specified visible behavior.
2462         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
2463     else if (intersectHeight == visibleRect.height()) {
2464         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
2465         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
2466         if (scrollY == alignCenter)
2467             scrollY = noScroll;
2468     } else if (intersectHeight > 0)
2469         // If the rectangle is partially visible, use the specified partial behavior
2470         scrollY = ScrollAlignment::getPartialBehavior(alignY);
2471     else
2472         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
2473     // If we're trying to align to the closest edge, and the exposeRect is further down
2474     // than the visibleRect, and not bigger than the visible area, then align with the bottom.
2475     if (scrollY == alignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
2476         scrollY = alignBottom;
2477
2478     // Given the Y behavior, compute the Y coordinate.
2479     LayoutUnit y;
2480     if (scrollY == noScroll) 
2481         y = visibleRect.y();
2482     else if (scrollY == alignBottom)
2483         y = exposeRect.maxY() - visibleRect.height();
2484     else if (scrollY == alignCenter)
2485         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
2486     else
2487         y = exposeRect.y();
2488
2489     return LayoutRect(LayoutPoint(x, y), visibleRect.size());
2490 }
2491
2492 void RenderLayer::autoscroll(const IntPoint& position)
2493 {
2494     IntPoint currentDocumentPosition = renderer().view().frameView().windowToContents(position);
2495     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
2496 }
2497
2498 bool RenderLayer::canResize() const
2499 {
2500     // We need a special case for <iframe> because they never have
2501     // hasOverflowClip(). However, they do "implicitly" clip their contents, so
2502     // we want to allow resizing them also.
2503     return (renderer().hasOverflowClip() || renderer().isRenderIFrame()) && renderer().style()->resize() != RESIZE_NONE;
2504 }
2505
2506 void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
2507 {
2508     // FIXME: This should be possible on generated content but is not right now.
2509     if (!inResizeMode() || !canResize() || !renderer().element())
2510         return;
2511
2512     // FIXME: The only case where renderer->element()->renderer() != renderer is with continuations. Do they matter here?
2513     // If they do it would still be better to deal with them explicitly.
2514     Element* element = renderer().element();
2515     RenderBox* renderer = toRenderBox(element->renderer());
2516
2517     Document& document = element->document();
2518     if (!document.frame()->eventHandler().mousePressed())
2519         return;
2520
2521     float zoomFactor = renderer->style()->effectiveZoom();
2522
2523     LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(evt.position()));
2524     newOffset.setWidth(newOffset.width() / zoomFactor);
2525     newOffset.setHeight(newOffset.height() / zoomFactor);
2526     
2527     LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
2528     LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
2529     element->setMinimumSizeForResizing(minimumSize);
2530     
2531     LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
2532     if (renderer->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
2533         newOffset.setWidth(-newOffset.width());
2534         adjustedOldOffset.setWidth(-adjustedOldOffset.width());
2535     }
2536     
2537     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
2538
2539     ASSERT_WITH_SECURITY_IMPLICATION(element->isStyledElement());
2540     StyledElement* styledElement = static_cast<StyledElement*>(element);
2541     bool isBoxSizingBorder = renderer->style()->boxSizing() == BORDER_BOX;
2542
2543     EResize resize = renderer->style()->resize();
2544     if (resize != RESIZE_VERTICAL && difference.width()) {
2545         if (element->isFormControlElement()) {
2546             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
2547             styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, renderer->marginLeft() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2548             styledElement->setInlineStyleProperty(CSSPropertyMarginRight, renderer->marginRight() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2549         }
2550         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingWidth());
2551         baseWidth = baseWidth / zoomFactor;
2552         styledElement->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSPrimitiveValue::CSS_PX);
2553     }
2554
2555     if (resize != RESIZE_HORIZONTAL && difference.height()) {
2556         if (element->isFormControlElement()) {
2557             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
2558             styledElement->setInlineStyleProperty(CSSPropertyMarginTop, renderer->marginTop() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2559             styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, renderer->marginBottom() / zoomFactor, CSSPrimitiveValue::CSS_PX);
2560         }
2561         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingHeight());
2562         baseHeight = baseHeight / zoomFactor;
2563         styledElement->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSPrimitiveValue::CSS_PX);
2564     }
2565
2566     document.updateLayout();
2567
2568     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
2569 }
2570
2571 int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
2572 {
2573     Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_hBar : m_vBar).get();
2574     return scrollbar ? (scrollbar->totalSize() - scrollbar->visibleSize()) : 0;
2575 }
2576
2577 void RenderLayer::setScrollOffset(const IntPoint& offset)
2578 {
2579     scrollTo(offset.x(), offset.y());
2580 }
2581
2582 int RenderLayer::scrollPosition(Scrollbar* scrollbar) const
2583 {
2584     if (scrollbar->orientation() == HorizontalScrollbar)
2585         return scrollXOffset();
2586     if (scrollbar->orientation() == VerticalScrollbar)
2587         return scrollYOffset();
2588     return 0;
2589 }
2590
2591 IntPoint RenderLayer::scrollPosition() const
2592 {
2593     return IntPoint(m_scrollOffset);
2594 }
2595
2596 IntPoint RenderLayer::minimumScrollPosition() const
2597 {
2598     return -scrollOrigin();
2599 }
2600
2601 IntPoint RenderLayer::maximumScrollPosition() const
2602 {
2603     // FIXME: m_scrollSize may not be up-to-date if m_scrollDimensionsDirty is true.
2604     return -scrollOrigin() + roundedIntSize(m_scrollSize) - visibleContentRect(IncludeScrollbars).size();
2605 }
2606
2607 IntRect RenderLayer::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
2608 {
2609     int verticalScrollbarWidth = 0;
2610     int horizontalScrollbarHeight = 0;
2611     if (scrollbarInclusion == IncludeScrollbars) {
2612         verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
2613         horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
2614     }
2615     
2616     return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
2617                    IntSize(max(0, m_layerSize.width() - verticalScrollbarWidth), 
2618                            max(0, m_layerSize.height() - horizontalScrollbarHeight)));
2619 }
2620
2621 IntSize RenderLayer::overhangAmount() const
2622 {
2623     return IntSize();
2624 }
2625
2626 bool RenderLayer::isActive() const
2627 {
2628     Page* page = renderer().frame().page();
2629     return page && page->focusController().isActive();
2630 }
2631
2632 static int cornerStart(const RenderLayer* layer, int minX, int maxX, int thickness)
2633 {
2634     if (layer->renderer().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2635         return minX + layer->renderer().style()->borderLeftWidth();
2636     return maxX - thickness - layer->renderer().style()->borderRightWidth();
2637 }
2638
2639 static IntRect cornerRect(const RenderLayer* layer, const IntRect& bounds)
2640 {
2641     int horizontalThickness;
2642     int verticalThickness;
2643     if (!layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2644         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
2645         // even when they don't exist in order to set the resizer square size properly.
2646         horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
2647         verticalThickness = horizontalThickness;
2648     } else if (layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2649         horizontalThickness = layer->verticalScrollbar()->width();
2650         verticalThickness = horizontalThickness;
2651     } else if (layer->horizontalScrollbar() && !layer->verticalScrollbar()) {
2652         verticalThickness = layer->horizontalScrollbar()->height();
2653         horizontalThickness = verticalThickness;
2654     } else {
2655         horizontalThickness = layer->verticalScrollbar()->width();
2656         verticalThickness = layer->horizontalScrollbar()->height();
2657     }
2658     return IntRect(cornerStart(layer, bounds.x(), bounds.maxX(), horizontalThickness),
2659         bounds.maxY() - verticalThickness - layer->renderer().style()->borderBottomWidth(),
2660         horizontalThickness, verticalThickness);
2661 }
2662
2663 IntRect RenderLayer::scrollCornerRect() const
2664 {
2665     // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
2666     // This happens when:
2667     // (a) A resizer is present and at least one scrollbar is present
2668     // (b) Both scrollbars are present.
2669     bool hasHorizontalBar = horizontalScrollbar();
2670     bool hasVerticalBar = verticalScrollbar();
2671     bool hasResizer = renderer().style()->resize() != RESIZE_NONE;
2672     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
2673         return cornerRect(this, renderBox()->pixelSnappedBorderBoxRect());
2674     return IntRect();
2675 }
2676
2677 static IntRect resizerCornerRect(const RenderLayer* layer, const IntRect& bounds)
2678 {
2679     ASSERT(layer->renderer().isBox());
2680     if (layer->renderer().style()->resize() == RESIZE_NONE)
2681         return IntRect();
2682     return cornerRect(layer, bounds);
2683 }
2684
2685 IntRect RenderLayer::scrollCornerAndResizerRect() const
2686 {
2687     RenderBox* box = renderBox();
2688     if (!box)
2689         return IntRect();
2690     IntRect scrollCornerAndResizer = scrollCornerRect();
2691     if (scrollCornerAndResizer.isEmpty())
2692         scrollCornerAndResizer = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2693     return scrollCornerAndResizer;
2694 }
2695
2696 bool RenderLayer::isScrollCornerVisible() const
2697 {
2698     ASSERT(renderer().isBox());
2699     return !scrollCornerRect().isEmpty();
2700 }
2701
2702 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
2703 {
2704     IntRect rect = scrollbarRect;
2705     rect.move(scrollbarOffset(scrollbar));
2706
2707     return renderer().view().frameView().convertFromRenderer(&renderer(), rect);
2708 }
2709
2710 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
2711 {
2712     IntRect rect = renderer().view().frameView().convertToRenderer(&renderer(), parentRect);
2713     rect.move(-scrollbarOffset(scrollbar));
2714     return rect;
2715 }
2716
2717 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
2718 {
2719     IntPoint point = scrollbarPoint;
2720     point.move(scrollbarOffset(scrollbar));
2721     return renderer().view().frameView().convertFromRenderer(&renderer(), point);
2722 }
2723
2724 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
2725 {
2726     IntPoint point = renderer().view().frameView().convertToRenderer(&renderer(), parentPoint);
2727     point.move(-scrollbarOffset(scrollbar));
2728     return point;
2729 }
2730
2731 IntSize RenderLayer::contentsSize() const
2732 {
2733     return IntSize(scrollWidth(), scrollHeight());
2734 }
2735
2736 int RenderLayer::visibleHeight() const
2737 {
2738     return m_layerSize.height();
2739 }
2740
2741 int RenderLayer::visibleWidth() const
2742 {
2743     return m_layerSize.width();
2744 }
2745
2746 bool RenderLayer::shouldSuspendScrollAnimations() const
2747 {
2748     return renderer().view().frameView().shouldSuspendScrollAnimations();
2749 }
2750
2751 IntPoint RenderLayer::lastKnownMousePosition() const
2752 {
2753     return renderer().frame().eventHandler().lastKnownMousePosition();
2754 }
2755
2756 bool RenderLayer::isHandlingWheelEvent() const
2757 {
2758     return renderer().frame().eventHandler().isHandlingWheelEvent();
2759 }
2760
2761 IntRect RenderLayer::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const
2762 {
2763     if (!m_hBar)
2764         return IntRect();
2765
2766     const RenderBox* box = renderBox();
2767     const IntRect& scrollCorner = scrollCornerRect();
2768
2769     return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
2770         borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
2771         borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
2772         m_hBar->height());
2773 }
2774
2775 IntRect RenderLayer::rectForVerticalScrollbar(const IntRect& borderBoxRect) const
2776 {
2777     if (!m_vBar)
2778         return IntRect();
2779
2780     const RenderBox* box = renderBox();
2781     const IntRect& scrollCorner = scrollCornerRect();
2782
2783     return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
2784         borderBoxRect.y() + box->borderTop(),
2785         m_vBar->width(),
2786         borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
2787 }
2788
2789 LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
2790 {
2791     const RenderBox* box = renderBox();
2792     if (renderer().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2793         return minX + box->borderLeft();
2794     return maxX - box->borderRight() - m_vBar->width();
2795 }
2796
2797 LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
2798 {
2799     const RenderBox* box = renderBox();
2800     int x = minX + box->borderLeft();
2801     if (renderer().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2802         x += m_vBar ? m_vBar->width() : resizerCornerRect(this, box->pixelSnappedBorderBoxRect()).width();
2803     return x;
2804 }
2805
2806 IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
2807 {
2808     RenderBox* box = renderBox();
2809
2810     if (scrollbar == m_vBar.get())
2811         return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
2812
2813     if (scrollbar == m_hBar.get())
2814         return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2815     
2816     ASSERT_NOT_REACHED();
2817     return IntSize();
2818 }
2819
2820 void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
2821 {
2822 #if USE(ACCELERATED_COMPOSITING)
2823     if (scrollbar == m_vBar.get()) {
2824         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2825             layer->setNeedsDisplayInRect(rect);
2826             return;
2827         }
2828     } else {
2829         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2830             layer->setNeedsDisplayInRect(rect);
2831             return;
2832         }
2833     }
2834 #endif
2835     IntRect scrollRect = rect;
2836     RenderBox* box = renderBox();
2837     ASSERT(box);
2838     // If we are not yet inserted into the tree, there is no need to repaint.
2839     if (!box->parent())
2840         return;
2841
2842     if (scrollbar == m_vBar.get())
2843         scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
2844     else
2845         scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2846     LayoutRect repaintRect = scrollRect;
2847     renderBox()->flipForWritingMode(repaintRect);
2848     renderer().repaintRectangle(repaintRect);
2849 }
2850
2851 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
2852 {
2853 #if USE(ACCELERATED_COMPOSITING)
2854     if (GraphicsLayer* layer = layerForScrollCorner()) {
2855         layer->setNeedsDisplayInRect(rect);
2856         return;
2857     }
2858 #endif
2859     if (m_scrollCorner)
2860         m_scrollCorner->repaintRectangle(rect);
2861     if (m_resizer)
2862         m_resizer->repaintRectangle(rect);
2863 }
2864
2865 static inline RenderElement* rendererForScrollbar(RenderLayerModelObject& renderer)
2866 {
2867     if (Element* element = renderer.element()) {
2868         if (ShadowRoot* shadowRoot = element->containingShadowRoot()) {
2869             if (shadowRoot->type() == ShadowRoot::UserAgentShadowRoot)
2870                 return shadowRoot->hostElement()->renderer();
2871         }
2872     }
2873
2874     return &renderer;
2875 }
2876
2877 PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
2878 {
2879     RefPtr<Scrollbar> widget;
2880     RenderElement* actualRenderer = rendererForScrollbar(renderer());
2881     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
2882     if (hasCustomScrollbarStyle)
2883         widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->element());
2884     else {
2885         widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
2886         didAddScrollbar(widget.get(), orientation);
2887     }
2888     renderer().view().frameView().addChild(widget.get());
2889     return widget.release();
2890 }
2891
2892 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
2893 {
2894     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
2895     if (!scrollbar)
2896         return;
2897
2898     if (!scrollbar->isCustomScrollbar())
2899         willRemoveScrollbar(scrollbar.get(), orientation);
2900
2901     scrollbar->removeFromParent();
2902     scrollbar->disconnectFromScrollableArea();
2903     scrollbar = 0;
2904 }
2905
2906 bool RenderLayer::scrollsOverflow() const
2907 {
2908     if (!renderer().isBox())
2909         return false;
2910
2911     return toRenderBox(renderer()).scrollsOverflow();
2912 }
2913
2914 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
2915 {
2916     if (hasScrollbar == hasHorizontalScrollbar())
2917         return;
2918
2919     if (hasScrollbar)
2920         m_hBar = createScrollbar(HorizontalScrollbar);
2921     else
2922         destroyScrollbar(HorizontalScrollbar);
2923
2924     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2925     if (m_hBar)
2926         m_hBar->styleChanged();
2927     if (m_vBar)
2928         m_vBar->styleChanged();
2929
2930     // Force an update since we know the scrollbars have changed things.
2931 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2932     if (renderer().document().hasAnnotatedRegions())
2933         renderer().document().setAnnotatedRegionsDirty(true);
2934 #endif
2935 }
2936
2937 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
2938 {
2939     if (hasScrollbar == hasVerticalScrollbar())
2940         return;
2941
2942     if (hasScrollbar)
2943         m_vBar = createScrollbar(VerticalScrollbar);
2944     else
2945         destroyScrollbar(VerticalScrollbar);
2946
2947      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2948     if (m_hBar)
2949         m_hBar->styleChanged();
2950     if (m_vBar)
2951         m_vBar->styleChanged();
2952
2953     // Force an update since we know the scrollbars have changed things.
2954 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
2955     if (renderer().document().hasAnnotatedRegions())
2956         renderer().document().setAnnotatedRegionsDirty(true);
2957 #endif
2958 }
2959
2960 ScrollableArea* RenderLayer::enclosingScrollableArea() const
2961 {
2962     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2963         return scrollableLayer;
2964
2965     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
2966     // if the frame view isn't scrollable.
2967     return 0;
2968 }
2969
2970 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
2971 {
2972     if (!m_vBar || (m_vBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_vBar->shouldParticipateInHitTesting())))
2973         return 0;
2974     return m_vBar->width();
2975 }
2976
2977 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
2978 {
2979     if (!m_hBar || (m_hBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_hBar->shouldParticipateInHitTesting())))
2980         return 0;
2981     return m_hBar->height();
2982 }
2983
2984 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
2985 {
2986     // Currently the resize corner is either the bottom right corner or the bottom left corner.
2987     // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
2988     IntSize elementSize = size();
2989     if (renderer().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2990         elementSize.setWidth(0);
2991     IntPoint resizerPoint = IntPoint(elementSize);
2992     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2993     return localPoint - resizerPoint;
2994 }
2995
2996 bool RenderLayer::hasOverflowControls() const
2997 {
2998     return m_hBar || m_vBar || m_scrollCorner || renderer().style()->resize() != RESIZE_NONE;
2999 }
3000
3001 void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
3002 {
3003     if (!m_hBar && !m_vBar && !canResize())
3004         return;
3005     
3006     RenderBox* box = renderBox();
3007     if (!box)
3008         return;
3009
3010     const IntRect borderBox = box->pixelSnappedBorderBoxRect();
3011     const IntRect& scrollCorner = scrollCornerRect();
3012     IntRect absBounds(borderBox.location() + offsetFromRoot, borderBox.size());
3013     if (m_vBar) {
3014         IntRect vBarRect = rectForVerticalScrollbar(borderBox);
3015         vBarRect.move(offsetFromRoot);
3016         m_vBar->setFrameRect(vBarRect);
3017     }
3018     
3019     if (m_hBar) {
3020         IntRect hBarRect = rectForHorizontalScrollbar(borderBox);
3021         hBarRect.move(offsetFromRoot);
3022         m_hBar->setFrameRect(hBarRect);
3023     }
3024     
3025     if (m_scrollCorner)
3026         m_scrollCorner->setFrameRect(scrollCorner);
3027     if (m_resizer)
3028         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
3029
3030 #if USE(ACCELERATED_COMPOSITING)    
3031     if (isComposited())
3032         backing()->positionOverflowControlsLayers(offsetFromRoot);
3033 #endif
3034 }
3035
3036 int RenderLayer::scrollWidth() const
3037 {
3038     ASSERT(renderBox());
3039     if (m_scrollDimensionsDirty)
3040         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3041     return snapSizeToPixel(m_scrollSize.width(), renderBox()->clientLeft() + renderBox()->x());
3042 }
3043
3044 int RenderLayer::scrollHeight() const
3045 {
3046     ASSERT(renderBox());
3047     if (m_scrollDimensionsDirty)
3048         const_cast<RenderLayer*>(this)->computeScrollDimensions();
3049     return snapSizeToPixel(m_scrollSize.height(), renderBox()->clientTop() + renderBox()->y());
3050 }
3051
3052 LayoutUnit RenderLayer::overflowTop() const
3053 {
3054     RenderBox* box = renderBox();
3055     LayoutRect overflowRect(box->layoutOverflowRect());
3056     box->flipForWritingMode(overflowRect);
3057     return overflowRect.y();
3058 }
3059
3060 LayoutUnit RenderLayer::overflowBottom() const
3061 {
3062     RenderBox* box = renderBox();
3063     LayoutRect overflowRect(box->layoutOverflowRect());
3064     box->flipForWritingMode(overflowRect);
3065     return overflowRect.maxY();
3066 }
3067
3068 LayoutUnit RenderLayer::overflowLeft() const
3069 {
3070     RenderBox* box = renderBox();
3071     LayoutRect overflowRect(box->layoutOverflowRect());
3072     box->flipForWritingMode(overflowRect);
3073     return overflowRect.x();
3074 }
3075
3076 LayoutUnit RenderLayer::overflowRight() const
3077 {
3078     RenderBox* box = renderBox();
3079     LayoutRect overflowRect(box->layoutOverflowRect());
3080     box->flipForWritingMode(overflowRect);
3081     return overflowRect.maxX();
3082 }
3083
3084 void RenderLayer::computeScrollDimensions()
3085 {
3086     RenderBox* box = renderBox();
3087     ASSERT(box);
3088
3089     m_scrollDimensionsDirty = false;
3090
3091     m_scrollSize.setWidth(overflowRight() - overflowLeft());
3092     m_scrollSize.setHeight(overflowBottom() - overflowTop());
3093
3094     int scrollableLeftOverflow = overflowLeft() - box->borderLeft();
3095     int scrollableTopOverflow = overflowTop() - box->borderTop();
3096     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
3097 }
3098
3099 bool RenderLayer::hasScrollableHorizontalOverflow() const
3100 {
3101     return hasHorizontalOverflow() && renderBox()->scrollsOverflowX();
3102 }
3103
3104 bool RenderLayer::hasScrollableVerticalOverflow() const
3105 {
3106     return hasVerticalOverflow() && renderBox()->scrollsOverflowY();
3107 }
3108
3109 bool RenderLayer::hasHorizontalOverflow() const
3110 {
3111     ASSERT(!m_scrollDimensionsDirty);
3112
3113     return scrollWidth() > renderBox()->pixelSnappedClientWidth();
3114 }
3115
3116 bool RenderLayer::hasVerticalOverflow() const
3117 {
3118     ASSERT(!m_scrollDimensionsDirty);
3119
3120     return scrollHeight() > renderBox()->pixelSnappedClientHeight();
3121 }
3122
3123 void RenderLayer::updateScrollbarsAfterLayout()
3124 {
3125     RenderBox* box = renderBox();
3126     ASSERT(box);
3127
3128     // List box parts handle the scrollbars by themselves so we have nothing to do.
3129     if (box->style()->appearance() == ListboxPart)
3130         return;
3131
3132     bool hasHorizontalOverflow = this->hasHorizontalOverflow();
3133     bool hasVerticalOverflow = this->hasVerticalOverflow();
3134
3135     // overflow:scroll should just enable/disable.
3136     if (renderer().style()->overflowX() == OSCROLL)
3137         m_hBar->setEnabled(hasHorizontalOverflow);
3138     if (renderer().style()->overflowY() == OSCROLL)
3139         m_vBar->setEnabled(hasVerticalOverflow);
3140
3141     // overflow:auto may need to lay out again if scrollbars got added/removed.
3142     bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
3143     bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
3144
3145     if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
3146         if (box->hasAutoHorizontalScrollbar())
3147             setHasHorizontalScrollbar(hasHorizontalOverflow);
3148         if (box->hasAutoVerticalScrollbar())
3149             setHasVerticalScrollbar(hasVerticalOverflow);
3150
3151         updateSelfPaintingLayer();
3152
3153         // Force an update since we know the scrollbars have changed things.
3154 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(DRAGGABLE_REGION)
3155         if (renderer().document().hasAnnotatedRegions())
3156             renderer().document().setAnnotatedRegionsDirty(true);
3157 #endif
3158
3159         renderer().repaint();
3160
3161         if (renderer().style()->overflowX() == OAUTO || renderer().style()->overflowY() == OAUTO) {
3162             if (!m_inOverflowRelayout) {
3163                 // Our proprietary overflow: overlay value doesn't trigger a layout.
3164                 m_inOverflowRelayout = true;
3165                 renderer().setNeedsLayout(MarkOnlyThis);
3166                 if (renderer().isRenderBlock()) {
3167                     RenderBlock& block = toRenderBlock(renderer());
3168                     block.scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
3169                     block.layoutBlock(true);
3170                 } else
3171                     renderer().layout();
3172                 m_inOverflowRelayout = false;
3173             }
3174         }
3175     }
3176
3177     // Set up the range (and page step/line step).
3178     if (m_hBar) {
3179         int clientWidth = box->pixelSnappedClientWidth();
3180         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
3181         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3182         m_hBar->setProportion(clientWidth, m_scrollSize.width());
3183     }
3184     if (m_vBar) {
3185         int clientHeight = box->pixelSnappedClientHeight();
3186         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
3187         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
3188         m_vBar->setProportion(clientHeight, m_scrollSize.height());
3189     }
3190
3191     updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
3192 }
3193
3194 void RenderLayer::updateScrollInfoAfterLayout()
3195 {
3196     RenderBox* box = renderBox();
3197     if (!box)
3198         return;
3199
3200     m_scrollDimensionsDirty = true;
3201     IntSize originalScrollOffset = scrollOffset();
3202
3203     computeScrollDimensions();
3204
3205     if (box->style()->overflowX() != OMARQUEE) {
3206         // Layout may cause us to be at an invalid scroll position. In this case we need
3207         // to pull our scroll offsets back to the max (or push them up to the min).
3208         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset());
3209         if (clampedScrollOffset != scrollOffset())
3210             scrollToOffset(clampedScrollOffset);
3211     }
3212
3213     updateScrollbarsAfterLayout();
3214
3215     if (originalScrollOffset != scrollOffset())
3216         scrollToOffsetWithoutAnimation(IntPoint(scrollOffset()));
3217
3218 #if USE(ACCELERATED_COMPOSITING)
3219     // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
3220     if (compositor().updateLayerCompositingState(*this))
3221         compositor().setCompositingLayersNeedRebuild();
3222 #endif
3223 }
3224
3225 bool RenderLayer::overflowControlsIntersectRect(const IntRect& localRect) const
3226 {
3227     const IntRect borderBox = renderBox()->pixelSnappedBorderBoxRect();
3228
3229     if (rectForHorizontalScrollbar(borderBox).intersects(localRect))
3230         return true;
3231
3232     if (rectForVerticalScrollbar(borderBox).intersects(localRect))
3233         return true;
3234
3235     if (scrollCornerRect().intersects(localRect))
3236         return true;
3237     
3238     if (resizerCornerRect(this, borderBox).intersects(localRect))
3239         return true;
3240
3241     return false;
3242 }
3243
3244 void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
3245 {
3246     // Don't do anything if we have no overflow.
3247     if (!renderer().hasOverflowClip())
3248         return;
3249
3250     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
3251     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
3252     // will be false, and we should just tell the root layer that there are overlay scrollbars
3253     // that need to be painted. That will cause the second pass through the layer tree to run,
3254     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
3255     // second pass doesn't need to re-enter the RenderTree to get it right.
3256     if (hasOverlayScrollbars() && !paintingOverlayControls) {
3257         m_cachedOverlayScrollbarOffset = paintOffset;
3258 #if USE(ACCELERATED_COMPOSITING)
3259         // It's not necessary to do the second pass if the scrollbars paint into layers.
3260         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
3261             return;
3262 #endif
3263         IntRect localDamgeRect = damageRect;
3264         localDamgeRect.moveBy(-paintOffset);
3265         if (!overflowControlsIntersectRect(localDamgeRect))
3266             return;
3267
3268         RenderLayer* paintingRoot = 0;
3269 #if USE(ACCELERATED_COMPOSITING)
3270         paintingRoot = enclosingCompositingLayer();
3271 #endif
3272         if (!paintingRoot)
3273             paintingRoot = renderer().view().layer();
3274
3275         paintingRoot->setContainsDirtyOverlayScrollbars(true);
3276         return;
3277     }
3278
3279     // This check is required to avoid painting custom CSS scrollbars twice.
3280     if (paintingOverlayControls && !hasOverlayScrollbars())
3281         return;
3282
3283     IntPoint adjustedPaintOffset = paintOffset;
3284     if (paintingOverlayControls)
3285         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
3286
3287     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
3288     // widgets can move without layout occurring (most notably when you scroll a document that
3289     // contains fixed positioned elements).
3290     positionOverflowControls(toIntSize(adjustedPaintOffset));
3291
3292     // Now that we're sure the scrollbars are in the right place, paint them.
3293     if (m_hBar
3294 #if USE(ACCELERATED_COMPOSITING)
3295         && !layerForHorizontalScrollbar()
3296 #endif
3297               )
3298         m_hBar->paint(context, damageRect);
3299     if (m_vBar
3300 #if USE(ACCELERATED_COMPOSITING)
3301         && !layerForVerticalScrollbar()
3302 #endif
3303               )
3304         m_vBar->paint(context, damageRect);
3305
3306 #if USE(ACCELERATED_COMPOSITING)
3307     if (layerForScrollCorner())
3308         return;
3309 #endif
3310
3311     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
3312     // edge of the box.
3313     paintScrollCorner(context, adjustedPaintOffset, damageRect);
3314     
3315     // Paint our resizer last, since it sits on top of the scroll corner.
3316     paintResizer(context, adjustedPaintOffset, damageRect);
3317 }
3318
3319 void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
3320 {
3321     RenderBox* box = renderBox();
3322     ASSERT(box);
3323
3324     IntRect absRect = scrollCornerRect();
3325     absRect.moveBy(paintOffset);
3326     if (!absRect.intersects(damageRect))
3327         return;
3328
3329     if (context->updatingControlTints()) {
3330         updateScrollCornerStyle();
3331         return;
3332     }
3333
3334     if (m_scrollCorner) {
3335         m_scrollCorner->paintIntoRect(context, paintOffset, absRect);
3336         return;
3337     }
3338
3339     // We don't want to paint white if we have overlay scrollbars, since we need
3340     // to see what is behind it.
3341     if (!hasOverlayScrollbars())
3342         context->fillRect(absRect, Color::white, box->style()->colorSpace());
3343 }
3344
3345 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
3346 {
3347     float deviceScaleFactor = WebCore::deviceScaleFactor(&renderer().frame());
3348
3349     RefPtr<Image> resizeCornerImage;
3350     IntSize cornerResizerSize;
3351     if (deviceScaleFactor >= 2) {
3352         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
3353         resizeCornerImage = resizeCornerImageHiRes;
3354         cornerResizerSize = resizeCornerImage->size();
3355         cornerResizerSize.scale(0.5f);
3356     } else {
3357         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
3358         resizeCornerImage = resizeCornerImageLoRes;
3359         cornerResizerSize = resizeCornerImage->size();
3360     }
3361
3362     if (renderer().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
3363         context->save();
3364         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
3365         context->scale(FloatSize(-1.0, 1.0));
3366         context->drawImage(resizeCornerImage.get(), renderer().style()->colorSpace(), IntRect(IntPoint(), cornerResizerSize));
3367         context->restore();
3368         return;
3369     }
3370     IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
3371     context->drawImage(resizeCornerImage.get(), renderer().style()->colorSpace(), imageRect);
3372 }
3373
3374 void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
3375 {
3376     if (renderer().style()->resize() == RESIZE_NONE)
3377         return;
3378
3379     RenderBox* box = renderBox();
3380     ASSERT(box);
3381
3382     IntRect absRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
3383     absRect.moveBy(paintOffset);
3384     if (!absRect.intersects(damageRect))
3385         return;
3386
3387     if (context->updatingControlTints()) {
3388         updateResizerStyle();
3389         return;
3390     }
3391     
3392     if (m_resizer) {
3393         m_resizer->paintIntoRect(context, paintOffset, absRect);
3394         return;
3395     }
3396
3397     drawPlatformResizerImage(context, absRect);
3398
3399     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
3400     // Clipping will exclude the right and bottom edges of this frame.
3401     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
3402         GraphicsContextStateSaver stateSaver(*context);
3403         context->clip(absRect);
3404         IntRect largerCorner = absRect;
3405         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
3406         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
3407         context->setStrokeThickness(1.0f);
3408         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
3409         context->drawRect(largerCorner);
3410     }
3411 }
3412
3413 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
3414 {
3415     if (!canResize())
3416         return false;
3417     
3418     RenderBox* box = renderBox();
3419     ASSERT(box);
3420
3421     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
3422
3423     IntRect localBounds(0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
3424     return resizerCornerRect(this, localBounds).contains(localPoint);
3425 }
3426
3427 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
3428 {
3429     if (!m_hBar && !m_vBar && !canResize())
3430         return false;
3431
3432     RenderBox* box = renderBox();
3433     ASSERT(box);
3434     
3435     IntRect resizeControlRect;
3436     if (renderer().style()->resize() != RESIZE_NONE) {
3437         resizeControlRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
3438         if (resizeControlRect.contains(localPoint))
3439             return true;
3440     }
3441
3442     int resizeControlSize = max(resizeControlRect.height(), 0);
3443
3444     // FIXME: We should hit test the m_scrollCorner and pass it back through the result.
3445
3446     if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
3447         LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
3448                             box->borderTop(),
3449                             m_vBar->width(),
3450                             box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
3451         if (vBarRect.contains(localPoint)) {
3452             result.setScrollbar(m_vBar.get());
3453             return true;
3454         }
3455     }
3456
3457     resizeControlSize = max(resizeControlRect.width(), 0);
3458     if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
3459         LayoutRect hBarRect(horizontalScrollbarStart(0),
3460                             box->height() - box->borderBottom() - m_hBar->height(),
3461                             box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
3462                             m_hBar->height());
3463         if (hBarRect.contains(localPoint)) {
3464             result.setScrollbar(m_hBar.get());
3465             return true;
3466         }
3467     }
3468
3469     return false;
3470 }
3471
3472 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
3473 {
3474     return ScrollableArea::scroll(direction, granularity, multiplier);
3475 }
3476
3477 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* subtreePaintRoot, RenderRegion* region, PaintLayerFlags paintFlags)
3478 {
3479     OverlapTestRequestMap overlapTestRequests;
3480
3481     LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, LayoutSize(), subtreePaintRoot, region, &overlapTestRequests);
3482     paintLayer(context, paintingInfo, paintFlags);
3483
3484     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
3485     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
3486         it->key->setOverlapTestResult(false);
3487 }
3488
3489 void RenderLayer::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* subtreePaintRoot)
3490 {
3491     if (!m_containsDirtyOverlayScrollbars)
3492         return;
3493
3494     LayerPaintingInfo paintingInfo(this, enclosingIntRect(damageRect), paintBehavior, LayoutSize(), subtreePaintRoot);
3495     paintLayer(context, paintingInfo, PaintLayerPaintingOverlayScrollbars);
3496
3497     m_containsDirtyOverlayScrollbars = false;
3498 }
3499
3500 static bool inContainingBlockChain(RenderLayer* startLayer, RenderLayer* endLayer)
3501 {
3502     if (startLayer == endLayer)
3503         return true;
3504     
3505     RenderView* view = &startLayer->renderer().view();
3506     for (RenderBlock* currentBlock = startLayer->renderer().containingBlock(); currentBlock && currentBlock != view; currentBlock = currentBlock->containingBlock()) {
3507         if (currentBlock->layer() == endLayer)
3508             return true;
3509     }
3510     
3511     return false;
3512 }
3513
3514 void RenderLayer::clipToRect(RenderLayer* rootLayer, GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect,
3515                              BorderRadiusClippingRule rule)
3516 {
3517     if (clipRect.rect() != paintDirtyRect) {
3518         context->save();
3519         context->clip(pixelSnappedIntRect(clipRect.rect()));
3520     }
3521
3522     if (!clipRect.hasRadius())
3523         return;
3524
3525     // If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
3526     // any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
3527     // containing block chain so we check that also.
3528     for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
3529         if (layer->renderer().hasOverflowClip() && layer->renderer().style()->hasBorderRadius() && inContainingBlockChain(this, layer)) {
3530                 LayoutPoint delta;
3531                 layer->convertToLayerCoords(rootLayer, delta);
3532                 context->clipRoundedRect(layer->renderer().style()->getRoundedInnerBorderFor(LayoutRect(delta, layer->size())));
3533         }
3534
3535         if (layer == rootLayer)
3536             break;
3537     }
3538 }
3539
3540 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
3541 {
3542     if (clipRect.rect() == paintDirtyRect)
3543         return;
3544     context->restore();
3545 }
3546
3547 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
3548 {
3549     Vector<OverlapTestRequestClient*> overlappedRequestClients;
3550     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
3551     LayoutRect boundingBox = layer->boundingBox(rootLayer);
3552     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
3553         if (!boundingBox.intersects(it->value))
3554             continue;
3555
3556         it->key->setOverlapTestResult(true);
3557         overlappedRequestClients.append(it->key);
3558     }
3559     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
3560         overlapTestRequests.remove(overlappedRequestClients[i]);
3561 }
3562
3563 #if USE(ACCELERATED_COMPOSITING)
3564
3565 static inline bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
3566 {
3567     return paintingReflection && !layer->has3DTransform();
3568 }
3569
3570 #endif
3571     
3572 static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
3573 {
3574     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
3575     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
3576     // will do a full repaint().
3577     if (layer->renderer().document().didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer().isRoot())
3578         return true;
3579
3580     // Avoid painting all layers if the document is in a state where visual updates aren't allowed.
3581     // A full repaint will occur in Document::implicitClose() if painting is suppressed here.
3582     if (!layer->renderer().document().visualUpdatesAllowed())
3583         return true;
3584
3585     return false;
3586 }
3587
3588 #if USE(ACCELERATED_COMPOSITING)
3589
3590 static inline bool paintForFixedRootBackground(const RenderLayer* layer, RenderLayer::PaintLayerFlags paintFlags)
3591 {
3592     return layer->renderer().isRoot() && (paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
3593 }
3594
3595 #endif
3596
3597 void RenderLayer::paintLayer(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3598 {
3599 #if USE(ACCELERATED_COMPOSITING)
3600     if (isComposited()) {
3601         // The updatingControlTints() painting pass goes through compositing layers,
3602         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
3603         if (context->updatingControlTints() || (paintingInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers))
3604             paintFlags |= PaintLayerTemporaryClipRects;
3605         else if (!backing()->paintsIntoWindow()
3606             && !backing()->paintsIntoCompositedAncestor()
3607             && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)
3608             && !paintForFixedRootBackground(this, paintFlags)) {
3609             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
3610             return;
3611         }
3612     } else if (viewportConstrainedNotCompositedReason() == NotCompositedForBoundsOutOfView) {
3613         // Don't paint out-of-view viewport constrained layers (when doing prepainting) because they will never be visible
3614         // unless their position or viewport size is changed.
3615         ASSERT(renderer().style()->position() == FixedPosition);
3616         return;
3617     }
3618 #endif
3619
3620     // Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
3621     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
3622         return;
3623
3624     if (shouldSuppressPaintingLayer(this))
3625         return;
3626     
3627     // If this layer is totally invisible then there is nothing to paint.
3628     if (!renderer().opacity())
3629         return;
3630
3631     if (paintsWithTransparency(paintingInfo.paintBehavior))
3632         paintFlags |= PaintLayerHaveTransparency;
3633
3634     // PaintLayerAppliedTransform is used in RenderReplica, to avoid applying the transform twice.
3635     if (paintsWithTransform(paintingInfo.paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
3636         TransformationMatrix layerTransform = renderableTransform(paintingInfo.paintBehavior);
3637         // If the transform can't be inverted, then don't paint anything.
3638         if (!layerTransform.isInvertible())
3639             return;
3640
3641         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
3642         // layer from the parent now, assuming there is a parent
3643         if (paintFlags & PaintLayerHaveTransparency) {
3644             if (parent())
3645                 parent()->beginTransparencyLayers(context, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.paintBehavior);
3646             else
3647                 beginTransparencyLayers(context, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.paintBehavior);
3648         }
3649
3650         if (enclosingPaginationLayer()) {
3651             paintTransformedLayerIntoFragments(context, paintingInfo, paintFlags);
3652             return;
3653         }
3654
3655         // Make sure the parent's clip rects have been calculated.
3656         ClipRect clipRect = paintingInfo.paintDirtyRect;
3657         if (parent()) {
3658             ClipRectsContext clipRectsContext(paintingInfo.rootLayer, paintingInfo.region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
3659                 IgnoreOverlayScrollbarSize, (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip);
3660             clipRect = backgroundClipRect(clipRectsContext);
3661             clipRect.intersect(paintingInfo.paintDirtyRect);
3662         
3663             // Push the parent coordinate space's clip.
3664             parent()->clipToRect(paintingInfo.rootLayer, context, paintingInfo.paintDirtyRect, clipRect);
3665         }
3666
3667         paintLayerByApplyingTransform(context, paintingInfo, paintFlags);
3668
3669         // Restore the clip.
3670         if (parent())
3671             parent()->restoreClip(context, paintingInfo.paintDirtyRect, clipRect);
3672
3673         return;
3674     }
3675     
3676     paintLayerContentsAndReflection(context, paintingInfo, paintFlags);
3677 }
3678
3679 void RenderLayer::paintLayerContentsAndReflection(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3680 {
3681     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3682
3683     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3684
3685     // Paint the reflection first if we have one.
3686     if (m_reflection && !m_paintingInsideReflection) {
3687         // Mark that we are now inside replica painting.
3688         m_paintingInsideReflection = true;
3689         reflectionLayer()->paintLayer(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
3690         m_paintingInsideReflection = false;
3691     }
3692
3693     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
3694     paintLayerContents(context, paintingInfo, localPaintFlags);
3695 }
3696
3697 bool RenderLayer::setupFontSubpixelQuantization(GraphicsContext* context, bool& didQuantizeFonts)
3698 {
3699     if (context->paintingDisabled())
3700         return false;
3701
3702     bool scrollingOnMainThread = true;
3703 #if ENABLE(THREADED_SCROLLING)
3704     if (Page* page = renderer().frame().page()) {
3705         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
3706             scrollingOnMainThread = scrollingCoordinator->shouldUpdateScrollLayerPositionOnMainThread();
3707     }
3708 #endif
3709
3710     // FIXME: We shouldn't have to disable subpixel quantization for overflow clips or subframes once we scroll those
3711     // things on the scrolling thread.
3712     bool contentsScrollByPainting = (renderer().hasOverflowClip() && !usesCompositedScrolling()) || (renderer().frame().ownerElement());
3713     if (scrollingOnMainThread || contentsScrollByPainting) {
3714         didQuantizeFonts = context->shouldSubpixelQuantizeFonts();
3715         context->setShouldSubpixelQuantizeFonts(false);
3716         return true;
3717     }
3718     return false;
3719 }
3720
3721 bool RenderLayer::setupClipPath(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, const LayoutPoint& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed)
3722 {
3723     if (!renderer().hasClipPath() || context->paintingDisabled())
3724         return false;
3725
3726     RenderStyle* style = renderer().style();
3727
3728     ASSERT(style->clipPath());
3729     if (style->clipPath()->getOperationType() == ClipPathOperation::SHAPE) {
3730         ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(style->clipPath());
3731
3732         if (!rootRelativeBoundsComputed) {
3733             rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
3734             rootRelativeBoundsComputed = true;
3735         }
3736
3737         context->save();
3738         context->clipPath(clipPath->path(rootRelativeBounds), clipPath->windRule());
3739         return true;
3740     }
3741
3742 #if ENABLE(SVG)
3743     if (style->clipPath()->getOperationType() == ClipPathOperation::REFERENCE) {
3744         ReferenceClipPathOperation* referenceClipPathOperation = static_cast<ReferenceClipPathOperation*>(style->clipPath());
3745         Element* element = renderer().document().getElementById(referenceClipPathOperation->fragment());
3746         if (element && element->hasTagName(SVGNames::clipPathTag) && element->renderer()) {
3747             if (!rootRelativeBoundsComputed) {
3748                 rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
3749                 rootRelativeBoundsComputed = true;
3750             }
3751
3752             // FIXME: This should use a safer cast such as toRenderSVGResourceContainer().
3753             // FIXME: Should this do a context->save() and return true so we restore the context?
3754             static_cast<RenderSVGResourceClipper*>(element->renderer())->applyClippingToContext(&renderer(), rootRelativeBounds, paintingInfo.paintDirtyRect, context);
3755         }
3756     }
3757 #endif
3758
3759     return false;
3760 }
3761
3762 #if ENABLE(CSS_FILTERS)
3763
3764 PassOwnPtr<FilterEffectRendererHelper> RenderLayer::setupFilters(GraphicsContext* context, LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags, const LayoutPoint& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed)
3765 {
3766     if (context->paintingDisabled())
3767         return nullptr;
3768
3769     if (paintFlags & PaintLayerPaintingOverlayScrollbars)
3770         return nullptr;
3771
3772     FilterInfo* filterInfo = FilterInfo::getIfExists(*this);
3773     bool hasPaintedFilter = filterInfo && filterInfo->renderer() && paintsWithFilters();
3774     if (!hasPaintedFilter)
3775         return nullptr;
3776
3777     OwnPtr<FilterEffectRendererHelper> filterPainter = adoptPtr(new FilterEffectRendererHelper(hasPaintedFilter));
3778     if (!filterPainter->haveFilterEffect())
3779         return nullptr;
3780     
3781     LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
3782     filterRepaintRect.move(offsetFromRoot.x(), offsetFromRoot.y());
3783
3784     if (!rootRelativeBoundsComputed) {
3785         rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
3786         rootRelativeBoundsComputed = true;
3787     }
3788
3789     if (filterPainter->prepareFilterEffect(this, rootRelativeBounds, paintingInfo.paintDirtyRect, filterRepaintRect)) {
3790         // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
3791         filterInfo->resetDirtySourceRect();
3792
3793         if (!filterPainter->beginFilterEffect())
3794             return nullptr;
3795
3796         // Check that we didn't fail to allocate the graphics context for the offscreen buffer.
3797         ASSERT(filterPainter->hasStartedFilterEffect());
3798
3799         paintingInfo.paintDirtyRect = filterPainter->repaintRect();
3800         // If the filter needs the full source image, we need to avoid using the clip rectangles.
3801         // Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
3802         // Note that we will still apply the clipping on the final rendering of the filter.
3803         paintingInfo.clipToDirtyRect = !filterInfo->renderer()->hasFilterThatMovesPixels();
3804         return filterPainter.release();
3805     }
3806     return nullptr;
3807 }
3808
3809 GraphicsContext* RenderLayer::applyFilters(FilterEffectRendererHelper* filterPainter, GraphicsContext* originalContext, LayerPaintingInfo& paintingInfo, LayerFragments& layerFragments)
3810 {
3811     ASSERT(filterPainter->hasStartedFilterEffect());
3812     // Apply the correct clipping (ie. overflow: hidden).
3813     // FIXME: It is incorrect to just clip to the damageRect here once multiple fragments are involved.
3814     ClipRect backgroundRect = layerFragments.isEmpty() ? ClipRect() : layerFragments[0].backgroundRect;
3815     clipToRect(paintingInfo.rootLayer, originalContext, paintingInfo.paintDirtyRect, backgroundRect);
3816     filterPainter->applyFilterEffect(originalContext);
3817     restoreClip(originalContext, paintingInfo.paintDirtyRect, backgroundRect);
3818     return originalContext;
3819 }
3820
3821 #endif
3822
3823 // Helper for the sorting of layers by z-index.
3824 static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
3825 {
3826     return first->zIndex() < second->zIndex();
3827 }
3828
3829 // Paint the layers associated with the fixed positioned elements in named flows.
3830 // These layers should not be painted in a similar way as the other elements collected in
3831 // named flows - regions -> named flows - since we do not want them to be clipped to the
3832 // regions viewport.
3833 void RenderLayer::paintFixedLayersInNamedFlows(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3834 {
3835     if (!isRootLayer())
3836         return;
3837
3838     // Get the named flows for the view
3839     if (!renderer().view().hasRenderNamedFlowThreads())
3840         return;
3841
3842     // Collect the fixed layers in a list to be painted
3843     Vector<RenderLayer*> fixedLayers;
3844     renderer().view().flowThreadController().collectFixedPositionedLayers(fixedLayers);
3845
3846     // Sort the fixed layers list
3847     std::stable_sort(fixedLayers.begin(), fixedLayers.end(), compareZIndex);
3848
3849     // Paint the layers
3850     for (size_t i = 0; i < fixedLayers.size(); ++i) {
3851         RenderLayer* fixedLayer = fixedLayers.at(i);
3852         fixedLayer->paintLayer(context, paintingInfo, paintFlags);
3853     }
3854 }
3855
3856 void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
3857 {
3858     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3859
3860     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3861     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
3862     bool isSelfPaintingLayer = this->isSelfPaintingLayer();
3863     bool isPaintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
3864     bool isPaintingScrollingContent = paintFlags & PaintLayerPaintingCompositingScrollingPhase;
3865     bool isPaintingCompositedForeground = paintFlags & PaintLayerPaintingCompositingForegroundPhase;
3866     bool isPaintingCompositedBackground = paintFlags & PaintLayerPaintingCompositingBackgroundPhase;
3867     bool isPaintingOverflowContents = paintFlags & PaintLayerPaintingOverflowContents;
3868     // Outline always needs to be painted even if we have no visible content. Also,
3869     // the outline is painted in the background phase during composited scrolling.
3870     // If it were painted in the foreground phase, it would move with the scrolled
3871     // content. When not composited scrolling, the outline is painted in the
3872     // foreground phase. Since scrolled contents are moved by repainting in this
3873     // case, the outline won't get 'dragged along'.
3874     bool shouldPaintOutline = isSelfPaintingLayer && !isPaintingOverlayScrollbars
3875         && ((isPaintingScrollingContent && isPaintingCompositedBackground)
3876         || (!isPaintingScrollingContent && isPaintingCompositedForeground));
3877     bool shouldPaintContent = m_hasVisibleContent && isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3878
3879     if (localPaintFlags & PaintLayerPaintingRootBackgroundOnly && !renderer().isRenderView() && !renderer().isRoot())
3880         return;
3881
3882     // Ensure our lists are up-to-date.
3883     updateLayerListsIfNeeded();
3884
3885     // Do not paint the fixed positioned layers if the paint root is the named flow,
3886     // if the paint originates at region level.
3887     if (paintingInfo.rootLayer->isOutOfFlowRenderFlowThread()
3888         && renderer().fixedPositionedWithNamedFlowContainingBlock())
3889         return;
3890
3891     LayoutPoint offsetFromRoot;
3892     convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);
3893
3894     LayoutRect rootRelativeBounds;
3895     bool rootRelativeBoundsComputed = false;
3896
3897     // FIXME: We shouldn't have to disable subpixel quantization for overflow clips or subframes once we scroll those
3898     // things on the scrolling thread.
3899     bool didQuantizeFonts = true;
3900     bool needToAdjustSubpixelQuantization = setupFontSubpixelQuantization(context, didQuantizeFonts);
3901
3902     // Apply clip-path to context.
3903     bool hasClipPath = setupClipPath(context, paintingInfo, offsetFromRoot, rootRelativeBounds, rootRelativeBoundsComputed);
3904
3905     LayerPaintingInfo localPaintingInfo(paintingInfo);
3906
3907     GraphicsContext* transparencyLayerContext = context;
3908 #if ENABLE(CSS_FILTERS)
3909     OwnPtr<FilterEffectRendererHelper> filterPainter = setupFilters(context, localPaintingInfo, paintFlags, offsetFromRoot, rootRelativeBounds, rootRelativeBoundsComputed);
3910     if (filterPainter) {
3911         context = filterPainter->filterContext();
3912         if (context != transparencyLayerContext && haveTransparency) {
3913             // 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.
3914             beginTransparencyLayers(transparencyLayerContext, localPaintingInfo.rootLayer, paintingInfo.paintDirtyRect, localPaintingInfo.paintBehavior);
3915         }
3916     }
3917 #endif
3918
3919     // If this layer's renderer is a child of the subtreePaintRoot, we render unconditionally, which
3920     // is done by passing a nil subtreePaintRoot down to our renderer (as if no subtreePaintRoot was ever set).
3921     // Otherwise, our renderer tree may or may not contain the subtreePaintRoot root, so we pass that root along
3922     // so it will be tested against as we descend through the renderers.
3923     RenderObject* subtreePaintRootForRenderer = 0;
3924     if (localPaintingInfo.subtreePaintRoot && !renderer().isDescendantOf(localPaintingInfo.subtreePaintRoot))
3925         subtreePaintRootForRenderer = localPaintingInfo.subtreePaintRoot;
3926
3927     if (localPaintingInfo.overlapTestRequests && isSelfPaintingLayer)
3928         performOverlapTests(*localPaintingInfo.overlapTestRequests, localPaintingInfo.rootLayer, this);
3929
3930     bool forceBlackText = localPaintingInfo.paintBehavior & PaintBehaviorForceBlackText;
3931     bool selectionOnly  = localPaintingInfo.paintBehavior & PaintBehaviorSelectionOnly;
3932     
3933     PaintBehavior paintBehavior = PaintBehaviorNormal;
3934     if (localPaintFlags & PaintLayerPaintingSkipRootBackground)
3935         paintBehavior |= PaintBehaviorSkipRootBackground;
3936     else if (localPaintFlags & PaintLayerPaintingRootBackgroundOnly)
3937         paintBehavior |= PaintBehaviorRootBackgroundOnly;
3938
3939     LayerFragments layerFragments;
3940     if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
3941         // 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
3942         // fragment should paint. If the parent's filter dictates full repaint to ensure proper filter effect,
3943         // use the overflow clip as dirty rect, instead of no clipping. It maintains proper clipping for overflow::scroll.
3944         LayoutRect paintDirtyRect = localPaintingInfo.paintDirtyRect;
3945         if (!paintingInfo.clipToDirtyRect && renderer().hasOverflowClip()) {
3946             // We can turn clipping back by requesting full repaint for the overflow area.
3947             localPaintingInfo.clipToDirtyRect = true;
3948             paintDirtyRect = selfClipRect();
3949         }
3950         collectFragments(layerFragments, localPaintingInfo.rootLayer, localPaintingInfo.region, paintDirtyRect,
3951             (localPaintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, IgnoreOverlayScrollbarSize,
3952             (isPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip, &offsetFromRoot);
3953         updatePaintingInfoForFragments(layerFragments, localPaintingInfo, localPaintFlags, shouldPaintContent, &offsetFromRoot);
3954     }
3955     
3956     if (isPaintingCompositedBackground) {
3957         // Paint only the backgrounds for all of the fragments of the layer.
3958         if (shouldPaintContent && !selectionOnly)
3959             paintBackgroundForFragments(layerFragments, context, transparencyLayerContext, paintingInfo.paintDirtyRect, haveTransparency,
3960                 localPaintingInfo, paintBehavior, subtreePaintRootForRenderer);
3961     }
3962
3963     // Now walk the sorted list of children with negative z-indices.
3964     if ((isPaintingScrollingContent && isPaintingOverflowContents) || (!isPaintingScrollingContent && isPaintingCompositedBackground))
3965         paintList(negZOrderList(), context, localPaintingInfo, localPaintFlags);
3966     
3967     if (isPaintingCompositedForeground) {
3968         if (shouldPaintContent)