Rename first/second to key/value in HashMap iterators
[WebKit-https.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
489 void RenderLayer::computeRepaintRectsIncludingDescendants()
490 {
491     // FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
492     // We should make this more efficient.
493     computeRepaintRects();
494
495     for (RenderLayer* layer = firstChild(); layer; layer = layer->nextSibling())
496         layer->computeRepaintRectsIncludingDescendants();
497 }
498
499 void RenderLayer::clearRepaintRects()
500 {
501     ASSERT(!m_hasVisibleContent);
502     ASSERT(!m_visibleContentStatusDirty);
503
504     m_repaintRect = IntRect();
505     m_outlineBox = IntRect();
506 }
507
508 void RenderLayer::updateLayerPositionsAfterScroll(UpdateLayerPositionsAfterScrollFlags flags)
509 {
510     // FIXME: This shouldn't be needed, but there are some corner cases where
511     // these flags are still dirty. Update so that the check below is valid.
512     updateDescendantDependentFlags();
513
514     // If we have no visible content and no visible descendants, there is no point recomputing
515     // our rectangles as they will be empty. If our visibility changes, we are expected to
516     // recompute all our positions anyway.
517     if (!m_hasVisibleDescendant && !m_hasVisibleContent)
518         return;
519
520     updateLayerPosition();
521
522     if ((flags & HasSeenViewportConstrainedAncestor) || renderer()->style()->hasViewportConstrainedPosition()) {
523         // FIXME: Is it worth passing the offsetFromRoot around like in updateLayerPositions?
524         computeRepaintRects();
525         flags |= HasSeenViewportConstrainedAncestor;
526     } else if ((flags & HasSeenAncestorWithOverflowClip) && !m_canSkipRepaintRectsUpdateOnScroll) {
527         // If we have seen an overflow clip, we should update our repaint rects as clippedOverflowRectForRepaint
528         // intersects it with our ancestor overflow clip that may have moved.
529         computeRepaintRects();
530     }
531
532     if (renderer()->hasOverflowClip())
533         flags |= HasSeenAncestorWithOverflowClip;
534
535     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
536         child->updateLayerPositionsAfterScroll(flags);
537
538     // We don't update our reflection as scrolling is a translation which does not change the size()
539     // of an object, thus RenderReplica will still repaint itself properly as the layer position was
540     // updated above.
541
542     if (m_marquee)
543         m_marquee->updateMarqueePosition();
544 }
545
546 void RenderLayer::updateTransform()
547 {
548     // hasTransform() on the renderer is also true when there is transform-style: preserve-3d or perspective set,
549     // so check style too.
550     bool hasTransform = renderer()->hasTransform() && renderer()->style()->hasTransform();
551     bool had3DTransform = has3DTransform();
552
553     bool hadTransform = m_transform;
554     if (hasTransform != hadTransform) {
555         if (hasTransform)
556             m_transform = adoptPtr(new TransformationMatrix);
557         else
558             m_transform.clear();
559         
560         // Layers with transforms act as clip rects roots, so clear the cached clip rects here.
561         clearClipRectsIncludingDescendants();
562     }
563     
564     if (hasTransform) {
565         RenderBox* box = renderBox();
566         ASSERT(box);
567         m_transform->makeIdentity();
568         box->style()->applyTransform(*m_transform, box->pixelSnappedBorderBoxRect().size(), RenderStyle::IncludeTransformOrigin);
569         makeMatrixRenderable(*m_transform, canRender3DTransforms());
570     }
571
572     if (had3DTransform != has3DTransform())
573         dirty3DTransformedDescendantStatus();
574 }
575
576 TransformationMatrix RenderLayer::currentTransform() const
577 {
578     if (!m_transform)
579         return TransformationMatrix();
580
581 #if USE(ACCELERATED_COMPOSITING)
582     if (renderer()->style()->isRunningAcceleratedAnimation()) {
583         TransformationMatrix currTransform;
584         RefPtr<RenderStyle> style = renderer()->animation()->getAnimatedStyleForRenderer(renderer());
585         style->applyTransform(currTransform, renderBox()->pixelSnappedBorderBoxRect().size(), RenderStyle::IncludeTransformOrigin);
586         makeMatrixRenderable(currTransform, canRender3DTransforms());
587         return currTransform;
588     }
589 #endif
590
591     return *m_transform;
592 }
593
594 TransformationMatrix RenderLayer::renderableTransform(PaintBehavior paintBehavior) const
595 {
596     if (!m_transform)
597         return TransformationMatrix();
598     
599     if (paintBehavior & PaintBehaviorFlattenCompositingLayers) {
600         TransformationMatrix matrix = *m_transform;
601         makeMatrixRenderable(matrix, false /* flatten 3d */);
602         return matrix;
603     }
604
605     return *m_transform;
606 }
607
608 static bool checkContainingBlockChainForPagination(RenderBoxModelObject* renderer, RenderBox* ancestorColumnsRenderer)
609 {
610     RenderView* view = renderer->view();
611     RenderBoxModelObject* prevBlock = renderer;
612     RenderBlock* containingBlock;
613     for (containingBlock = renderer->containingBlock();
614          containingBlock && containingBlock != view && containingBlock != ancestorColumnsRenderer;
615          containingBlock = containingBlock->containingBlock())
616         prevBlock = containingBlock;
617     
618     // If the columns block wasn't in our containing block chain, then we aren't paginated by it.
619     if (containingBlock != ancestorColumnsRenderer)
620         return false;
621         
622     // If the previous block is absolutely positioned, then we can't be paginated by the columns block.
623     if (prevBlock->isOutOfFlowPositioned())
624         return false;
625         
626     // Otherwise we are paginated by the columns block.
627     return true;
628 }
629
630 void RenderLayer::updatePagination()
631 {
632     m_isPaginated = false;
633     if (isComposited() || !parent())
634         return; // FIXME: We will have to deal with paginated compositing layers someday.
635                 // FIXME: For now the RenderView can't be paginated.  Eventually printing will move to a model where it is though.
636     
637     if (isNormalFlowOnly()) {
638         m_isPaginated = parent()->renderer()->hasColumns();
639         return;
640     }
641
642     // If we're not normal flow, then we need to look for a multi-column object between us and our stacking context.
643     RenderLayer* ancestorStackingContext = stackingContext();
644     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
645         if (curr->renderer()->hasColumns()) {
646             m_isPaginated = checkContainingBlockChainForPagination(renderer(), curr->renderBox());
647             return;
648         }
649         if (curr == ancestorStackingContext)
650             return;
651     }
652 }
653
654 void RenderLayer::setHasVisibleContent()
655
656     if (m_hasVisibleContent && !m_visibleContentStatusDirty) {
657         ASSERT(!parent() || parent()->hasVisibleDescendant());
658         return;
659     }
660
661     m_visibleContentStatusDirty = false; 
662     m_hasVisibleContent = true;
663     computeRepaintRects();
664     if (!isNormalFlowOnly()) {
665         // We don't collect invisible layers in z-order lists if we are not in compositing mode.
666         // As we became visible, we need to dirty our stacking contexts ancestors to be properly
667         // collected. FIXME: When compositing, we could skip this dirtying phase.
668         for (RenderLayer* sc = stackingContext(); sc; sc = sc->stackingContext()) {
669             sc->dirtyZOrderLists();
670             if (sc->hasVisibleContent())
671                 break;
672         }
673     }
674
675     if (parent())
676         parent()->setAncestorChainHasVisibleDescendant();
677 }
678
679 void RenderLayer::dirtyVisibleContentStatus() 
680
681     m_visibleContentStatusDirty = true; 
682     if (parent())
683         parent()->dirtyAncestorChainVisibleDescendantStatus();
684 }
685
686 void RenderLayer::dirtyAncestorChainVisibleDescendantStatus()
687 {
688     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
689         if (layer->m_visibleDescendantStatusDirty)
690             break;
691
692         layer->m_visibleDescendantStatusDirty = true;
693     }
694 }
695
696 void RenderLayer::setAncestorChainHasVisibleDescendant()
697 {
698     for (RenderLayer* layer = this; layer; layer = layer->parent()) {
699         if (!layer->m_visibleDescendantStatusDirty && layer->hasVisibleDescendant())
700             break;
701
702         layer->m_hasVisibleDescendant = true;
703         layer->m_visibleDescendantStatusDirty = false;
704     }
705 }
706
707 void RenderLayer::updateDescendantDependentFlags()
708 {
709     if (m_visibleDescendantStatusDirty || m_hasSelfPaintingLayerDescendantDirty) {
710         m_hasVisibleDescendant = false;
711         m_hasSelfPaintingLayerDescendant = false;
712         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
713             child->updateDescendantDependentFlags();
714
715             bool hasVisibleDescendant = child->m_hasVisibleContent || child->m_hasVisibleDescendant;
716             bool hasSelfPaintingLayerDescendant = child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant();
717
718             m_hasVisibleDescendant |= hasVisibleDescendant;
719             m_hasSelfPaintingLayerDescendant |= hasSelfPaintingLayerDescendant;
720
721             if (m_hasVisibleDescendant && m_hasSelfPaintingLayerDescendant)
722                 break;
723         }
724         m_visibleDescendantStatusDirty = false;
725         m_hasSelfPaintingLayerDescendantDirty = false;
726     }
727
728     if (m_visibleContentStatusDirty) {
729         if (renderer()->style()->visibility() == VISIBLE)
730             m_hasVisibleContent = true;
731         else {
732             // layer may be hidden but still have some visible content, check for this
733             m_hasVisibleContent = false;
734             RenderObject* r = renderer()->firstChild();
735             while (r) {
736                 if (r->style()->visibility() == VISIBLE && !r->hasLayer()) {
737                     m_hasVisibleContent = true;
738                     break;
739                 }
740                 if (r->firstChild() && !r->hasLayer())
741                     r = r->firstChild();
742                 else if (r->nextSibling())
743                     r = r->nextSibling();
744                 else {
745                     do {
746                         r = r->parent();
747                         if (r == renderer())
748                             r = 0;
749                     } while (r && !r->nextSibling());
750                     if (r)
751                         r = r->nextSibling();
752                 }
753             }
754         }    
755         m_visibleContentStatusDirty = false; 
756     }
757 }
758
759 void RenderLayer::dirty3DTransformedDescendantStatus()
760 {
761     RenderLayer* curr = stackingContext();
762     if (curr)
763         curr->m_3DTransformedDescendantStatusDirty = true;
764         
765     // This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
766     // Note that preserves3D() creates stacking context, so we can just run up the stacking contexts.
767     while (curr && curr->preserves3D()) {
768         curr->m_3DTransformedDescendantStatusDirty = true;
769         curr = curr->stackingContext();
770     }
771 }
772
773 // Return true if this layer or any preserve-3d descendants have 3d.
774 bool RenderLayer::update3DTransformedDescendantStatus()
775 {
776     if (m_3DTransformedDescendantStatusDirty) {
777         m_has3DTransformedDescendant = false;
778
779         updateZOrderLists();
780
781         // Transformed or preserve-3d descendants can only be in the z-order lists, not
782         // in the normal flow list, so we only need to check those.
783         if (Vector<RenderLayer*>* positiveZOrderList = posZOrderList()) {
784             for (unsigned i = 0; i < positiveZOrderList->size(); ++i)
785                 m_has3DTransformedDescendant |= positiveZOrderList->at(i)->update3DTransformedDescendantStatus();
786         }
787
788         // Now check our negative z-index children.
789         if (Vector<RenderLayer*>* negativeZOrderList = negZOrderList()) {
790             for (unsigned i = 0; i < negativeZOrderList->size(); ++i)
791                 m_has3DTransformedDescendant |= negativeZOrderList->at(i)->update3DTransformedDescendantStatus();
792         }
793         
794         m_3DTransformedDescendantStatusDirty = false;
795     }
796     
797     // If we live in a 3d hierarchy, then the layer at the root of that hierarchy needs
798     // the m_has3DTransformedDescendant set.
799     if (preserves3D())
800         return has3DTransform() || m_has3DTransformedDescendant;
801
802     return has3DTransform();
803 }
804
805 void RenderLayer::updateLayerPosition()
806 {
807     LayoutPoint localPoint;
808     LayoutSize inlineBoundingBoxOffset; // We don't put this into the RenderLayer x/y for inlines, so we need to subtract it out when done.
809     if (renderer()->isRenderInline()) {
810         RenderInline* inlineFlow = toRenderInline(renderer());
811         IntRect lineBox = inlineFlow->linesBoundingBox();
812         setSize(lineBox.size());
813         inlineBoundingBoxOffset = toSize(lineBox.location());
814         localPoint += inlineBoundingBoxOffset;
815     } else if (RenderBox* box = renderBox()) {
816         // FIXME: Is snapping the size really needed here for the RenderBox case?
817         setSize(pixelSnappedIntSize(box->size(), box->location()));
818         localPoint += box->topLeftLocationOffset();
819     }
820
821     // Clear our cached clip rect information.
822     clearClipRects();
823  
824     if (!renderer()->isOutOfFlowPositioned() && renderer()->parent()) {
825         // We must adjust our position by walking up the render tree looking for the
826         // nearest enclosing object with a layer.
827         RenderObject* curr = renderer()->parent();
828         while (curr && !curr->hasLayer()) {
829             if (curr->isBox() && !curr->isTableRow()) {
830                 // Rows and cells share the same coordinate space (that of the section).
831                 // Omit them when computing our xpos/ypos.
832                 localPoint += toRenderBox(curr)->topLeftLocationOffset();
833             }
834             curr = curr->parent();
835         }
836         if (curr->isBox() && curr->isTableRow()) {
837             // Put ourselves into the row coordinate space.
838             localPoint -= toRenderBox(curr)->topLeftLocationOffset();
839         }
840     }
841     
842     // Subtract our parent's scroll offset.
843     if (renderer()->isOutOfFlowPositioned() && enclosingPositionedAncestor()) {
844         RenderLayer* positionedParent = enclosingPositionedAncestor();
845
846         // For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
847         LayoutSize offset = positionedParent->scrolledContentOffset();
848         localPoint -= offset;
849         
850         if (renderer()->isOutOfFlowPositioned() && positionedParent->renderer()->isInFlowPositioned() && positionedParent->renderer()->isRenderInline()) {
851             LayoutSize offset = toRenderInline(positionedParent->renderer())->offsetForInFlowPositionedInline(toRenderBox(renderer()));
852             localPoint += offset;
853         }
854     } else if (parent()) {
855         if (isComposited()) {
856             // FIXME: Composited layers ignore pagination, so about the best we can do is make sure they're offset into the appropriate column.
857             // They won't split across columns properly.
858             LayoutSize columnOffset;
859             if (!parent()->renderer()->hasColumns() && parent()->renderer()->isRoot() && renderer()->view()->hasColumns())
860                 renderer()->view()->adjustForColumns(columnOffset, localPoint);
861             else
862                 parent()->renderer()->adjustForColumns(columnOffset, localPoint);
863
864             localPoint += columnOffset;
865         }
866
867         IntSize scrollOffset = parent()->scrolledContentOffset();
868         localPoint -= scrollOffset;
869     }
870     
871     if (renderer()->isInFlowPositioned()) {
872         m_offsetForInFlowPosition = renderer()->offsetForInFlowPosition();
873         localPoint.move(m_offsetForInFlowPosition);
874     } else {
875         m_offsetForInFlowPosition = LayoutSize();
876     }
877
878     // FIXME: We'd really like to just get rid of the concept of a layer rectangle and rely on the renderers.
879     localPoint -= inlineBoundingBoxOffset;
880     setLocation(localPoint.x(), localPoint.y());
881 }
882
883 TransformationMatrix RenderLayer::perspectiveTransform() const
884 {
885     if (!renderer()->hasTransform())
886         return TransformationMatrix();
887
888     RenderStyle* style = renderer()->style();
889     if (!style->hasPerspective())
890         return TransformationMatrix();
891
892     // Maybe fetch the perspective from the backing?
893     const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
894     const float boxWidth = borderBox.width();
895     const float boxHeight = borderBox.height();
896
897     float perspectiveOriginX = floatValueForLength(style->perspectiveOriginX(), boxWidth);
898     float perspectiveOriginY = floatValueForLength(style->perspectiveOriginY(), boxHeight);
899
900     // A perspective origin of 0,0 makes the vanishing point in the center of the element.
901     // We want it to be in the top-left, so subtract half the height and width.
902     perspectiveOriginX -= boxWidth / 2.0f;
903     perspectiveOriginY -= boxHeight / 2.0f;
904     
905     TransformationMatrix t;
906     t.translate(perspectiveOriginX, perspectiveOriginY);
907     t.applyPerspective(style->perspective());
908     t.translate(-perspectiveOriginX, -perspectiveOriginY);
909     
910     return t;
911 }
912
913 FloatPoint RenderLayer::perspectiveOrigin() const
914 {
915     if (!renderer()->hasTransform())
916         return FloatPoint();
917
918     const LayoutRect borderBox = toRenderBox(renderer())->borderBoxRect();
919     RenderStyle* style = renderer()->style();
920
921     return FloatPoint(floatValueForLength(style->perspectiveOriginX(), borderBox.width()),
922                       floatValueForLength(style->perspectiveOriginY(), borderBox.height()));
923 }
924
925 RenderLayer* RenderLayer::stackingContext() const
926 {
927     RenderLayer* layer = parent();
928     while (layer && !layer->isRootLayer() && !layer->renderer()->isRoot() && layer->renderer()->style()->hasAutoZIndex())
929         layer = layer->parent();
930     return layer;
931 }
932
933 static inline bool isPositionedContainer(RenderLayer* layer)
934 {
935     RenderBoxModelObject* layerRenderer = layer->renderer();
936     return layer->isRootLayer() || layerRenderer->isPositioned() || layer->hasTransform();
937 }
938
939 static inline bool isFixedPositionedContainer(RenderLayer* layer)
940 {
941     return layer->isRootLayer() || layer->hasTransform();
942 }
943
944 RenderLayer* RenderLayer::enclosingPositionedAncestor() const
945 {
946     RenderLayer* curr = parent();
947     while (curr && !isPositionedContainer(curr))
948         curr = curr->parent();
949
950     return curr;
951 }
952
953 RenderLayer* RenderLayer::enclosingScrollableLayer() const
954 {
955     for (RenderObject* nextRenderer = renderer()->parent(); nextRenderer; nextRenderer = nextRenderer->parent()) {
956         if (nextRenderer->isBox() && toRenderBox(nextRenderer)->canBeScrolledAndHasScrollableArea())
957             return nextRenderer->enclosingLayer();
958     }
959
960     return 0;
961 }
962
963 IntRect RenderLayer::scrollableAreaBoundingBox() const
964 {
965     return renderer()->absoluteBoundingBoxRect();
966 }
967
968 RenderLayer* RenderLayer::enclosingTransformedAncestor() const
969 {
970     RenderLayer* curr = parent();
971     while (curr && !curr->isRootLayer() && !curr->transform())
972         curr = curr->parent();
973
974     return curr;
975 }
976
977 static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
978 {
979     return layer->isNormalFlowOnly() ? layer->parent() : layer->stackingContext();
980 }
981
982 inline bool RenderLayer::shouldRepaintAfterLayout() const
983 {
984 #if USE(ACCELERATED_COMPOSITING)
985     if (m_repaintStatus == NeedsNormalRepaint)
986         return true;
987
988     // Composited layers that were moved during a positioned movement only
989     // layout, don't need to be repainted. They just need to be recomposited.
990     ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
991     return !isComposited();
992 #else
993     return true;
994 #endif
995 }
996
997 #if USE(ACCELERATED_COMPOSITING)
998 RenderLayer* RenderLayer::enclosingCompositingLayer(bool includeSelf) const
999 {
1000     if (includeSelf && isComposited())
1001         return const_cast<RenderLayer*>(this);
1002
1003     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1004         if (curr->isComposited())
1005             return const_cast<RenderLayer*>(curr);
1006     }
1007          
1008     return 0;
1009 }
1010
1011 RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(bool includeSelf) const
1012 {
1013     if (includeSelf && isComposited() && !backing()->paintsIntoCompositedAncestor())
1014         return const_cast<RenderLayer*>(this);
1015
1016     for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
1017         if (curr->isComposited() && !curr->backing()->paintsIntoCompositedAncestor())
1018             return const_cast<RenderLayer*>(curr);
1019     }
1020          
1021     return 0;
1022 }
1023 #endif
1024
1025 #if ENABLE(CSS_FILTERS)
1026 RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
1027 {
1028     const RenderLayer* curr = includeSelf ? this : parent();
1029     for (; curr; curr = curr->parent()) {
1030         if (curr->requiresFullLayerImageForFilters())
1031             return const_cast<RenderLayer*>(curr);
1032     }
1033     
1034     return 0;
1035 }
1036
1037 RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
1038 {
1039     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1040         if ((curr != this && curr->requiresFullLayerImageForFilters()) || curr->isComposited() || curr->isRootLayer())
1041             return const_cast<RenderLayer*>(curr);
1042     }
1043     return 0;
1044 }
1045
1046 void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect, bool immediate)
1047 {
1048     if (rect.isEmpty())
1049         return;
1050     
1051     LayoutRect rectForRepaint = rect;
1052     
1053 #if ENABLE(CSS_FILTERS)
1054     if (renderer()->style()->hasFilterOutsets()) {
1055         int topOutset;
1056         int rightOutset;
1057         int bottomOutset;
1058         int leftOutset;
1059         renderer()->style()->getFilterOutsets(topOutset, rightOutset, bottomOutset, leftOutset);
1060         rectForRepaint.move(-leftOutset, -topOutset);
1061         rectForRepaint.expand(leftOutset + rightOutset, topOutset + bottomOutset);
1062     }
1063 #endif
1064
1065     RenderLayerFilterInfo* filterInfo = this->filterInfo();
1066     ASSERT(filterInfo);
1067     filterInfo->expandDirtySourceRect(rectForRepaint);
1068     
1069 #if ENABLE(CSS_SHADERS)
1070     ASSERT(filterInfo->renderer());
1071     if (filterInfo->renderer()->hasCustomShaderFilter()) {
1072         // If we have at least one custom shader, we need to update the whole bounding box of the layer, because the
1073         // shader can address any ouput pixel.
1074         // Note: This is only for output rect, so there's no need to expand the dirty source rect.
1075         rectForRepaint.unite(calculateLayerBounds(this, this));
1076     }
1077 #endif
1078     
1079     RenderLayer* parentLayer = enclosingFilterRepaintLayer();
1080     ASSERT(parentLayer);
1081     FloatQuad repaintQuad(rectForRepaint);
1082     LayoutRect parentLayerRect = renderer()->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
1083     
1084 #if USE(ACCELERATED_COMPOSITING)
1085     if (parentLayer->isComposited()) {
1086         if (!parentLayer->backing()->paintsIntoWindow()) {
1087             parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
1088             return;
1089         }
1090         // If the painting goes to window, redirect the painting to the parent RenderView.
1091         parentLayer = renderer()->view()->layer();
1092         parentLayerRect = renderer()->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
1093     }
1094 #endif
1095
1096     if (parentLayer->paintsWithFilters()) {
1097         parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect, immediate);
1098         return;        
1099     }
1100     
1101     if (parentLayer->isRootLayer()) {
1102         RenderView* view = toRenderView(parentLayer->renderer());
1103         view->repaintViewRectangle(parentLayerRect, immediate);
1104         return;
1105     }
1106     
1107     ASSERT_NOT_REACHED();
1108 }
1109
1110 bool RenderLayer::hasAncestorWithFilterOutsets() const
1111 {
1112     for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
1113         RenderBoxModelObject* renderer = curr->renderer();
1114         if (renderer->style()->hasFilterOutsets())
1115             return true;
1116     }
1117     return false;
1118 }
1119 #endif
1120     
1121 RenderLayer* RenderLayer::clippingRootForPainting() const
1122 {
1123 #if USE(ACCELERATED_COMPOSITING)
1124     if (isComposited())
1125         return const_cast<RenderLayer*>(this);
1126 #endif
1127
1128     const RenderLayer* current = this;
1129     while (current) {
1130         if (current->isRootLayer())
1131             return const_cast<RenderLayer*>(current);
1132
1133         current = compositingContainer(current);
1134         ASSERT(current);
1135         if (current->transform()
1136 #if USE(ACCELERATED_COMPOSITING)
1137             || (current->isComposited() && !current->backing()->paintsIntoCompositedAncestor())
1138 #endif
1139         )
1140             return const_cast<RenderLayer*>(current);
1141     }
1142
1143     ASSERT_NOT_REACHED();
1144     return 0;
1145 }
1146
1147 LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
1148 {
1149     // We don't use convertToLayerCoords because it doesn't know about transforms
1150     return roundedLayoutPoint(renderer()->absoluteToLocal(absolutePoint, false, true));
1151 }
1152
1153 bool RenderLayer::cannotBlitToWindow() const
1154 {
1155     if (isTransparent() || hasReflection() || hasTransform())
1156         return true;
1157     if (!parent())
1158         return false;
1159     return parent()->cannotBlitToWindow();
1160 }
1161
1162 bool RenderLayer::isTransparent() const
1163 {
1164 #if ENABLE(SVG)
1165     if (renderer()->node() && renderer()->node()->namespaceURI() == SVGNames::svgNamespaceURI)
1166         return false;
1167 #endif
1168     return renderer()->isTransparent() || renderer()->hasMask();
1169 }
1170
1171 RenderLayer* RenderLayer::transparentPaintingAncestor()
1172 {
1173     if (isComposited())
1174         return 0;
1175
1176     for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
1177         if (curr->isComposited())
1178             return 0;
1179         if (curr->isTransparent())
1180             return curr;
1181     }
1182     return 0;
1183 }
1184
1185 static LayoutRect transparencyClipBox(const RenderLayer*, const RenderLayer* rootLayer, PaintBehavior);
1186
1187 static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, const RenderLayer* layer, const RenderLayer* rootLayer, PaintBehavior paintBehavior)
1188 {
1189     // If we have a mask, then the clip is limited to the border box area (and there is
1190     // no need to examine child layers).
1191     if (!layer->renderer()->hasMask()) {
1192         // Note: we don't have to walk z-order lists since transparent elements always establish
1193         // a stacking context.  This means we can just walk the layer tree directly.
1194         for (RenderLayer* curr = layer->firstChild(); curr; curr = curr->nextSibling()) {
1195             if (!layer->reflection() || layer->reflectionLayer() != curr)
1196                 clipRect.unite(transparencyClipBox(curr, rootLayer, paintBehavior));
1197         }
1198     }
1199
1200     // If we have a reflection, then we need to account for that when we push the clip.  Reflect our entire
1201     // current transparencyClipBox to catch all child layers.
1202     // FIXME: Accelerated compositing will eventually want to do something smart here to avoid incorporating this
1203     // size into the parent layer.
1204     if (layer->renderer()->hasReflection()) {
1205         LayoutPoint delta;
1206         layer->convertToLayerCoords(rootLayer, delta);
1207         clipRect.move(-delta.x(), -delta.y());
1208         clipRect.unite(layer->renderBox()->reflectedRect(clipRect));
1209         clipRect.moveBy(delta);
1210     }
1211 }
1212
1213 static LayoutRect transparencyClipBox(const RenderLayer* layer, const RenderLayer* rootLayer, PaintBehavior paintBehavior)
1214 {
1215     // FIXME: Although this function completely ignores CSS-imposed clipping, we did already intersect with the
1216     // paintDirtyRect, and that should cut down on the amount we have to paint.  Still it
1217     // would be better to respect clips.
1218     
1219     if (rootLayer != layer && layer->paintsWithTransform(paintBehavior)) {
1220         // The best we can do here is to use enclosed bounding boxes to establish a "fuzzy" enough clip to encompass
1221         // the transformed layer and all of its children.
1222         LayoutPoint delta;
1223         layer->convertToLayerCoords(rootLayer, delta);
1224
1225         TransformationMatrix transform;
1226         transform.translate(delta.x(), delta.y());
1227         transform = transform * *layer->transform();
1228
1229         LayoutRect clipRect = layer->boundingBox(layer);
1230         expandClipRectForDescendantsAndReflection(clipRect, layer, layer, paintBehavior);
1231         return transform.mapRect(clipRect);
1232     }
1233     
1234     LayoutRect clipRect = layer->boundingBox(rootLayer);
1235     expandClipRectForDescendantsAndReflection(clipRect, layer, rootLayer, paintBehavior);
1236     return clipRect;
1237 }
1238
1239 LayoutRect RenderLayer::paintingExtent(const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
1240 {
1241     return intersection(transparencyClipBox(this, rootLayer, paintBehavior), paintDirtyRect);
1242 }
1243
1244 void RenderLayer::beginTransparencyLayers(GraphicsContext* context, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
1245 {
1246     if (context->paintingDisabled() || (paintsWithTransparency(paintBehavior) && m_usedTransparency))
1247         return;
1248     
1249     RenderLayer* ancestor = transparentPaintingAncestor();
1250     if (ancestor)
1251         ancestor->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
1252     
1253     if (paintsWithTransparency(paintBehavior)) {
1254         m_usedTransparency = true;
1255         context->save();
1256         LayoutRect clipRect = paintingExtent(rootLayer, paintDirtyRect, paintBehavior);
1257         context->clip(clipRect);
1258         context->beginTransparencyLayer(renderer()->opacity());
1259 #ifdef REVEAL_TRANSPARENCY_LAYERS
1260         context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f), ColorSpaceDeviceRGB);
1261         context->fillRect(clipRect);
1262 #endif
1263     }
1264 }
1265
1266 void* RenderLayer::operator new(size_t sz, RenderArena* renderArena)
1267 {
1268     return renderArena->allocate(sz);
1269 }
1270
1271 void RenderLayer::operator delete(void* ptr, size_t sz)
1272 {
1273     // Stash size where destroy can find it.
1274     *(size_t *)ptr = sz;
1275 }
1276
1277 void RenderLayer::destroy(RenderArena* renderArena)
1278 {
1279     delete this;
1280
1281     // Recover the size left there for us by operator delete and free the memory.
1282     renderArena->free(*(size_t *)this, this);
1283 }
1284
1285 void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
1286 {
1287     RenderLayer* prevSibling = beforeChild ? beforeChild->previousSibling() : lastChild();
1288     if (prevSibling) {
1289         child->setPreviousSibling(prevSibling);
1290         prevSibling->setNextSibling(child);
1291         ASSERT(prevSibling != child);
1292     } else
1293         setFirstChild(child);
1294
1295     if (beforeChild) {
1296         beforeChild->setPreviousSibling(child);
1297         child->setNextSibling(beforeChild);
1298         ASSERT(beforeChild != child);
1299     } else
1300         setLastChild(child);
1301
1302     child->setParent(this);
1303
1304     if (child->isNormalFlowOnly())
1305         dirtyNormalFlowList();
1306
1307     if (!child->isNormalFlowOnly() || child->firstChild()) {
1308         // Dirty the z-order list in which we are contained.  The stackingContext() can be null in the
1309         // case where we're building up generated content layers.  This is ok, since the lists will start
1310         // off dirty in that case anyway.
1311         child->dirtyStackingContextZOrderLists();
1312     }
1313
1314     child->updateDescendantDependentFlags();
1315     if (child->m_hasVisibleContent || child->m_hasVisibleDescendant)
1316         setAncestorChainHasVisibleDescendant();
1317
1318     if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
1319         setAncestorChainHasSelfPaintingLayerDescendant();
1320
1321 #if USE(ACCELERATED_COMPOSITING)
1322     compositor()->layerWasAdded(this, child);
1323 #endif
1324 }
1325
1326 RenderLayer* RenderLayer::removeChild(RenderLayer* oldChild)
1327 {
1328 #if USE(ACCELERATED_COMPOSITING)
1329     if (!renderer()->documentBeingDestroyed())
1330         compositor()->layerWillBeRemoved(this, oldChild);
1331 #endif
1332
1333     // remove the child
1334     if (oldChild->previousSibling())
1335         oldChild->previousSibling()->setNextSibling(oldChild->nextSibling());
1336     if (oldChild->nextSibling())
1337         oldChild->nextSibling()->setPreviousSibling(oldChild->previousSibling());
1338
1339     if (m_first == oldChild)
1340         m_first = oldChild->nextSibling();
1341     if (m_last == oldChild)
1342         m_last = oldChild->previousSibling();
1343
1344     if (oldChild->isNormalFlowOnly())
1345         dirtyNormalFlowList();
1346     if (!oldChild->isNormalFlowOnly() || oldChild->firstChild()) { 
1347         // Dirty the z-order list in which we are contained.  When called via the
1348         // reattachment process in removeOnlyThisLayer, the layer may already be disconnected
1349         // from the main layer tree, so we need to null-check the |stackingContext| value.
1350         oldChild->dirtyStackingContextZOrderLists();
1351     }
1352
1353     oldChild->setPreviousSibling(0);
1354     oldChild->setNextSibling(0);
1355     oldChild->setParent(0);
1356     
1357     oldChild->updateDescendantDependentFlags();
1358     if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
1359         dirtyAncestorChainVisibleDescendantStatus();
1360
1361     if (oldChild->isSelfPaintingLayer() || oldChild->hasSelfPaintingLayerDescendant())
1362         dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
1363
1364     return oldChild;
1365 }
1366
1367 void RenderLayer::removeOnlyThisLayer()
1368 {
1369     if (!m_parent)
1370         return;
1371
1372     // Mark that we are about to lose our layer. This makes render tree
1373     // walks ignore this layer while we're removing it.
1374     m_renderer->setHasLayer(false);
1375
1376 #if USE(ACCELERATED_COMPOSITING)
1377     compositor()->layerWillBeRemoved(m_parent, this);
1378 #endif
1379
1380     // Dirty the clip rects.
1381     clearClipRectsIncludingDescendants();
1382
1383     RenderLayer* nextSib = nextSibling();
1384     bool hasLayerOffset;
1385     const LayoutPoint offsetFromRootBeforeMove = computeOffsetFromRoot(hasLayerOffset);
1386
1387     // Remove the child reflection layer before moving other child layers.
1388     // The reflection layer should not be moved to the parent.
1389     if (reflection())
1390         removeChild(reflectionLayer());
1391
1392     // Now walk our kids and reattach them to our parent.
1393     RenderLayer* current = m_first;
1394     while (current) {
1395         RenderLayer* next = current->nextSibling();
1396         removeChild(current);
1397         m_parent->addChild(current, nextSib);
1398         current->setRepaintStatus(NeedsFullRepaint);
1399         LayoutPoint offsetFromRoot = offsetFromRootBeforeMove;
1400         // updateLayerPositions depends on hasLayer() already being false for proper layout.
1401         ASSERT(!renderer()->hasLayer());
1402         current->updateLayerPositions(hasLayerOffset ? &offsetFromRoot : 0);
1403         current = next;
1404     }
1405
1406     // Remove us from the parent.
1407     m_parent->removeChild(this);
1408     m_renderer->destroyLayer();
1409 }
1410
1411 void RenderLayer::insertOnlyThisLayer()
1412 {
1413     if (!m_parent && renderer()->parent()) {
1414         // We need to connect ourselves when our renderer() has a parent.
1415         // Find our enclosingLayer and add ourselves.
1416         RenderLayer* parentLayer = renderer()->parent()->enclosingLayer();
1417         ASSERT(parentLayer);
1418         RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer()->parent()->findNextLayer(parentLayer, renderer()) : 0;
1419         parentLayer->addChild(this, beforeChild);
1420     }
1421
1422     // Remove all descendant layers from the hierarchy and add them to the new position.
1423     for (RenderObject* curr = renderer()->firstChild(); curr; curr = curr->nextSibling())
1424         curr->moveLayers(m_parent, this);
1425
1426     // Clear out all the clip rects.
1427     clearClipRectsIncludingDescendants();
1428 }
1429
1430 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation) const
1431 {
1432     LayoutPoint location = roundedLocation;
1433     convertToLayerCoords(ancestorLayer, location);
1434     roundedLocation = roundedIntPoint(location);
1435 }
1436
1437 void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntRect& roundedRect) const
1438 {
1439     LayoutRect rect = roundedRect;
1440     convertToLayerCoords(ancestorLayer, rect);
1441     roundedRect = pixelSnappedIntRect(rect);
1442 }
1443
1444 void RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutPoint& location) const
1445 {
1446     if (ancestorLayer == this)
1447         return;
1448
1449     EPosition position = renderer()->style()->position();
1450
1451     // FIXME: Positioning of out-of-flow(fixed, absolute) elements collected in a RenderFlowThread
1452     // may need to be revisited in a future patch.
1453     // If the fixed renderer is inside a RenderFlowThread, we should not compute location using localToAbsolute,
1454     // since localToAbsolute maps the coordinates from named flow to regions coordinates and regions can be
1455     // positioned in a completely different place in the viewport (RenderView).
1456     if (position == FixedPosition && !renderer()->inRenderFlowThread() && (!ancestorLayer || ancestorLayer == renderer()->view()->layer())) {
1457         // If the fixed layer's container is the root, just add in the offset of the view. We can obtain this by calling
1458         // localToAbsolute() on the RenderView.
1459         FloatPoint absPos = renderer()->localToAbsolute(FloatPoint(), true);
1460         location += LayoutSize(absPos.x(), absPos.y());
1461         return;
1462     }
1463
1464     // For the fixed positioned elements inside a render flow thread, we should also skip the code path below
1465     // Otherwise, for the case of ancestorLayer == rootLayer and fixed positioned element child of a transformed
1466     // element in render flow thread, we will hit the fixed positioned container before hitting the ancestor layer.
1467     if (position == FixedPosition && !renderer()->inRenderFlowThread()) {
1468         // For a fixed layers, we need to walk up to the root to see if there's a fixed position container
1469         // (e.g. a transformed layer). It's an error to call convertToLayerCoords() across a layer with a transform,
1470         // so we should always find the ancestor at or before we find the fixed position container.
1471         RenderLayer* fixedPositionContainerLayer = 0;
1472         bool foundAncestor = false;
1473         for (RenderLayer* currLayer = parent(); currLayer; currLayer = currLayer->parent()) {
1474             if (currLayer == ancestorLayer)
1475                 foundAncestor = true;
1476
1477             if (isFixedPositionedContainer(currLayer)) {
1478                 fixedPositionContainerLayer = currLayer;
1479                 ASSERT_UNUSED(foundAncestor, foundAncestor);
1480                 break;
1481             }
1482         }
1483         
1484         ASSERT(fixedPositionContainerLayer); // We should have hit the RenderView's layer at least.
1485
1486         if (fixedPositionContainerLayer != ancestorLayer) {
1487             LayoutPoint fixedContainerCoords;
1488             convertToLayerCoords(fixedPositionContainerLayer, fixedContainerCoords);
1489
1490             LayoutPoint ancestorCoords;
1491             ancestorLayer->convertToLayerCoords(fixedPositionContainerLayer, ancestorCoords);
1492
1493             location += (fixedContainerCoords - ancestorCoords);
1494             return;
1495         }
1496     }
1497     
1498     RenderLayer* parentLayer;
1499     if (position == AbsolutePosition || position == FixedPosition) {
1500         // Do what enclosingPositionedAncestor() does, but check for ancestorLayer along the way.
1501         parentLayer = parent();
1502         bool foundAncestorFirst = false;
1503         while (parentLayer) {
1504             // RenderFlowThread is a positioned container, child of RenderView, positioned at (0,0).
1505             // This implies that, for out-of-flow positioned elements inside a RenderFlowThread,
1506             // we are bailing out before reaching root layer.
1507             if (isPositionedContainer(parentLayer))
1508                 break;
1509
1510             if (parentLayer == ancestorLayer) {
1511                 foundAncestorFirst = true;
1512                 break;
1513             }
1514
1515             parentLayer = parentLayer->parent();
1516         }
1517
1518         // We should not reach RenderView layer past the RenderFlowThread layer for any
1519         // children of the RenderFlowThread.
1520         if (renderer()->inRenderFlowThread() && !renderer()->isRenderFlowThread())
1521             ASSERT(parentLayer != renderer()->view()->layer());
1522
1523         if (foundAncestorFirst) {
1524             // Found ancestorLayer before the abs. positioned container, so compute offset of both relative
1525             // to enclosingPositionedAncestor and subtract.
1526             RenderLayer* positionedAncestor = parentLayer->enclosingPositionedAncestor();
1527
1528             LayoutPoint thisCoords;
1529             convertToLayerCoords(positionedAncestor, thisCoords);
1530             
1531             LayoutPoint ancestorCoords;
1532             ancestorLayer->convertToLayerCoords(positionedAncestor, ancestorCoords);
1533
1534             location += (thisCoords - ancestorCoords);
1535             return;
1536         }
1537     } else
1538         parentLayer = parent();
1539     
1540     if (!parentLayer)
1541         return;
1542
1543     parentLayer->convertToLayerCoords(ancestorLayer, location);
1544
1545     location += toSize(m_topLeft);
1546 }
1547
1548 void RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutRect& rect) const
1549 {
1550     LayoutPoint delta;
1551     convertToLayerCoords(ancestorLayer, delta);
1552     rect.move(-delta.x(), -delta.y());
1553 }
1554
1555 bool RenderLayer::usesCompositedScrolling() const
1556 {
1557 #if USE(ACCELERATED_COMPOSITING)
1558     if (!scrollsOverflow() || !allowsScrolling())
1559         return false;
1560
1561 #if ENABLE(OVERFLOW_SCROLLING)
1562     return renderer()->style()->useTouchOverflowScrolling();
1563 #else
1564     return false;
1565 #endif
1566 #else
1567     return false;
1568 #endif
1569 }
1570
1571 static inline int adjustedScrollDelta(int beginningDelta) {
1572     // This implemention matches Firefox's.
1573     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
1574     const int speedReducer = 12;
1575
1576     int adjustedDelta = beginningDelta / speedReducer;
1577     if (adjustedDelta > 1)
1578         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
1579     else if (adjustedDelta < -1)
1580         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
1581
1582     return adjustedDelta;
1583 }
1584
1585 static inline IntSize adjustedScrollDelta(const IntSize& delta)
1586 {
1587     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
1588 }
1589
1590 void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
1591 {
1592     Frame* frame = renderer()->frame();
1593     if (!frame)
1594         return;
1595     
1596     IntPoint currentMousePosition = frame->eventHandler()->currentMousePosition();
1597     
1598     // 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
1599     static IntPoint previousMousePosition;
1600     if (currentMousePosition.x() < 0 || currentMousePosition.y() < 0)
1601         currentMousePosition = previousMousePosition;
1602     else
1603         previousMousePosition = currentMousePosition;
1604
1605     IntSize delta = currentMousePosition - sourcePoint;
1606
1607     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
1608         delta.setWidth(0);
1609     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
1610         delta.setHeight(0);
1611
1612     scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
1613 }
1614
1615 void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
1616 {
1617     if (delta.isZero())
1618         return;
1619
1620     bool restrictedByLineClamp = false;
1621     if (renderer()->parent())
1622         restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
1623
1624     if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
1625         IntSize newScrollOffset = scrollOffset() + delta;
1626         scrollToOffset(newScrollOffset, clamp);
1627
1628         // If this layer can't do the scroll we ask the next layer up that can scroll to try
1629         IntSize remainingScrollOffset = newScrollOffset - scrollOffset();
1630         if (!remainingScrollOffset.isZero() && renderer()->parent()) {
1631             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
1632                 scrollableLayer->scrollByRecursively(remainingScrollOffset);
1633
1634             Frame* frame = renderer()->frame();
1635             if (frame)
1636                 frame->eventHandler()->updateAutoscrollRenderer();
1637         }
1638     } else if (renderer()->view()->frameView()) {
1639         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
1640         // have an overflow clip. Which means that it is a document node that can be scrolled.
1641         renderer()->view()->frameView()->scrollBy(delta);
1642         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement? 
1643         // https://bugs.webkit.org/show_bug.cgi?id=28237
1644     }
1645 }
1646
1647 IntSize RenderLayer::clampScrollOffset(const IntSize& scrollOffset) const
1648 {
1649     RenderBox* box = renderBox();
1650     ASSERT(box);
1651
1652     int maxX = scrollWidth() - box->pixelSnappedClientWidth();
1653     int maxY = scrollHeight() - box->pixelSnappedClientHeight();
1654
1655     int x = min(max(scrollOffset.width(), 0), maxX);
1656     int y = min(max(scrollOffset.height(), 0), maxY);
1657     return IntSize(x, y);
1658 }
1659
1660 void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
1661 {
1662     IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
1663     if (newScrollOffset != this->scrollOffset())
1664         scrollToOffsetWithoutAnimation(toPoint(newScrollOffset));
1665 }
1666
1667 void RenderLayer::scrollTo(int x, int y)
1668 {
1669     RenderBox* box = renderBox();
1670     if (!box)
1671         return;
1672
1673     if (box->style()->overflowX() != OMARQUEE) {
1674         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
1675         if (m_scrollDimensionsDirty)
1676             computeScrollDimensions();
1677     }
1678     
1679     // FIXME: Eventually, we will want to perform a blit.  For now never
1680     // blit, since the check for blitting is going to be very
1681     // complicated (since it will involve testing whether our layer
1682     // is either occluded by another layer or clipped by an enclosing
1683     // layer or contains fixed backgrounds, etc.).
1684     IntSize newScrollOffset = IntSize(x - scrollOrigin().x(), y - scrollOrigin().y());
1685     if (m_scrollOffset == newScrollOffset)
1686         return;
1687     m_scrollOffset = newScrollOffset;
1688
1689     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
1690     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
1691     updateLayerPositionsAfterScroll();
1692
1693     RenderView* view = renderer()->view();
1694     
1695     // We should have a RenderView if we're trying to scroll.
1696     ASSERT(view);
1697     if (view) {
1698 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
1699         // Update dashboard regions, scrolling may change the clip of a
1700         // particular region.
1701         view->frameView()->updateDashboardRegions();
1702 #endif
1703
1704         view->updateWidgetPositions();
1705     }
1706
1707     updateCompositingLayersAfterScroll();
1708
1709     RenderBoxModelObject* repaintContainer = renderer()->containerForRepaint();
1710     Frame* frame = renderer()->frame();
1711     if (frame) {
1712         // The caret rect needs to be invalidated after scrolling
1713         frame->selection()->setCaretRectNeedsUpdate();
1714
1715         FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_repaintRect);
1716         if (repaintContainer)
1717             quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
1718         frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
1719     }
1720
1721     // Just schedule a full repaint of our object.
1722     if (view && !usesCompositedScrolling())
1723         renderer()->repaintUsingContainer(repaintContainer, m_repaintRect);
1724
1725     // Schedule the scroll DOM event.
1726     if (renderer()->node())
1727         renderer()->node()->document()->eventQueue()->enqueueOrDispatchScrollEvent(renderer()->node(), DocumentEventQueue::ScrollEventElementTarget);
1728 }
1729
1730 void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
1731 {
1732     RenderLayer* parentLayer = 0;
1733     LayoutRect newRect = rect;
1734
1735     // We may end up propagating a scroll event. It is important that we suspend events until 
1736     // the end of the function since they could delete the layer or the layer's renderer().
1737     FrameView* frameView = renderer()->document()->view();
1738     if (frameView)
1739         frameView->pauseScheduledEvents();
1740
1741     bool restrictedByLineClamp = false;
1742     if (renderer()->parent()) {
1743         parentLayer = renderer()->parent()->enclosingLayer();
1744         restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
1745     }
1746
1747     if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
1748         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
1749         // This will prevent us from revealing text hidden by the slider in Safari RSS.
1750         RenderBox* box = renderBox();
1751         ASSERT(box);
1752         FloatPoint absPos = box->localToAbsolute();
1753         absPos.move(box->borderLeft(), box->borderTop());
1754
1755         LayoutRect layerBounds = LayoutRect(absPos.x() + scrollXOffset(), absPos.y() + scrollYOffset(), box->clientWidth(), box->clientHeight());
1756         LayoutRect exposeRect = LayoutRect(rect.x() + scrollXOffset(), rect.y() + scrollYOffset(), rect.width(), rect.height());
1757         LayoutRect r = getRectToExpose(layerBounds, exposeRect, alignX, alignY);
1758         
1759         int roundedAdjustedX = roundToInt(r.x() - absPos.x());
1760         int roundedAdjustedY = roundToInt(r.y() - absPos.y());
1761         IntSize clampedScrollOffset = clampScrollOffset(IntSize(roundedAdjustedX, roundedAdjustedY));
1762         if (clampedScrollOffset != scrollOffset()) {
1763             IntSize oldScrollOffset = scrollOffset();
1764             scrollToOffset(clampedScrollOffset);
1765             IntSize scrollOffsetDifference = scrollOffset() - oldScrollOffset;
1766             newRect.move(-scrollOffsetDifference);
1767         }
1768     } else if (!parentLayer && renderer()->isBox() && renderBox()->canBeProgramaticallyScrolled()) {
1769         if (frameView) {
1770             Element* ownerElement = 0;
1771             if (renderer()->document())
1772                 ownerElement = renderer()->document()->ownerElement();
1773
1774             if (ownerElement && ownerElement->renderer()) {
1775                 HTMLFrameElement* frameElement = 0;
1776
1777                 if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
1778                     frameElement = static_cast<HTMLFrameElement*>(ownerElement);
1779
1780                 if (frameElement && frameElement->scrollingMode() != ScrollbarAlwaysOff) {
1781                     LayoutRect viewRect = frameView->visibleContentRect();
1782                     LayoutRect exposeRect = getRectToExpose(viewRect, rect, alignX, alignY);
1783
1784                     int xOffset = roundToInt(exposeRect.x());
1785                     int yOffset = roundToInt(exposeRect.y());
1786                     // Adjust offsets if they're outside of the allowable range.
1787                     xOffset = max(0, min(frameView->contentsWidth(), xOffset));
1788                     yOffset = max(0, min(frameView->contentsHeight(), yOffset));
1789
1790                     frameView->setScrollPosition(IntPoint(xOffset, yOffset));
1791                     if (frameView->safeToPropagateScrollToParent()) {
1792                         parentLayer = ownerElement->renderer()->enclosingLayer();
1793                         newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
1794                         newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
1795                     } else
1796                         parentLayer = 0;
1797                 }
1798             } else {
1799                 LayoutRect viewRect = frameView->visibleContentRect();
1800                 LayoutRect r = getRectToExpose(viewRect, rect, alignX, alignY);
1801                 
1802                 frameView->setScrollPosition(roundedIntPoint(r.location()));
1803
1804                 // This is the outermost view of a web page, so after scrolling this view we
1805                 // scroll its container by calling Page::scrollRectIntoView.
1806                 // This only has an effect on the Mac platform in applications
1807                 // that put web views into scrolling containers, such as Mac OS X Mail.
1808                 // The canAutoscroll function in EventHandler also knows about this.
1809                 if (Frame* frame = frameView->frame()) {
1810                     if (Page* page = frame->page())
1811                         page->chrome()->scrollRectIntoView(pixelSnappedIntRect(rect));
1812                 }
1813             }
1814         }
1815     }
1816     
1817     if (parentLayer)
1818         parentLayer->scrollRectToVisible(newRect, alignX, alignY);
1819
1820     if (frameView)
1821         frameView->resumeScheduledEvents();
1822 }
1823
1824 void RenderLayer::updateCompositingLayersAfterScroll()
1825 {
1826 #if USE(ACCELERATED_COMPOSITING)
1827     if (compositor()->inCompositingMode()) {
1828         // Our stacking context is guaranteed to contain all of our descendants that may need
1829         // repositioning, so update compositing layers from there.
1830         if (RenderLayer* compositingAncestor = stackingContext()->enclosingCompositingLayer()) {
1831             if (compositor()->compositingConsultsOverlap())
1832                 compositor()->updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
1833             else {
1834                 bool isUpdateRoot = true;
1835                 compositingAncestor->backing()->updateAfterLayout(RenderLayerBacking::AllDescendants, isUpdateRoot);
1836             }
1837         }
1838     }
1839 #endif
1840 }
1841
1842 LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
1843 {
1844     // Determine the appropriate X behavior.
1845     ScrollBehavior scrollX;
1846     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
1847     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
1848     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
1849         // If the rectangle is fully visible, use the specified visible behavior.
1850         // If the rectangle is partially visible, but over a certain threshold,
1851         // then treat it as fully visible to avoid unnecessary horizontal scrolling
1852         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
1853     else if (intersectWidth == visibleRect.width()) {
1854         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
1855         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
1856         if (scrollX == alignCenter)
1857             scrollX = noScroll;
1858     } else if (intersectWidth > 0)
1859         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
1860         scrollX = ScrollAlignment::getPartialBehavior(alignX);
1861     else
1862         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
1863     // If we're trying to align to the closest edge, and the exposeRect is further right
1864     // than the visibleRect, and not bigger than the visible area, then align with the right.
1865     if (scrollX == alignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
1866         scrollX = alignRight;
1867
1868     // Given the X behavior, compute the X coordinate.
1869     LayoutUnit x;
1870     if (scrollX == noScroll) 
1871         x = visibleRect.x();
1872     else if (scrollX == alignRight)
1873         x = exposeRect.maxX() - visibleRect.width();
1874     else if (scrollX == alignCenter)
1875         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
1876     else
1877         x = exposeRect.x();
1878
1879     // Determine the appropriate Y behavior.
1880     ScrollBehavior scrollY;
1881     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
1882     LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
1883     if (intersectHeight == exposeRect.height())
1884         // If the rectangle is fully visible, use the specified visible behavior.
1885         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
1886     else if (intersectHeight == visibleRect.height()) {
1887         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
1888         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
1889         if (scrollY == alignCenter)
1890             scrollY = noScroll;
1891     } else if (intersectHeight > 0)
1892         // If the rectangle is partially visible, use the specified partial behavior
1893         scrollY = ScrollAlignment::getPartialBehavior(alignY);
1894     else
1895         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
1896     // If we're trying to align to the closest edge, and the exposeRect is further down
1897     // than the visibleRect, and not bigger than the visible area, then align with the bottom.
1898     if (scrollY == alignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
1899         scrollY = alignBottom;
1900
1901     // Given the Y behavior, compute the Y coordinate.
1902     LayoutUnit y;
1903     if (scrollY == noScroll) 
1904         y = visibleRect.y();
1905     else if (scrollY == alignBottom)
1906         y = exposeRect.maxY() - visibleRect.height();
1907     else if (scrollY == alignCenter)
1908         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
1909     else
1910         y = exposeRect.y();
1911
1912     return LayoutRect(LayoutPoint(x, y), visibleRect.size());
1913 }
1914
1915 void RenderLayer::autoscroll()
1916 {
1917     Frame* frame = renderer()->frame();
1918     if (!frame)
1919         return;
1920
1921     FrameView* frameView = frame->view();
1922     if (!frameView)
1923         return;
1924
1925 #if ENABLE(DRAG_SUPPORT)
1926     frame->eventHandler()->updateSelectionForMouseDrag();
1927 #endif
1928
1929     IntPoint currentDocumentPosition = frameView->windowToContents(frame->eventHandler()->currentMousePosition());
1930     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
1931 }
1932
1933 void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
1934 {
1935     // FIXME: This should be possible on generated content but is not right now.
1936     if (!inResizeMode() || !renderer()->hasOverflowClip() || !renderer()->node())
1937         return;
1938
1939     ASSERT(renderer()->node()->isElementNode());
1940     Element* element = static_cast<Element*>(renderer()->node());
1941     RenderBox* renderer = toRenderBox(element->renderer());
1942
1943     EResize resize = renderer->style()->resize();
1944     if (resize == RESIZE_NONE)
1945         return;
1946
1947     Document* document = element->document();
1948     if (!document->frame()->eventHandler()->mousePressed())
1949         return;
1950
1951     float zoomFactor = renderer->style()->effectiveZoom();
1952
1953     LayoutSize newOffset = offsetFromResizeCorner(document->view()->windowToContents(evt.position()));
1954     newOffset.setWidth(newOffset.width() / zoomFactor);
1955     newOffset.setHeight(newOffset.height() / zoomFactor);
1956     
1957     LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
1958     LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
1959     element->setMinimumSizeForResizing(minimumSize);
1960     
1961     LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
1962     if (renderer->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
1963         newOffset.setWidth(-newOffset.width());
1964         adjustedOldOffset.setWidth(-adjustedOldOffset.width());
1965     }
1966     
1967     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
1968
1969     ASSERT(element->isStyledElement());
1970     StyledElement* styledElement = static_cast<StyledElement*>(element);
1971     bool isBoxSizingBorder = renderer->style()->boxSizing() == BORDER_BOX;
1972
1973     if (resize != RESIZE_VERTICAL && difference.width()) {
1974         if (element->isFormControlElement()) {
1975             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
1976             styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, String::number(renderer->marginLeft() / zoomFactor) + "px", false);
1977             styledElement->setInlineStyleProperty(CSSPropertyMarginRight, String::number(renderer->marginRight() / zoomFactor) + "px", false);
1978         }
1979         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? ZERO_LAYOUT_UNIT : renderer->borderAndPaddingWidth());
1980         baseWidth = baseWidth / zoomFactor;
1981         styledElement->setInlineStyleProperty(CSSPropertyWidth, String::number(roundToInt(baseWidth + difference.width())) + "px", false);
1982     }
1983
1984     if (resize != RESIZE_HORIZONTAL && difference.height()) {
1985         if (element->isFormControlElement()) {
1986             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
1987             styledElement->setInlineStyleProperty(CSSPropertyMarginTop, String::number(renderer->marginTop() / zoomFactor) + "px", false);
1988             styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, String::number(renderer->marginBottom() / zoomFactor) + "px", false);
1989         }
1990         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? ZERO_LAYOUT_UNIT : renderer->borderAndPaddingHeight());
1991         baseHeight = baseHeight / zoomFactor;
1992         styledElement->setInlineStyleProperty(CSSPropertyHeight, String::number(roundToInt(baseHeight + difference.height())) + "px", false);
1993     }
1994
1995     document->updateLayout();
1996
1997     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
1998 }
1999
2000 int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
2001 {
2002     Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_hBar : m_vBar).get();
2003     return scrollbar ? (scrollbar->totalSize() - scrollbar->visibleSize()) : 0;
2004 }
2005
2006 void RenderLayer::setScrollOffset(const IntPoint& offset)
2007 {
2008     scrollTo(offset.x(), offset.y());
2009 }
2010
2011 int RenderLayer::scrollPosition(Scrollbar* scrollbar) const
2012 {
2013     if (scrollbar->orientation() == HorizontalScrollbar)
2014         return scrollXOffset();
2015     if (scrollbar->orientation() == VerticalScrollbar)
2016         return scrollYOffset();
2017     return 0;
2018 }
2019
2020 IntPoint RenderLayer::scrollPosition() const
2021 {
2022     return scrollOrigin() + m_scrollOffset;
2023 }
2024
2025 IntPoint RenderLayer::minimumScrollPosition() const
2026 {
2027     return scrollOrigin();
2028 }
2029
2030 IntPoint RenderLayer::maximumScrollPosition() const
2031 {
2032     // FIXME: m_scrollSize may not be up-to-date if m_scrollDimensionsDirty is true.
2033     return scrollOrigin() + roundedIntSize(m_scrollSize) - visibleContentRect(true).size();
2034 }
2035
2036 IntRect RenderLayer::visibleContentRect(bool includeScrollbars) const
2037 {
2038     int verticalScrollbarWidth = 0;
2039     int horizontalScrollbarHeight = 0;
2040     if (includeScrollbars) {
2041         verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
2042         horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
2043     }
2044     
2045     return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
2046                    IntSize(max(0, m_layerSize.width() - verticalScrollbarWidth), 
2047                            max(0, m_layerSize.height() - horizontalScrollbarHeight)));
2048 }
2049
2050 IntSize RenderLayer::overhangAmount() const
2051 {
2052     return IntSize();
2053 }
2054
2055 bool RenderLayer::isActive() const
2056 {
2057     Page* page = renderer()->frame()->page();
2058     return page && page->focusController()->isActive();
2059 }
2060
2061 static int cornerStart(const RenderLayer* layer, int minX, int maxX, int thickness)
2062 {
2063     if (layer->renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2064         return minX + layer->renderer()->style()->borderLeftWidth();
2065     return maxX - thickness - layer->renderer()->style()->borderRightWidth();
2066 }
2067
2068 static IntRect cornerRect(const RenderLayer* layer, const IntRect& bounds)
2069 {
2070     int horizontalThickness;
2071     int verticalThickness;
2072     if (!layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2073         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
2074         // even when they don't exist in order to set the resizer square size properly.
2075         horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
2076         verticalThickness = horizontalThickness;
2077     } else if (layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2078         horizontalThickness = layer->verticalScrollbar()->width();
2079         verticalThickness = horizontalThickness;
2080     } else if (layer->horizontalScrollbar() && !layer->verticalScrollbar()) {
2081         verticalThickness = layer->horizontalScrollbar()->height();
2082         horizontalThickness = verticalThickness;
2083     } else {
2084         horizontalThickness = layer->verticalScrollbar()->width();
2085         verticalThickness = layer->horizontalScrollbar()->height();
2086     }
2087     return IntRect(cornerStart(layer, bounds.x(), bounds.maxX(), horizontalThickness),
2088                    bounds.maxY() - verticalThickness - layer->renderer()->style()->borderBottomWidth(),
2089                    horizontalThickness, verticalThickness);
2090 }
2091
2092 IntRect RenderLayer::scrollCornerRect() const
2093 {
2094     // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
2095     // This happens when:
2096     // (a) A resizer is present and at least one scrollbar is present
2097     // (b) Both scrollbars are present.
2098     bool hasHorizontalBar = horizontalScrollbar();
2099     bool hasVerticalBar = verticalScrollbar();
2100     bool hasResizer = renderer()->style()->resize() != RESIZE_NONE;
2101     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
2102         return cornerRect(this, renderBox()->pixelSnappedBorderBoxRect());
2103     return IntRect();
2104 }
2105
2106 static IntRect resizerCornerRect(const RenderLayer* layer, const IntRect& bounds)
2107 {
2108     ASSERT(layer->renderer()->isBox());
2109     if (layer->renderer()->style()->resize() == RESIZE_NONE)
2110         return IntRect();
2111     return cornerRect(layer, bounds);
2112 }
2113
2114 IntRect RenderLayer::scrollCornerAndResizerRect() const
2115 {
2116     RenderBox* box = renderBox();
2117     if (!box)
2118         return IntRect();
2119     IntRect scrollCornerAndResizer = scrollCornerRect();
2120     if (scrollCornerAndResizer.isEmpty())
2121         scrollCornerAndResizer = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2122     return scrollCornerAndResizer;
2123 }
2124
2125 bool RenderLayer::isScrollCornerVisible() const
2126 {
2127     ASSERT(renderer()->isBox());
2128     return !scrollCornerRect().isEmpty();
2129 }
2130
2131 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
2132 {
2133     RenderView* view = renderer()->view();
2134     if (!view)
2135         return scrollbarRect;
2136
2137     IntRect rect = scrollbarRect;
2138     rect.move(scrollbarOffset(scrollbar));
2139
2140     return view->frameView()->convertFromRenderer(renderer(), rect);
2141 }
2142
2143 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
2144 {
2145     RenderView* view = renderer()->view();
2146     if (!view)
2147         return parentRect;
2148
2149     IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
2150     rect.move(-scrollbarOffset(scrollbar));
2151     return rect;
2152 }
2153
2154 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
2155 {
2156     RenderView* view = renderer()->view();
2157     if (!view)
2158         return scrollbarPoint;
2159
2160     IntPoint point = scrollbarPoint;
2161     point.move(scrollbarOffset(scrollbar));
2162     return view->frameView()->convertFromRenderer(renderer(), point);
2163 }
2164
2165 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
2166 {
2167     RenderView* view = renderer()->view();
2168     if (!view)
2169         return parentPoint;
2170
2171     IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
2172
2173     point.move(-scrollbarOffset(scrollbar));
2174     return point;
2175 }
2176
2177 IntSize RenderLayer::contentsSize() const
2178 {
2179     return IntSize(scrollWidth(), scrollHeight());
2180 }
2181
2182 int RenderLayer::visibleHeight() const
2183 {
2184     return m_layerSize.height();
2185 }
2186
2187 int RenderLayer::visibleWidth() const
2188 {
2189     return m_layerSize.width();
2190 }
2191
2192 bool RenderLayer::shouldSuspendScrollAnimations() const
2193 {
2194     RenderView* view = renderer()->view();
2195     if (!view)
2196         return true;
2197     return view->frameView()->shouldSuspendScrollAnimations();
2198 }
2199
2200 bool RenderLayer::isOnActivePage() const
2201 {
2202     return !m_renderer->document()->inPageCache();
2203 }
2204
2205 IntPoint RenderLayer::currentMousePosition() const
2206 {
2207     return renderer()->frame() ? renderer()->frame()->eventHandler()->currentMousePosition() : IntPoint();
2208 }
2209
2210 LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
2211 {
2212     const RenderBox* box = renderBox();
2213     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2214         return minX + box->borderLeft();
2215     return maxX - box->borderRight() - m_vBar->width();
2216 }
2217
2218 LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
2219 {
2220     const RenderBox* box = renderBox();
2221     int x = minX + box->borderLeft();
2222     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2223         x += m_vBar ? m_vBar->width() : resizerCornerRect(this, box->pixelSnappedBorderBoxRect()).width();
2224     return x;
2225 }
2226
2227 IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
2228 {
2229     RenderBox* box = renderBox();
2230
2231     if (scrollbar == m_vBar.get())
2232         return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
2233
2234     if (scrollbar == m_hBar.get())
2235         return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2236     
2237     ASSERT_NOT_REACHED();
2238     return IntSize();
2239 }
2240
2241 void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
2242 {
2243 #if USE(ACCELERATED_COMPOSITING)
2244     if (scrollbar == m_vBar.get()) {
2245         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2246             layer->setNeedsDisplayInRect(rect);
2247             return;
2248         }
2249     } else {
2250         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2251             layer->setNeedsDisplayInRect(rect);
2252             return;
2253         }
2254     }
2255 #endif
2256     IntRect scrollRect = rect;
2257     RenderBox* box = renderBox();
2258     ASSERT(box);
2259     // If we are not yet inserted into the tree, there is no need to repaint.
2260     if (!box->parent())
2261         return;
2262
2263     if (scrollbar == m_vBar.get())
2264         scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
2265     else
2266         scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2267     renderer()->repaintRectangle(scrollRect);
2268 }
2269
2270 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
2271 {
2272 #if USE(ACCELERATED_COMPOSITING)
2273     if (GraphicsLayer* layer = layerForScrollCorner()) {
2274         layer->setNeedsDisplayInRect(rect);
2275         return;
2276     }
2277 #endif
2278     if (m_scrollCorner)
2279         m_scrollCorner->repaintRectangle(rect);
2280     if (m_resizer)
2281         m_resizer->repaintRectangle(rect);
2282 }
2283
2284 PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
2285 {
2286     RefPtr<Scrollbar> widget;
2287     RenderObject* actualRenderer = renderer()->node() ? renderer()->node()->shadowAncestorNode()->renderer() : renderer();
2288     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
2289     if (hasCustomScrollbarStyle)
2290         widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->node());
2291     else {
2292         widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
2293         if (orientation == HorizontalScrollbar)
2294             didAddHorizontalScrollbar(widget.get());
2295         else 
2296             didAddVerticalScrollbar(widget.get());
2297     }
2298     renderer()->document()->view()->addChild(widget.get());        
2299     return widget.release();
2300 }
2301
2302 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
2303 {
2304     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
2305     if (!scrollbar)
2306         return;
2307
2308     if (!scrollbar->isCustomScrollbar()) {
2309         if (orientation == HorizontalScrollbar)
2310             willRemoveHorizontalScrollbar(scrollbar.get());
2311         else
2312             willRemoveVerticalScrollbar(scrollbar.get());
2313     }
2314
2315     scrollbar->removeFromParent();
2316     scrollbar->disconnectFromScrollableArea();
2317     scrollbar = 0;
2318 }
2319
2320 bool RenderLayer::scrollsOverflow() const
2321 {
2322     if (!renderer()->isBox())
2323         return false;
2324
2325     return toRenderBox(renderer())->scrollsOverflow();
2326 }
2327
2328 bool RenderLayer::allowsScrolling() const
2329 {
2330     return (m_hBar && m_hBar->enabled()) || (m_vBar && m_vBar->enabled());
2331 }
2332
2333 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
2334 {
2335     if (hasScrollbar == hasHorizontalScrollbar())
2336         return;
2337
2338     if (hasScrollbar)
2339         m_hBar = createScrollbar(HorizontalScrollbar);
2340     else
2341         destroyScrollbar(HorizontalScrollbar);
2342
2343     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2344     if (m_hBar)
2345         m_hBar->styleChanged();
2346     if (m_vBar)
2347         m_vBar->styleChanged();
2348
2349 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2350     // Force an update since we know the scrollbars have changed things.
2351     if (renderer()->document()->hasDashboardRegions())
2352         renderer()->document()->setDashboardRegionsDirty(true);
2353 #endif
2354 }
2355
2356 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
2357 {
2358     if (hasScrollbar == hasVerticalScrollbar())
2359         return;
2360
2361     if (hasScrollbar)
2362         m_vBar = createScrollbar(VerticalScrollbar);
2363     else
2364         destroyScrollbar(VerticalScrollbar);
2365
2366      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2367     if (m_hBar)
2368         m_hBar->styleChanged();
2369     if (m_vBar)
2370         m_vBar->styleChanged();
2371
2372 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2373     // Force an update since we know the scrollbars have changed things.
2374     if (renderer()->document()->hasDashboardRegions())
2375         renderer()->document()->setDashboardRegionsDirty(true);
2376 #endif
2377 }
2378
2379 ScrollableArea* RenderLayer::enclosingScrollableArea() const
2380 {
2381     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2382         return scrollableLayer;
2383
2384     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
2385     // if the frame view isn't scrollable.
2386     return 0;
2387 }
2388
2389 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
2390 {
2391     if (!m_vBar || (m_vBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
2392         return 0;
2393     return m_vBar->width();
2394 }
2395
2396 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
2397 {
2398     if (!m_hBar || (m_hBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
2399         return 0;
2400     return m_hBar->height();
2401 }
2402
2403 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
2404 {
2405     // Currently the resize corner is either the bottom right corner or the bottom left corner.
2406     // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
2407     IntSize elementSize = size();
2408     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2409         elementSize.setWidth(0);
2410     IntPoint resizerPoint = toPoint(elementSize);
2411     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2412     return localPoint - resizerPoint;
2413 }
2414
2415 bool RenderLayer::hasOverflowControls() const
2416 {
2417     return m_hBar || m_vBar || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
2418 }
2419
2420 void RenderLayer::positionOverflowControls(const IntSize& offsetFromLayer)
2421 {
2422     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2423         return;
2424     
2425     RenderBox* box = renderBox();
2426     if (!box)
2427         return;
2428
2429     const IntRect borderBox = box->pixelSnappedBorderBoxRect();
2430     const IntRect& scrollCorner = scrollCornerRect();
2431     IntRect absBounds(borderBox.location() + offsetFromLayer, borderBox.size());
2432     if (m_vBar)
2433         m_vBar->setFrameRect(IntRect(verticalScrollbarStart(absBounds.x(), absBounds.maxX()),
2434                                      absBounds.y() + box->borderTop(),
2435                                      m_vBar->width(),
2436                                      absBounds.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height()));
2437
2438     if (m_hBar)
2439         m_hBar->setFrameRect(IntRect(horizontalScrollbarStart(absBounds.x()),
2440                                      absBounds.maxY() - box->borderBottom() - m_hBar->height(),
2441                                      absBounds.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
2442                                      m_hBar->height()));
2443
2444 #if USE(ACCELERATED_COMPOSITING)
2445     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2446         if (m_hBar) {
2447             layer->setPosition(m_hBar->frameRect().location() - offsetFromLayer);
2448             layer->setSize(m_hBar->frameRect().size());
2449         }
2450         layer->setDrawsContent(m_hBar);
2451     }
2452     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2453         if (m_vBar) {
2454             layer->setPosition(m_vBar->frameRect().location() - offsetFromLayer);
2455             layer->setSize(m_vBar->frameRect().size());
2456         }
2457         layer->setDrawsContent(m_vBar);
2458     }
2459
2460     if (GraphicsLayer* layer = layerForScrollCorner()) {
2461         const LayoutRect& scrollCornerAndResizer = scrollCornerAndResizerRect();
2462         layer->setPosition(scrollCornerAndResizer.location());
2463         layer->setSize(scrollCornerAndResizer.size());
2464         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
2465     }
2466 #endif
2467
2468     if (m_scrollCorner)
2469         m_scrollCorner->setFrameRect(scrollCorner);
2470     if (m_resizer)
2471         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
2472 }
2473
2474 int RenderLayer::scrollWidth() const
2475 {
2476     ASSERT(renderBox());
2477     if (m_scrollDimensionsDirty)
2478         const_cast<RenderLayer*>(this)->computeScrollDimensions();
2479     return snapSizeToPixel(m_scrollSize.width(), renderBox()->clientLeft() + renderBox()->x());
2480 }
2481
2482 int RenderLayer::scrollHeight() const
2483 {
2484     ASSERT(renderBox());
2485     if (m_scrollDimensionsDirty)
2486         const_cast<RenderLayer*>(this)->computeScrollDimensions();
2487     return snapSizeToPixel(m_scrollSize.height(), renderBox()->clientTop() + renderBox()->y());
2488 }
2489
2490 LayoutUnit RenderLayer::overflowTop() const
2491 {
2492     RenderBox* box = renderBox();
2493     LayoutRect overflowRect(box->layoutOverflowRect());
2494     box->flipForWritingMode(overflowRect);
2495     return overflowRect.y();
2496 }
2497
2498 LayoutUnit RenderLayer::overflowBottom() const
2499 {
2500     RenderBox* box = renderBox();
2501     LayoutRect overflowRect(box->layoutOverflowRect());
2502     box->flipForWritingMode(overflowRect);
2503     return overflowRect.maxY();
2504 }
2505
2506 LayoutUnit RenderLayer::overflowLeft() const
2507 {
2508     RenderBox* box = renderBox();
2509     LayoutRect overflowRect(box->layoutOverflowRect());
2510     box->flipForWritingMode(overflowRect);
2511     return overflowRect.x();
2512 }
2513
2514 LayoutUnit RenderLayer::overflowRight() const
2515 {
2516     RenderBox* box = renderBox();
2517     LayoutRect overflowRect(box->layoutOverflowRect());
2518     box->flipForWritingMode(overflowRect);
2519     return overflowRect.maxX();
2520 }
2521
2522 void RenderLayer::computeScrollDimensions()
2523 {
2524     RenderBox* box = renderBox();
2525     ASSERT(box);
2526
2527     m_scrollDimensionsDirty = false;
2528
2529     m_scrollSize.setWidth(overflowRight() - overflowLeft());
2530     m_scrollSize.setHeight(overflowBottom() - overflowTop());
2531
2532     int scrollableLeftOverflow = overflowLeft() - box->borderLeft();
2533     int scrollableTopOverflow = overflowTop() - box->borderTop();
2534     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
2535 }
2536
2537 bool RenderLayer::hasHorizontalOverflow() const
2538 {
2539     ASSERT(!m_scrollDimensionsDirty);
2540
2541     return scrollWidth() > renderBox()->pixelSnappedClientWidth();
2542 }
2543
2544 bool RenderLayer::hasVerticalOverflow() const
2545 {
2546     ASSERT(!m_scrollDimensionsDirty);
2547
2548     return scrollHeight() > renderBox()->pixelSnappedClientHeight();
2549 }
2550
2551 void RenderLayer::updateScrollbarsAfterLayout()
2552 {
2553     RenderBox* box = renderBox();
2554     ASSERT(box);
2555
2556     // List box parts handle the scrollbars by themselves so we have nothing to do.
2557     if (box->style()->appearance() == ListboxPart)
2558         return;
2559
2560     bool hasHorizontalOverflow = this->hasHorizontalOverflow();
2561     bool hasVerticalOverflow = this->hasVerticalOverflow();
2562
2563     // overflow:scroll should just enable/disable.
2564     if (renderer()->style()->overflowX() == OSCROLL)
2565         m_hBar->setEnabled(hasHorizontalOverflow);
2566     if (renderer()->style()->overflowY() == OSCROLL)
2567         m_vBar->setEnabled(hasVerticalOverflow);
2568
2569     // overflow:auto may need to lay out again if scrollbars got added/removed.
2570     bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
2571     bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
2572
2573     if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
2574         if (box->hasAutoHorizontalScrollbar())
2575             setHasHorizontalScrollbar(hasHorizontalOverflow);
2576         if (box->hasAutoVerticalScrollbar())
2577             setHasVerticalScrollbar(hasVerticalOverflow);
2578
2579         updateSelfPaintingLayer();
2580
2581 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2582         // Force an update since we know the scrollbars have changed things.
2583         if (renderer()->document()->hasDashboardRegions())
2584             renderer()->document()->setDashboardRegionsDirty(true);
2585 #endif
2586
2587         renderer()->repaint();
2588
2589         if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
2590             if (!m_inOverflowRelayout) {
2591                 // Our proprietary overflow: overlay value doesn't trigger a layout.
2592                 m_inOverflowRelayout = true;
2593                 renderer()->setNeedsLayout(true, MarkOnlyThis);
2594                 if (renderer()->isRenderBlock()) {
2595                     RenderBlock* block = toRenderBlock(renderer());
2596                     block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
2597                     block->layoutBlock(true);
2598                 } else
2599                     renderer()->layout();
2600                 m_inOverflowRelayout = false;
2601             }
2602         }
2603     }
2604
2605     // Set up the range (and page step/line step).
2606     if (m_hBar) {
2607         int clientWidth = box->pixelSnappedClientWidth();
2608         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
2609         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2610         m_hBar->setProportion(clientWidth, m_scrollSize.width());
2611     }
2612     if (m_vBar) {
2613         int clientHeight = box->pixelSnappedClientHeight();
2614         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
2615         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2616         m_vBar->setProportion(clientHeight, m_scrollSize.height());
2617     }
2618
2619     updateScrollableAreaSet((hasHorizontalOverflow || hasVerticalOverflow) && scrollsOverflow());
2620 }
2621
2622 void RenderLayer::updateScrollInfoAfterLayout()
2623 {
2624     RenderBox* box = renderBox();
2625     if (!box)
2626         return;
2627
2628     m_scrollDimensionsDirty = true;
2629     IntSize originalScrollOffset = scrollOffset();
2630
2631     computeScrollDimensions();
2632
2633     if (box->style()->overflowX() != OMARQUEE) {
2634         // Layout may cause us to be at an invalid scroll position. In this case we need
2635         // to pull our scroll offsets back to the max (or push them up to the min).
2636         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset());
2637         if (clampedScrollOffset != scrollOffset())
2638             scrollToOffset(clampedScrollOffset);
2639     }
2640
2641     updateScrollbarsAfterLayout();
2642
2643     if (originalScrollOffset != scrollOffset())
2644         scrollToOffsetWithoutAnimation(toPoint(scrollOffset()));
2645 }
2646
2647 void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
2648 {
2649     // Don't do anything if we have no overflow.
2650     if (!renderer()->hasOverflowClip())
2651         return;
2652
2653     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
2654     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
2655     // will be false, and we should just tell the root layer that there are overlay scrollbars
2656     // that need to be painted. That will cause the second pass through the layer tree to run,
2657     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
2658     // second pass doesn't need to re-enter the RenderTree to get it right.
2659     if (hasOverlayScrollbars() && !paintingOverlayControls) {
2660         m_cachedOverlayScrollbarOffset = paintOffset;
2661 #if USE(ACCELERATED_COMPOSITING)
2662         // It's not necessary to do the second pass if the scrollbars paint into layers.
2663         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
2664             return;
2665 #endif
2666         RenderView* renderView = renderer()->view();
2667         renderView->layer()->setContainsDirtyOverlayScrollbars(true);
2668         renderView->frameView()->setContainsScrollableAreaWithOverlayScrollbars(true);
2669         return;
2670     }
2671
2672     // This check is required to avoid painting custom CSS scrollbars twice.
2673     if (paintingOverlayControls && !hasOverlayScrollbars())
2674         return;
2675
2676     IntPoint adjustedPaintOffset = paintOffset;
2677     if (paintingOverlayControls)
2678         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
2679
2680     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
2681     // widgets can move without layout occurring (most notably when you scroll a document that
2682     // contains fixed positioned elements).
2683     positionOverflowControls(toSize(adjustedPaintOffset));
2684
2685     // Now that we're sure the scrollbars are in the right place, paint them.
2686     if (m_hBar
2687 #if USE(ACCELERATED_COMPOSITING)
2688         && !layerForHorizontalScrollbar()
2689 #endif
2690               )
2691         m_hBar->paint(context, damageRect);
2692     if (m_vBar
2693 #if USE(ACCELERATED_COMPOSITING)
2694         && !layerForVerticalScrollbar()
2695 #endif
2696               )
2697         m_vBar->paint(context, damageRect);
2698
2699 #if USE(ACCELERATED_COMPOSITING)
2700     if (layerForScrollCorner())
2701         return;
2702 #endif
2703
2704     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
2705     // edge of the box.
2706     paintScrollCorner(context, adjustedPaintOffset, damageRect);
2707     
2708     // Paint our resizer last, since it sits on top of the scroll corner.
2709     paintResizer(context, adjustedPaintOffset, damageRect);
2710 }
2711
2712 void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2713 {
2714     RenderBox* box = renderBox();
2715     ASSERT(box);
2716
2717     IntRect absRect = scrollCornerRect();
2718     absRect.moveBy(paintOffset);
2719     if (!absRect.intersects(damageRect))
2720         return;
2721
2722     if (context->updatingControlTints()) {
2723         updateScrollCornerStyle();
2724         return;
2725     }
2726
2727     if (m_scrollCorner) {
2728         m_scrollCorner->paintIntoRect(context, paintOffset, absRect);
2729         return;
2730     }
2731
2732     // We don't want to paint white if we have overlay scrollbars, since we need
2733     // to see what is behind it.
2734     if (!hasOverlayScrollbars())
2735         context->fillRect(absRect, Color::white, box->style()->colorSpace());
2736 }
2737
2738 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
2739 {
2740     float deviceScaleFactor = WebCore::deviceScaleFactor(renderer()->frame());
2741
2742     RefPtr<Image> resizeCornerImage;
2743     IntSize cornerResizerSize;
2744     if (deviceScaleFactor >= 2) {
2745         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
2746         resizeCornerImage = resizeCornerImageHiRes;
2747         cornerResizerSize = resizeCornerImage->size();
2748         cornerResizerSize.scale(0.5f);
2749     } else {
2750         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
2751         resizeCornerImage = resizeCornerImageLoRes;
2752         cornerResizerSize = resizeCornerImage->size();
2753     }
2754
2755     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
2756         context->save();
2757         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
2758         context->scale(FloatSize(-1.0, 1.0));
2759         context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), IntRect(IntPoint(), cornerResizerSize));
2760         context->restore();
2761         return;
2762     }
2763     IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
2764     context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), imageRect);
2765 }
2766
2767 void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2768 {
2769     if (renderer()->style()->resize() == RESIZE_NONE)
2770         return;
2771
2772     RenderBox* box = renderBox();
2773     ASSERT(box);
2774
2775     IntRect absRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2776     absRect.moveBy(paintOffset);
2777     if (!absRect.intersects(damageRect))
2778         return;
2779
2780     if (context->updatingControlTints()) {
2781         updateResizerStyle();
2782         return;
2783     }
2784     
2785     if (m_resizer) {
2786         m_resizer->paintIntoRect(context, paintOffset, absRect);
2787         return;
2788     }
2789
2790     drawPlatformResizerImage(context, absRect);
2791
2792     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
2793     // Clipping will exclude the right and bottom edges of this frame.
2794     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
2795         GraphicsContextStateSaver stateSaver(*context);
2796         context->clip(absRect);
2797         IntRect largerCorner = absRect;
2798         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
2799         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
2800         context->setStrokeThickness(1.0f);
2801         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
2802         context->drawRect(largerCorner);
2803     }
2804 }
2805
2806 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
2807 {
2808     if (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE)
2809         return false;
2810     
2811     RenderBox* box = renderBox();
2812     ASSERT(box);
2813
2814     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2815
2816     IntRect localBounds(0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
2817     return resizerCornerRect(this, localBounds).contains(localPoint);
2818 }
2819     
2820 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
2821 {
2822     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2823         return false;
2824
2825     RenderBox* box = renderBox();
2826     ASSERT(box);
2827     
2828     IntRect resizeControlRect;
2829     if (renderer()->style()->resize() != RESIZE_NONE) {
2830         resizeControlRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2831         if (resizeControlRect.contains(localPoint))
2832             return true;
2833     }
2834
2835     int resizeControlSize = max(resizeControlRect.height(), 0);
2836
2837     if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
2838         LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
2839                             box->borderTop(),
2840                             m_vBar->width(),
2841                             box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
2842         if (vBarRect.contains(localPoint)) {
2843             result.setScrollbar(m_vBar.get());
2844             return true;
2845         }
2846     }
2847
2848     resizeControlSize = max(resizeControlRect.width(), 0);
2849     if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
2850         LayoutRect hBarRect(horizontalScrollbarStart(0),
2851                             box->height() - box->borderBottom() - m_hBar->height(),
2852                             box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
2853                             m_hBar->height());
2854         if (hBarRect.contains(localPoint)) {
2855             result.setScrollbar(m_hBar.get());
2856             return true;
2857         }
2858     }
2859
2860     return false;
2861 }
2862
2863 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
2864 {
2865     return ScrollableArea::scroll(direction, granularity, multiplier);
2866 }
2867
2868 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
2869 {
2870     OverlapTestRequestMap overlapTestRequests;
2871     paintLayer(this, context, enclosingIntRect(damageRect), LayoutSize(), paintBehavior, paintingRoot, region, &overlapTestRequests, paintFlags);
2872     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2873     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
2874         it->key->setOverlapTestResult(false);
2875 }
2876
2877 void RenderLayer::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot)
2878 {
2879     if (!m_containsDirtyOverlayScrollbars)
2880         return;
2881     paintLayer(this, context, damageRect, LayoutSize(), paintBehavior, paintingRoot, 0, 0, PaintLayerHaveTransparency | PaintLayerTemporaryClipRects 
2882                | PaintLayerPaintingOverlayScrollbars);
2883     m_containsDirtyOverlayScrollbars = false;
2884 }
2885
2886 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2887 static bool inContainingBlockChain(RenderLayer* startLayer, RenderLayer* endLayer)
2888 {
2889     if (startLayer == endLayer)
2890         return true;
2891     
2892     RenderView* view = startLayer->renderer()->view();
2893     for (RenderBlock* currentBlock = startLayer->renderer()->containingBlock(); currentBlock && currentBlock != view; currentBlock = currentBlock->containingBlock()) {
2894         if (currentBlock->layer() == endLayer)
2895             return true;
2896     }
2897     
2898     return false;
2899 }
2900 #endif
2901
2902 void RenderLayer::clipToRect(RenderLayer* rootLayer, GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect,
2903                              BorderRadiusClippingRule rule)
2904 {
2905     if (clipRect.rect() == paintDirtyRect)
2906         return;
2907     context->save();
2908     context->clip(pixelSnappedIntRect(clipRect.rect()));
2909     
2910     if (!clipRect.hasRadius())
2911         return;
2912
2913 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2914     // If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
2915     // any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
2916     // containing block chain so we check that also.
2917     for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
2918         if (layer->renderer()->hasOverflowClip() && layer->renderer()->style()->hasBorderRadius() && inContainingBlockChain(this, layer)) {
2919                 LayoutPoint delta;
2920                 layer->convertToLayerCoords(rootLayer, delta);
2921                 context->addRoundedRectClip(layer->renderer()->style()->getRoundedInnerBorderFor(LayoutRect(delta, layer->size())));
2922         }
2923
2924         if (layer == rootLayer)
2925             break;
2926     }
2927 #endif
2928 }
2929
2930 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
2931 {
2932     if (clipRect.rect() == paintDirtyRect)
2933         return;
2934     context->restore();
2935 }
2936
2937 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
2938 {
2939     Vector<OverlapTestRequestClient*> overlappedRequestClients;
2940     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2941     LayoutRect boundingBox = layer->boundingBox(rootLayer);
2942     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
2943         if (!boundingBox.intersects(it->value))
2944             continue;
2945
2946         it->key->setOverlapTestResult(true);
2947         overlappedRequestClients.append(it->key);
2948     }
2949     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
2950         overlapTestRequests.remove(overlappedRequestClients[i]);
2951 }
2952
2953 #if USE(ACCELERATED_COMPOSITING)
2954 static bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
2955 {
2956     return paintingReflection && !layer->has3DTransform();
2957 }
2958 #endif
2959     
2960 static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
2961 {
2962     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
2963     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2964     // will do a full repaint().
2965     if (layer->renderer()->document()->didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer()->isRoot())
2966         return true;
2967
2968     // Avoid painting all layers if the document is in a state where visual updates aren't allowed.
2969     // A full repaint will occur in Document::implicitClose() if painting is suppressed here.
2970     if (!layer->renderer()->document()->visualUpdatesAllowed())
2971         return true;
2972
2973     return false;
2974 }
2975
2976
2977 void RenderLayer::paintLayer(RenderLayer* rootLayer, GraphicsContext* context,
2978                         const LayoutRect& paintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
2979                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
2980                         PaintLayerFlags paintFlags)
2981 {
2982 #if USE(ACCELERATED_COMPOSITING)
2983     if (isComposited()) {
2984         // The updatingControlTints() painting pass goes through compositing layers,
2985         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
2986         if (context->updatingControlTints() || (paintBehavior & PaintBehaviorFlattenCompositingLayers))
2987             paintFlags |= PaintLayerTemporaryClipRects;
2988         else if (!backing()->paintsIntoWindow() && !backing()->paintsIntoCompositedAncestor() && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection) && !(rootLayer->containsDirtyOverlayScrollbars() && (paintFlags & PaintLayerPaintingOverlayScrollbars))) {
2989             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
2990             return;
2991         }
2992     }
2993 #endif
2994
2995     // Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
2996     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
2997         return;
2998
2999     if (shouldSuppressPaintingLayer(this))
3000         return;
3001     
3002     // If this layer is totally invisible then there is nothing to paint.
3003     if (!renderer()->opacity())
3004         return;
3005
3006     if (paintsWithTransparency(paintBehavior))
3007         paintFlags |= PaintLayerHaveTransparency;
3008
3009     // PaintLayerAppliedTransform is used in RenderReplica, to avoid applying the transform twice.
3010     if (paintsWithTransform(paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
3011         TransformationMatrix layerTransform = renderableTransform(paintBehavior);
3012         // If the transform can't be inverted, then don't paint anything.
3013         if (!layerTransform.isInvertible())
3014             return;
3015
3016         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
3017         // layer from the parent now, assuming there is a parent
3018         if (paintFlags & PaintLayerHaveTransparency) {
3019             if (parent())
3020                 parent()->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
3021             else
3022                 beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
3023         }
3024
3025         // Make sure the parent's clip rects have been calculated.
3026         ClipRect clipRect = paintDirtyRect;
3027         if (parent()) {
3028             clipRect = backgroundClipRect(rootLayer, region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects,
3029                 IgnoreOverlayScrollbarSize, (paintFlags & PaintLayerPaintingOverflowContents) ? IgnoreOverflowClip : RespectOverflowClip);
3030             clipRect.intersect(paintDirtyRect);
3031         
3032             // Push the parent coordinate space's clip.
3033             parent()->clipToRect(rootLayer, context, paintDirtyRect, clipRect);
3034         }
3035
3036         // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
3037         // This involves subtracting out the position of the layer in our current coordinate space, but preserving
3038         // the accumulated error for sub-pixel layout.
3039         LayoutPoint delta;
3040         convertToLayerCoords(rootLayer, delta);
3041         TransformationMatrix transform(layerTransform);
3042         IntPoint roundedDelta = roundedIntPoint(delta);
3043         transform.translateRight(roundedDelta.x(), roundedDelta.y());
3044         LayoutSize adjustedSubPixelAccumulation = subPixelAccumulation + (delta - roundedDelta);
3045         
3046         // Apply the transform.
3047         {
3048             GraphicsContextStateSaver stateSaver(*context);
3049             context->concatCTM(transform.toAffineTransform());
3050
3051             // Now do a paint with the root layer shifted to be us.
3052             paintLayerContentsAndReflection(this, context, enclosingIntRect(transform.inverse().mapRect(paintDirtyRect)), adjustedSubPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3053         }        
3054
3055         // Restore the clip.
3056         if (parent())
3057             parent()->restoreClip(context, paintDirtyRect, clipRect);
3058
3059         return;
3060     }
3061     
3062     paintLayerContentsAndReflection(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3063 }
3064
3065 void RenderLayer::paintLayerContentsAndReflection(RenderLayer* rootLayer, GraphicsContext* context,
3066                         const LayoutRect& paintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
3067                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3068                         PaintLayerFlags paintFlags)
3069 {
3070     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3071
3072     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3073
3074     // Paint the reflection first if we have one.
3075     if (m_reflection && !m_paintingInsideReflection) {
3076         // Mark that we are now inside replica painting.
3077         m_paintingInsideReflection = true;
3078         reflectionLayer()->paintLayer(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags | PaintLayerPaintingReflection);
3079         m_paintingInsideReflection = false;
3080     }
3081
3082     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
3083     paintLayerContents(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3084 }
3085
3086 void RenderLayer::paintLayerContents(RenderLayer* rootLayer, GraphicsContext* context, 
3087                         const LayoutRect& parentPaintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
3088                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3089                         PaintLayerFlags paintFlags)
3090 {
3091     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3092
3093     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3094     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
3095     bool isSelfPaintingLayer = this->isSelfPaintingLayer();
3096     bool isPaintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
3097     // Outline always needs to be painted even if we have no visible content.
3098     bool shouldPaintOutline = isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3099     bool shouldPaintContent = m_hasVisibleContent && isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3100
3101     // Calculate the clip rects we should use only when we need them.
3102     LayoutRect layerBounds;
3103     ClipRect damageRect, clipRectToApply, outlineRect;
3104     LayoutPoint paintOffset;
3105     LayoutRect paintDirtyRect = parentPaintDirtyRect;
3106     
3107     bool useClipRect = true;
3108     GraphicsContext* transparencyLayerContext = context;
3109     
3110     // Ensure our lists are up-to-date.
3111     updateLayerListsIfNeeded();
3112
3113 #if ENABLE(CSS_FILTERS)
3114     FilterEffectRendererHelper filterPainter(filterRenderer() && paintsWithFilters());
3115     if (filterPainter.haveFilterEffect() && !context->paintingDisabled()) {
3116         LayoutPoint rootLayerOffset;
3117         convertToLayerCoords(rootLayer, rootLayerOffset);
3118         RenderLayerFilterInfo* filterInfo = this->filterInfo();
3119         ASSERT(filterInfo);
3120         LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
3121         filterRepaintRect.move(rootLayerOffset.x(), rootLayerOffset.y());
3122         if (filterPainter.prepareFilterEffect(this, calculateLayerBounds(this, rootLayer, 0), parentPaintDirtyRect, filterRepaintRect)) {
3123             // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
3124             filterInfo->resetDirtySourceRect();
3125
3126             // Rewire the old context to a memory buffer, so that we can capture the contents of the layer.
3127             // NOTE: We saved the old context in the "transparencyLayerContext" local variable, to be able to start a transparency layer
3128             // on the original context and avoid duplicating "beginFilterEffect" after each transpareny layer call. Also, note that 
3129             // beginTransparencyLayers will only create a single lazy transparency layer, even though it is called twice in this method.
3130             context = filterPainter.beginFilterEffect(context);
3131
3132             // Check that we didn't fail to allocate the graphics context for the offscreen buffer.
3133             if (filterPainter.hasStartedFilterEffect()) {
3134                 paintDirtyRect = filterPainter.repaintRect();
3135                 // If the filter needs the full source image, we need to avoid using the clip rectangles.
3136                 // Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
3137                 // Note that we will still apply the clipping on the final rendering of the filter.
3138                 useClipRect = !filterRenderer()->hasFilterThatMovesPixels();
3139             }
3140         }
3141     }
3142 #endif
3143     
3144     if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
3145         calculateRects(rootLayer, region, (localPaintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect,
3146             IgnoreOverlayScrollbarSize, localPaintFlags & PaintLayerPaintingOverflowContents ? IgnoreOverflowClip : RespectOverflowClip);
3147         paintOffset = toPoint(layerBounds.location() - renderBoxLocation() + subPixelAccumulation);
3148     }
3149
3150     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
3151     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
3152     
3153     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
3154     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
3155     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
3156     // so it will be tested against as we descend through the renderers.
3157     RenderObject* paintingRootForRenderer = 0;
3158     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
3159         paintingRootForRenderer = paintingRoot;
3160
3161     if (overlapTestRequests && isSelfPaintingLayer)
3162         performOverlapTests(*overlapTestRequests, rootLayer, this);
3163
3164     // We want to paint our layer, but only if we intersect the damage rect.
3165     if (this != rootLayer || !(localPaintFlags & PaintLayerPaintingOverflowContents))
3166         shouldPaintContent &= intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
3167     
3168     if (localPaintFlags & PaintLayerPaintingCompositingBackgroundPhase) {
3169         if (shouldPaintContent && !selectionOnly) {
3170             // Begin transparency layers lazily now that we know we have to paint something.
3171             if (haveTransparency)
3172                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3173         
3174             if (useClipRect) {
3175                 // Paint our background first, before painting any child layers.
3176                 // Establish the clip used to paint our background.
3177                 clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Background painting will handle clipping to self.
3178             }
3179             
3180             // Paint the background.
3181             PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseBlockBackground, false, paintingRootForRenderer, region, 0);
3182             renderer()->paint(paintInfo, paintOffset);
3183
3184             if (useClipRect) {
3185                 // Restore the clip.
3186                 restoreClip(context, paintDirtyRect, damageRect);
3187             }
3188         }
3189
3190         // Now walk the sorted list of children with negative z-indices.
3191         paintList(negZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3192     }
3193     
3194     if (localPaintFlags & PaintLayerPaintingCompositingForegroundPhase) {
3195         // Now establish the appropriate clip and paint our child RenderObjects.
3196         if (shouldPaintContent && !clipRectToApply.isEmpty()) {
3197             // Begin transparency layers lazily now that we know we have to paint something.
3198             if (haveTransparency)
3199                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3200
3201             if (useClipRect) {
3202                 // Set up the clip used when painting our children.
3203                 clipToRect(rootLayer, context, paintDirtyRect, clipRectToApply);
3204             }
3205             
3206             PaintInfo paintInfo(context, pixelSnappedIntRect(clipRectToApply.rect()),
3207                                 selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
3208                                 forceBlackText, paintingRootForRenderer, region, 0);
3209             renderer()->paint(paintInfo, paintOffset);
3210             if (!selectionOnly) {
3211                 paintInfo.phase = PaintPhaseFloat;
3212                 renderer()->paint(paintInfo, paintOffset);
3213                 paintInfo.phase = PaintPhaseForeground;
3214                 paintInfo.overlapTestRequests = overlapTestRequests;
3215                 renderer()->paint(paintInfo, paintOffset);
3216                 paintInfo.phase = PaintPhaseChildOutlines;
3217                 renderer()->paint(paintInfo, paintOffset);
3218             }
3219
3220             if (useClipRect) {
3221                 // Now restore our clip.
3222                 restoreClip(context, paintDirtyRect, clipRectToApply);
3223             }
3224         }
3225
3226         if (shouldPaintOutline && !outlineRect.isEmpty()) {
3227             // Paint our own outline
3228             PaintInfo paintInfo(context, pixelSnappedIntRect(outlineRect.rect()), PaintPhaseSelfOutline, false, paintingRootForRenderer, region, 0);
3229             clipToRect(rootLayer, context, paintDirtyRect, outlineRect, DoNotIncludeSelfForBorderRadius);
3230             renderer()->paint(paintInfo, paintOffset);
3231             restoreClip(context, paintDirtyRect, outlineRect);
3232         }
3233     
3234         // Paint any child layers that have overflow.
3235         paintList(m_normalFlowList, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3236     
3237         // Now walk the sorted list of children with positive z-indices.
3238         paintList(posZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3239     }
3240
3241     if (isPaintingOverlayScrollbars) {
3242         clipToRect(rootLayer, context, paintDirtyRect, damageRect);
3243         paintOverflowControls(context, roundedIntPoint(paintOffset), pixelSnappedIntRect(damageRect.rect()), true);
3244         restoreClip(context, paintDirtyRect, damageRect);
3245     }
3246
3247 #if ENABLE(CSS_FILTERS)
3248     if (filterPainter.hasStartedFilterEffect()) {
3249         // Apply the correct clipping (ie. overflow: hidden).
3250         clipToRect(rootLayer, transparencyLayerContext, paintDirtyRect, damageRect);
3251         context = filterPainter.applyFilterEffect();
3252         restoreClip(transparencyLayerContext, paintDirtyRect, damageRect);
3253     }
3254 #endif
3255
3256     // Make sure that we now use the original transparency context.
3257     ASSERT(transparencyLayerContext == context);
3258
3259     if ((localPaintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && renderer()->hasMask() && !selectionOnly) {
3260         if (useClipRect)
3261             clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Mask painting will handle clipping to self.
3262         
3263         // Paint the mask.
3264         PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseMask, false, paintingRootForRenderer, region, 0);
3265         renderer()->paint(paintInfo, paintOffset);
3266         
3267         if (useClipRect) {
3268             // Restore the clip.
3269             restoreClip(context, paintDirtyRect, damageRect);
3270         }
3271     }
3272
3273     // End our transparency layer
3274     if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
3275         context->endTransparencyLayer();
3276         context->restore();
3277         m_usedTransparency = false;
3278     }
3279 }
3280
3281 void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* context,
3282                             const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3283                             RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3284                             PaintLayerFlags paintFlags)
3285 {
3286     if (!list)
3287         return;
3288
3289     if (!hasSelfPaintingLayerDescendant())
3290         return;
3291
3292 #if !ASSERT_DISABLED
3293     LayerListMutationDetector mutationChecker(this);
3294 #endif
3295
3296     for (size_t i = 0; i < list->size(); ++i) {
3297         RenderLayer* childLayer = list->at(i);
3298         if (!childLayer->isPaginated())
3299             childLayer->paintLayer(rootLayer, context, paintDirtyRect, LayoutSize(), paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3300         else
3301             paintPaginatedChildLayer(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3302     }
3303 }
3304
3305 void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3306                                            const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3307                                            RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3308                                            PaintLayerFlags paintFlags)
3309 {
3310     // We need to do multiple passes, breaking up our child layer into strips.
3311     Vector<RenderLayer*> columnLayers;
3312     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3313     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3314         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3315             columnLayers.append(curr);
3316         if (curr == ancestorLayer)
3317             break;
3318     }
3319
3320     // It is possible for paintLayer() to be called after the child layer ceases to be paginated but before
3321     // updateLayerPositions() is called and resets the isPaginated() flag, see <rdar://problem/10098679>.
3322     // If this is the case, just bail out, since the upcoming call to updateLayerPositions() will repaint the layer.
3323     if (!columnLayers.size())
3324         return;
3325
3326     paintChildLayerIntoColumns(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags, columnLayers, columnLayers.size() - 1);
3327 }
3328
3329 void RenderLayer::paintChildLayerIntoColumns(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3330                                              const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3331                                              RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3332                                              PaintLayerFlags paintFlags, const Vector<RenderLayer*>& columnLayers, size_t colIndex)
3333 {
3334     RenderBlock* columnBlock = toRenderBlock(columnLayers[colIndex]->renderer());
3335
3336     ASSERT(columnBlock && columnBlock->hasColumns());
3337     if (!columnBlock || !columnBlock->hasColumns())
3338         return;
3339     
3340     LayoutPoint layerOffset;
3341     // FIXME: It looks suspicious to call convertToLayerCoords here
3342     // as canUseConvertToLayerCoords is true for this layer.
3343     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3344     
3345     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3346
3347     ColumnInfo* colInfo = columnBlock->columnInfo();
3348     unsigned colCount = columnBlock->columnCount(colInfo);
3349     LayoutUnit currLogicalTopOffset = 0;
3350     for (unsigned i = 0; i < colCount; i++) {
3351         // For each rect, we clip to the rect, and then we adjust our coords.
3352         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3353         columnBlock->flipForWritingMode(colRect);
3354         LayoutUnit logicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - columnBlock->logicalLeftOffsetForContent();
3355         LayoutSize offset;
3356         if (isHorizontal) {
3357             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3358                 offset = LayoutSize(logicalLeftOffset, currLogicalTopOffset);
3359             else
3360                 offset = LayoutSize(0, colRect.y() + currLogicalTopOffset - columnBlock->borderTop() - columnBlock->paddingTop());
3361         } else {
3362             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3363                 offset = LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3364             else
3365                 offset = LayoutSize(colRect.x() + currLogicalTopOffset - columnBlock->borderLeft() - columnBlock->paddingLeft(), 0);
3366         }
3367
3368         colRect.moveBy(layerOffset);
3369
3370         LayoutRect localDirtyRect(paintDirtyRect);
3371         localDirtyRect.intersect(colRect);
3372         
3373         if (!localDirtyRect.isEmpty()) {
3374             GraphicsContextStateSaver stateSaver(*context);
3375             
3376             // Each strip pushes a clip, since column boxes are specified as being
3377             // like overflow:hidden.
3378             context->clip(pixelSnappedIntRect(colRect));
3379
3380             if (!colIndex) {
3381                 // Apply a translation transform to change where the layer paints.
3382                 TransformationMatrix oldTransform;
3383                 bool oldHasTransform = childLayer->transform();
3384                 if (oldHasTransform)
3385                     oldTransform = *childLayer->transform();
3386                 TransformationMatrix newTransform(oldTransform);
3387                 newTransform.translateRight(roundToInt(offset.width()), roundToInt(offset.height()));
3388                 
3389                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3390                 childLayer->paintLayer(rootLayer, context, localDirtyRect, LayoutSize(), paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3391                 if (oldHasTransform)
3392                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3393                 else
3394                     childLayer->m_transform.clear();
3395             } else {
3396                 // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
3397                 // This involves subtracting out the position of the layer in our current coordinate space.
3398                 LayoutPoint childOffset;
3399                 columnLayers[colIndex - 1]->convertToLayerCoords(rootLayer, childOffset);
3400                 TransformationMatrix transform;
3401                 transform.translateRight(roundToInt(childOffset.x() + offset.width()), roundToInt(childOffset.y() + offset.height()));
3402                 
3403                 // Apply the transform.
3404                 context->concatCTM(transform.toAffineTransform());
3405
3406                 // Now do a paint with the root layer shifted to be the next multicol block.
3407                 paintChildLayerIntoColumns(childLayer, columnLayers[colIndex - 1], context, transform.inverse().mapRect(localDirtyRect), paintBehavior, 
3408                                            paintingRoot, region, overlapTestRequests, paintFlags, 
3409                                            columnLayers, colIndex - 1);
3410             }
3411         }
3412
3413         // Move to the next position.
3414         LayoutUnit blockDelta = isHorizontal ? colRect.height() : colRect.width();
3415         if (columnBlock->style()->isFlippedBlocksWritingMode())
3416             currLogicalTopOffset += blockDelta;
3417         else
3418             currLogicalTopOffset -= blockDelta;
3419     }
3420 }
3421
3422 static inline LayoutRect frameVisibleRect(RenderObject* renderer)
3423 {
3424     FrameView* frameView = renderer->document()->view();
3425     if (!frameView)
3426         return LayoutRect();
3427
3428     return frameView->visibleContentRect();
3429 }
3430
3431 bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
3432 {
3433     return hitTest(request, result.hitTestPoint(), result);
3434 }
3435
3436 bool RenderLayer::hitTest(const HitTestRequest& request, const HitTestPoint& hitTestPoint, HitTestResult& result)
3437 {
3438     renderer()->document()->updateLayout();
3439     
3440     LayoutRect hitTestArea = renderer()->isRenderFlowThread() ? toRenderFlowThread(renderer())->borderBoxRect() : renderer()->view()->documentRect();
3441     if (!request.ignoreClipping())
3442         hitTestArea.intersect(frameVisibleRect(renderer()));
3443
3444     RenderLayer* insideLayer = hitTestLayer(this, 0, request, result, hitTestArea, hitTestPoint, false);
3445     if (!insideLayer) {
3446         // We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down, 
3447         // return ourselves. We do this so mouse events continue getting delivered after a drag has 
3448         // exited the WebView, and so hit testing over a scrollbar hits the content document.
3449         if ((request.active() || request.release()) && isRootLayer()) {
3450             renderer()->updateHitTestResult(result, toRenderView(renderer())->flipForWritingMode(result.point()));
3451             insideLayer = this;
3452         }
3453     }
3454
3455     // Now determine if the result is inside an anchor - if the urlElement isn't already set.
3456     Node* node = result.innerNode();
3457     if (node && !result.URLElement())
3458         result.setURLElement(static_cast<Element*>(node->enclosingLinkEventParentOrSelf()));
3459
3460     // Next set up the correct :hover/:active state along the new chain.
3461     updateHoverActiveState(request, result);
3462     
3463     // Now return whether we were inside this layer (this will always be true for the root
3464     // layer).
3465     return insideLayer;
3466 }
3467
3468 Node* RenderLayer::enclosingElement() const
3469 {
3470     for (RenderObject* r = renderer(); r; r = r->parent()) {
3471         if (Node* e = r->node())
3472             return e;
3473     }
3474     ASSERT_NOT_REACHED();
3475     return 0;
3476 }
3477
3478 // Compute the z-offset of the point in the transformState.
3479 // This is effectively projecting a ray normal to the plane of ancestor, finding where that
3480 // ray intersects target, and computing the z delta between those two points.
3481 static double computeZOffset(const HitTestingTransformState& transformState)
3482 {
3483     // We got an affine transform, so no z-offset
3484     if (transformState.m_accumulatedTransform.isAffine())
3485         return 0;
3486
3487     // Flatten the point into the target plane
3488     FloatPoint targetPoint = transformState.mappedPoint();
3489     
3490     // Now map the point back through the transform, which computes Z.
3491     FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
3492     return backmappedPoint.z();
3493 }
3494
3495 PassRefPtr<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
3496                                         const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3497                                         const HitTestingTransformState* containerTransformState) const
3498 {
3499     RefPtr<HitTestingTransformState> transformState;
3500     LayoutPoint offset;
3501     if (containerTransformState) {
3502         // If we're already computing transform state, then it's relative to the container (which we know is non-null).
3503         transformState = HitTestingTransformState::create(*containerTransformState);
3504         convertToLayerCoords(containerLayer, offset);
3505     } else {
3506         // If this is the first time we need to make transform state, then base it off of hitTestPoint,
3507         // which is relative to rootLayer.
3508         transformState = HitTestingTransformState::create(hitTestPoint.transformedPoint(), hitTestPoint.transformedRect(), FloatQuad(hitTestRect));
3509         convertToLayerCoords(rootLayer, offset);
3510     }
3511     
3512     RenderObject* containerRenderer = containerLayer ? containerLayer->renderer() : 0;
3513     if (renderer()->shouldUseTransformFromContainer(containerRenderer)) {
3514         TransformationMatrix containerTransform;
3515         renderer()->getTransformFromContainer(containerRenderer, toLayoutSize(offset), containerTransform);
3516         transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
3517     } else {
3518         transformState->translate(offset.x(), offset.y(), HitTestingTransformState::AccumulateTransform);
3519     }
3520     
3521     return transformState;
3522 }
3523
3524
3525 static bool isHitCandidate(const RenderLayer* hitLayer, bool canDepthSort, double* zOffset, const HitTestingTransformState* transformState)
3526 {
3527     if (!hitLayer)
3528         return false;
3529
3530     // The hit layer is depth-sorting with other layers, so just say that it was hit.
3531     if (canDepthSort)
3532         return true;
3533     
3534     // We need to look at z-depth to decide if this layer was hit.
3535     if (zOffset) {
3536         ASSERT(transformState);
3537         // This is actually computing our z, but that's OK because the hitLayer is coplanar with us.
3538         double childZOffset = computeZOffset(*transformState);
3539         if (childZOffset > *zOffset) {
3540             *zOffset = childZOffset;
3541             return true;
3542         }
3543         return false;
3544     }
3545
3546     return true;
3547 }
3548
3549 // hitTestPoint and hitTestRect are relative to rootLayer.
3550 // A 'flattening' layer is one preserves3D() == false.
3551 // transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
3552 // transformState.m_lastPlanarPoint is the hitTestPoint in the plane of the containing flattening layer.
3553 // transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
3554 // 
3555 // If zOffset is non-null (which indicates that the caller wants z offset information), 
3556 //  *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
3557 RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
3558                                        const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, bool appliedTransform,
3559                                        const HitTestingTransformState* transformState, double* zOffset)
3560 {
3561     // The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
3562
3563     bool useTemporaryClipRects = renderer()->view()->frameView()->containsScrollableAreaWithOverlayScrollbars();
3564
3565     // Apply a transform if we have one.
3566     if (transform() && !appliedTransform) {
3567         // Make sure the parent's clip rects have been calculated.
3568         if (parent()) {
3569             ClipRect clipRect = backgroundClipRect(rootLayer, hitTestPoint.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, IncludeOverlayScrollbarSize);
3570             // Go ahead and test the enclosing clip now.
3571             if (!clipRect.intersects(hitTestPoint))
3572                 return 0;
3573         }
3574
3575         // Create a transform state to accumulate this transform.
3576         RefPtr<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3577
3578         // If the transform can't be inverted, then don't hit test this layer at all.
3579         if (!newTransformState->m_accumulatedTransform.isInvertible())
3580             return 0;
3581
3582         // Compute the point and the hit test rect in the coords of this layer by using the values
3583         // from the transformState, which store the point and quad in the coords of the last flattened
3584         // layer, and the accumulated transform which lets up map through preserve-3d layers.
3585         //
3586         // We can't just map hitTestPoint and hitTestRect because they may have been flattened (losing z)
3587         // by our container.
3588         FloatPoint localPoint = newTransformState->mappedPoint();
3589         FloatQuad localPointQuad = newTransformState->mappedQuad();
3590         LayoutRect localHitTestRect = newTransformState->boundsOfMappedArea();
3591         HitTestPoint newHitTestPoint;
3592         if (hitTestPoint.isRectBasedTest())
3593             newHitTestPoint = HitTestPoint(localPoint, localPointQuad);
3594         else
3595             newHitTestPoint = HitTestPoint(localPoint);
3596
3597         // Now do a hit test with the root layer shifted to be us.
3598         return hitTestLayer(this, containerLayer, request, result, localHitTestRect, newHitTestPoint, true, newTransformState.get(), zOffset);
3599     }
3600
3601     // Ensure our lists and 3d status are up-to-date.
3602     updateCompositingAndLayerListsIfNeeded();
3603     update3DTransformedDescendantStatus();
3604
3605     RefPtr<HitTestingTransformState> localTransformState;
3606     if (appliedTransform) {
3607         // We computed the correct state in the caller (above code), so just reference it.
3608         ASSERT(transformState);
3609         localTransformState = const_cast<HitTestingTransformState*>(transformState);
3610     } else if (transformState || m_has3DTransformedDescendant || preserves3D()) {
3611         // We need transform state for the first time, or to offset the container state, so create it here.
3612         localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3613     }
3614
3615     // Check for hit test on backface if backface-visibility is 'hidden'
3616     if (localTransformState && renderer()->style()->backfaceVisibility() == BackfaceVisibilityHidden) {
3617         TransformationMatrix invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
3618         // If the z-vector of the matrix is negative, the back is facing towards the viewer.
3619         if (invertedMatrix.m33() < 0)
3620             return 0;
3621     }
3622
3623     RefPtr<HitTestingTransformState> unflattenedTransformState = localTransformState;
3624     if (localTransformState && !preserves3D()) {
3625         // Keep a copy of the pre-flattening state, for computing z-offsets for the container
3626         unflattenedTransformState = HitTestingTransformState::create(*localTransformState);
3627         // This layer is flattening, so flatten the state passed to descendants.
3628         localTransformState->flatten();
3629     }
3630     
3631     // Calculate the clip rects we should use.
3632     LayoutRect layerBounds;
3633     ClipRect bgRect;
3634     ClipRect fgRect;
3635     ClipRect outlineRect;
3636     calculateRects(rootLayer, hitTestPoint.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, hitTestRect, layerBounds, bgRect, fgRect, outlineRect, IncludeOverlayScrollbarSize);
3637     
3638     // The following are used for keeping track of the z-depth of the hit point of 3d-transformed
3639     // descendants.
3640     double localZOffset = -numeric_limits<double>::infinity();
3641     double* zOffsetForDescendantsPtr = 0;
3642     double* zOffsetForContentsPtr = 0;
3643     
3644     bool depthSortDescendants = false;
3645     if (preserves3D()) {
3646         depthSortDescendants = true;
3647         // Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
3648         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3649         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3650     } else if (m_has3DTransformedDescendant) {
3651         // Flattening layer with 3d children; use a local zOffset pointer to depth-test children and foreground.
3652         depthSortDescendants = true;
3653         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3654         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3655     } else if (zOffset) {
3656         zOffsetForDescendantsPtr = 0;
3657         // Container needs us to give back a z offset for the hit layer.
3658         zOffsetForContentsPtr = zOffset;
3659     }
3660
3661     // This variable tracks which layer the mouse ends up being inside.
3662     RenderLayer* candidateLayer = 0;
3663
3664     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
3665     RenderLayer* hitLayer = hitTestList(posZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3666                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3667     if (hitLayer) {
3668         if (!depthSortDescendants)
3669             return hitLayer;
3670         candidateLayer = hitLayer;
3671     }
3672
3673     // Now check our overflow objects.
3674     hitLayer = hitTestList(m_normalFlowList, rootLayer, request, result, hitTestRect, hitTestPoint,
3675                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3676     if (hitLayer) {
3677         if (!depthSortDescendants)
3678             return hitLayer;
3679         candidateLayer = hitLayer;
3680     }
3681
3682     // Next we want to see if the mouse pos is inside the child RenderObjects of the layer.
3683     if (fgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3684         // Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
3685         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3686         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestDescendants) &&
3687             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3688             if (result.isRectBasedTest())
3689                 result.append(tempResult);
3690             else
3691                 result = tempResult;
3692             if (!depthSortDescendants)
3693                 return this;
3694             // Foreground can depth-sort with descendant layers, so keep this as a candidate.
3695             candidateLayer = this;
3696         } else if (result.isRectBasedTest())
3697             result.append(tempResult);
3698     }
3699
3700     // Now check our negative z-index children.
3701     hitLayer = hitTestList(negZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3702                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3703     if (hitLayer) {
3704         if (!depthSortDescendants)
3705             return hitLayer;
3706         candidateLayer = hitLayer;
3707     }
3708
3709     // If we found a layer, return. Child layers, and foreground always render in front of background.
3710     if (candidateLayer)
3711         return candidateLayer;
3712
3713     if (bgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3714         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3715         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestSelf) &&
3716             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3717             if (result.isRectBasedTest())
3718                 result.append(tempResult);
3719             else
3720                 result = tempResult;
3721             return this;
3722         } else if (result.isRectBasedTest())
3723             result.append(tempResult);
3724     }
3725
3726     return 0;
3727 }
3728
3729 bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const LayoutRect& layerBounds, const HitTestPoint& hitTestPoint, HitTestFilter hitTestFilter) const
3730 {
3731     if (!renderer()->hitTest(request, result, hitTestPoint,
3732                             toLayoutPoint(layerBounds.location() - renderBoxLocation()),
3733                             hitTestFilter)) {
3734         // It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
3735         // a rect-based test.
3736         ASSERT(!result.innerNode() || (result.isRectBasedTest() && result.rectBasedTestResult().size()));
3737         return false;
3738     }
3739
3740     // For positioned generated content, we might still not have a
3741     // node by the time we get to the layer level, since none of
3742     // the content in the layer has an element. So just walk up
3743     // the tree.
3744     if (!result.innerNode() || !result.innerNonSharedNode()) {
3745         Node* e = enclosingElement();
3746         if (!result.innerNode())
3747             result.setInnerNode(e);
3748         if (!result.innerNonSharedNode())
3749             result.setInnerNonSharedNode(e);
3750     }
3751         
3752     return true;
3753 }
3754
3755 RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
3756                                       const HitTestRequest& request, HitTestResult& result,
3757                                       const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3758                                       const HitTestingTransformState* transformState, 
3759                                       double* zOffsetForDescendants, double* zOffset,
3760                                       const HitTestingTransformState* unflattenedTransformState,
3761                                       bool depthSortDescendants)
3762 {
3763     if (!list)
3764         return 0;
3765     
3766     RenderLayer* resultLayer = 0;
3767     for (int i = list->size() - 1; i >= 0; --i) {
3768         RenderLayer* childLayer = list->at(i);
3769         RenderLayer* hitLayer = 0;
3770         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3771         if (childLayer->isPaginated())
3772             hitLayer = hitTestPaginatedChildLayer(childLayer, rootLayer, request, tempResult, hitTestRect, hitTestPoint, transformState, zOffsetForDescendants);
3773         else
3774             hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestPoint, false, transformState, zOffsetForDescendants);
3775
3776         // If it a rect-based test, we can safely append the temporary result since it might had hit
3777         // nodes but not necesserily had hitLayer set.
3778         if (result.isRectBasedTest())
3779             result.append(tempResult);
3780
3781         if (isHitCandidate(hitLayer, depthSortDescendants, zOffset, unflattenedTransformState)) {
3782             resultLayer = hitLayer;
3783             if (!result.isRectBasedTest())
3784                 result = tempResult;
3785             if (!depthSortDescendants)
3786                 break;
3787         }
3788     }
3789
3790     return resultLayer;
3791 }
3792
3793 RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3794                                                      const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset)
3795 {
3796     Vector<RenderLayer*> columnLayers;
3797     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3798     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3799         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3800             columnLayers.append(curr);
3801         if (curr == ancestorLayer)
3802             break;
3803     }
3804
3805     ASSERT(columnLayers.size());
3806     return hitTestChildLayerColumns(childLayer, rootLayer, request, result, hitTestRect, hitTestPoint, transformState, zOffset,
3807                                     columnLayers, columnLayers.size() - 1);
3808 }
3809
3810 RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3811                                                    const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset,
3812                                                    const Vector<RenderLayer*>& columnLayers, size_t columnIndex)
3813 {
3814     RenderBlock* columnBlock = toRenderBlock(columnLayers[columnIndex]->renderer());
3815
3816     ASSERT(columnBlock && columnBlock->hasColumns());
3817     if (!columnBlock || !columnBlock->hasColumns())
3818         return 0;
3819
3820     LayoutPoint layerOffset;
3821     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3822
3823     ColumnInfo* colInfo = columnBlock->columnInfo();
3824     int colCount = columnBlock->columnCount(colInfo);
3825
3826     // We have to go backwards from the last column to the first.
3827     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3828     LayoutUnit logicalLeft = columnBlock->logicalLeftOffsetForContent();
3829     LayoutUnit currLogicalTopOffset = 0;
3830     int i;
3831     for (i = 0; i < colCount; i++) {
3832         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3833         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3834         if (columnBlock->style()->isFlippedBlocksWritingMode())
3835             currLogicalTopOffset += blockDelta;
3836         else
3837             currLogicalTopOffset -= blockDelta;
3838     }
3839     for (i = colCount - 1; i >= 0; i--) {
3840         // For each rect, we clip to the rect, and then we adjust our coords.
3841         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3842         columnBlock->flipForWritingMode(colRect);
3843         LayoutUnit currLogicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - logicalLeft;
3844         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3845         if (columnBlock->style()->isFlippedBlocksWritingMode())
3846             currLogicalTopOffset -= blockDelta;
3847         else
3848             currLogicalTopOffset += blockDelta;
3849
3850         LayoutSize offset;
3851         if (isHorizontal) {
3852             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3853                 offset = LayoutSize(currLogicalLeftOffset, currLogicalTopOffset);
3854             else