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