CSS Masking and CSS Filters applied in wrong order
[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 & HasSeenFixedPositionedAncestor) || renderer()->style()->position() == FixedPosition) {
523         // FIXME: Is it worth passing the offsetFromRoot around like in updateLayerPositions?
524         computeRepaintRects();
525         flags |= HasSeenFixedPositionedAncestor;
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()->isRelPositioned() && positionedParent->renderer()->isRenderInline()) {
851             LayoutSize offset = toRenderInline(positionedParent->renderer())->relativePositionedInlineOffset(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()->isRelPositioned()) {
872         m_relativeOffset = renderer()->relativePositionOffset();
873         localPoint.move(m_relativeOffset);
874     } else {
875         m_relativeOffset = 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->isOutOfFlowPositioned() || layerRenderer->isRelPositioned() || 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 static inline int adjustedScrollDelta(int beginningDelta) {
1556     // This implemention matches Firefox's.
1557     // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
1558     const int speedReducer = 12;
1559
1560     int adjustedDelta = beginningDelta / speedReducer;
1561     if (adjustedDelta > 1)
1562         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
1563     else if (adjustedDelta < -1)
1564         adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
1565
1566     return adjustedDelta;
1567 }
1568
1569 static inline IntSize adjustedScrollDelta(const IntSize& delta)
1570 {
1571     return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
1572 }
1573
1574 void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
1575 {
1576     Frame* frame = renderer()->frame();
1577     if (!frame)
1578         return;
1579     
1580     IntPoint currentMousePosition = frame->eventHandler()->currentMousePosition();
1581     
1582     // 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
1583     static IntPoint previousMousePosition;
1584     if (currentMousePosition.x() < 0 || currentMousePosition.y() < 0)
1585         currentMousePosition = previousMousePosition;
1586     else
1587         previousMousePosition = currentMousePosition;
1588
1589     IntSize delta = currentMousePosition - sourcePoint;
1590
1591     if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
1592         delta.setWidth(0);
1593     if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
1594         delta.setHeight(0);
1595
1596     scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
1597 }
1598
1599 void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
1600 {
1601     if (delta.isZero())
1602         return;
1603
1604     bool restrictedByLineClamp = false;
1605     if (renderer()->parent())
1606         restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
1607
1608     if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
1609         IntSize newScrollOffset = scrollOffset() + delta;
1610         scrollToOffset(newScrollOffset, clamp);
1611
1612         // If this layer can't do the scroll we ask the next layer up that can scroll to try
1613         IntSize remainingScrollOffset = newScrollOffset - scrollOffset();
1614         if (!remainingScrollOffset.isZero() && renderer()->parent()) {
1615             if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
1616                 scrollableLayer->scrollByRecursively(remainingScrollOffset);
1617
1618             Frame* frame = renderer()->frame();
1619             if (frame)
1620                 frame->eventHandler()->updateAutoscrollRenderer();
1621         }
1622     } else if (renderer()->view()->frameView()) {
1623         // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
1624         // have an overflow clip. Which means that it is a document node that can be scrolled.
1625         renderer()->view()->frameView()->scrollBy(delta);
1626         // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement? 
1627         // https://bugs.webkit.org/show_bug.cgi?id=28237
1628     }
1629 }
1630
1631 IntSize RenderLayer::clampScrollOffset(const IntSize& scrollOffset) const
1632 {
1633     RenderBox* box = renderBox();
1634     ASSERT(box);
1635
1636     int maxX = scrollWidth() - box->pixelSnappedClientWidth();
1637     int maxY = scrollHeight() - box->pixelSnappedClientHeight();
1638
1639     int x = min(max(scrollOffset.width(), 0), maxX);
1640     int y = min(max(scrollOffset.height(), 0), maxY);
1641     return IntSize(x, y);
1642 }
1643
1644 void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
1645 {
1646     IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
1647     if (newScrollOffset != this->scrollOffset())
1648         scrollToOffsetWithoutAnimation(toPoint(newScrollOffset));
1649 }
1650
1651 void RenderLayer::scrollTo(int x, int y)
1652 {
1653     RenderBox* box = renderBox();
1654     if (!box)
1655         return;
1656
1657     if (box->style()->overflowX() != OMARQUEE) {
1658         // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
1659         if (m_scrollDimensionsDirty)
1660             computeScrollDimensions();
1661     }
1662     
1663     // FIXME: Eventually, we will want to perform a blit.  For now never
1664     // blit, since the check for blitting is going to be very
1665     // complicated (since it will involve testing whether our layer
1666     // is either occluded by another layer or clipped by an enclosing
1667     // layer or contains fixed backgrounds, etc.).
1668     IntSize newScrollOffset = IntSize(x - scrollOrigin().x(), y - scrollOrigin().y());
1669     if (m_scrollOffset == newScrollOffset)
1670         return;
1671     m_scrollOffset = newScrollOffset;
1672
1673     // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
1674     // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
1675     updateLayerPositionsAfterScroll();
1676
1677     RenderView* view = renderer()->view();
1678     
1679     // We should have a RenderView if we're trying to scroll.
1680     ASSERT(view);
1681     if (view) {
1682 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
1683         // Update dashboard regions, scrolling may change the clip of a
1684         // particular region.
1685         view->frameView()->updateDashboardRegions();
1686 #endif
1687
1688         view->updateWidgetPositions();
1689     }
1690
1691     updateCompositingLayersAfterScroll();
1692
1693     RenderBoxModelObject* repaintContainer = renderer()->containerForRepaint();
1694     Frame* frame = renderer()->frame();
1695     if (frame) {
1696         // The caret rect needs to be invalidated after scrolling
1697         frame->selection()->setCaretRectNeedsUpdate();
1698
1699         FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_repaintRect);
1700         if (repaintContainer)
1701             quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
1702         frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
1703     }
1704
1705     // Just schedule a full repaint of our object.
1706     if (view)
1707         renderer()->repaintUsingContainer(repaintContainer, m_repaintRect);
1708
1709     // Schedule the scroll DOM event.
1710     if (renderer()->node())
1711         renderer()->node()->document()->eventQueue()->enqueueOrDispatchScrollEvent(renderer()->node(), DocumentEventQueue::ScrollEventElementTarget);
1712 }
1713
1714 void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
1715 {
1716     RenderLayer* parentLayer = 0;
1717     LayoutRect newRect = rect;
1718
1719     // We may end up propagating a scroll event. It is important that we suspend events until 
1720     // the end of the function since they could delete the layer or the layer's renderer().
1721     FrameView* frameView = renderer()->document()->view();
1722     if (frameView)
1723         frameView->pauseScheduledEvents();
1724
1725     bool restrictedByLineClamp = false;
1726     if (renderer()->parent()) {
1727         parentLayer = renderer()->parent()->enclosingLayer();
1728         restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
1729     }
1730
1731     if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
1732         // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
1733         // This will prevent us from revealing text hidden by the slider in Safari RSS.
1734         RenderBox* box = renderBox();
1735         ASSERT(box);
1736         FloatPoint absPos = box->localToAbsolute();
1737         absPos.move(box->borderLeft(), box->borderTop());
1738
1739         LayoutRect layerBounds = LayoutRect(absPos.x() + scrollXOffset(), absPos.y() + scrollYOffset(), box->clientWidth(), box->clientHeight());
1740         LayoutRect exposeRect = LayoutRect(rect.x() + scrollXOffset(), rect.y() + scrollYOffset(), rect.width(), rect.height());
1741         LayoutRect r = getRectToExpose(layerBounds, exposeRect, alignX, alignY);
1742         
1743         int roundedAdjustedX = roundToInt(r.x() - absPos.x());
1744         int roundedAdjustedY = roundToInt(r.y() - absPos.y());
1745         IntSize clampedScrollOffset = clampScrollOffset(IntSize(roundedAdjustedX, roundedAdjustedY));
1746         if (clampedScrollOffset != scrollOffset()) {
1747             IntSize oldScrollOffset = scrollOffset();
1748             scrollToOffset(clampedScrollOffset);
1749             IntSize scrollOffsetDifference = scrollOffset() - oldScrollOffset;
1750             newRect.move(-scrollOffsetDifference);
1751         }
1752     } else if (!parentLayer && renderer()->isBox() && renderBox()->canBeProgramaticallyScrolled()) {
1753         if (frameView) {
1754             Element* ownerElement = 0;
1755             if (renderer()->document())
1756                 ownerElement = renderer()->document()->ownerElement();
1757
1758             if (ownerElement && ownerElement->renderer()) {
1759                 HTMLFrameElement* frameElement = 0;
1760
1761                 if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
1762                     frameElement = static_cast<HTMLFrameElement*>(ownerElement);
1763
1764                 if (frameElement && frameElement->scrollingMode() != ScrollbarAlwaysOff) {
1765                     LayoutRect viewRect = frameView->visibleContentRect();
1766                     LayoutRect exposeRect = getRectToExpose(viewRect, rect, alignX, alignY);
1767
1768                     int xOffset = roundToInt(exposeRect.x());
1769                     int yOffset = roundToInt(exposeRect.y());
1770                     // Adjust offsets if they're outside of the allowable range.
1771                     xOffset = max(0, min(frameView->contentsWidth(), xOffset));
1772                     yOffset = max(0, min(frameView->contentsHeight(), yOffset));
1773
1774                     frameView->setScrollPosition(IntPoint(xOffset, yOffset));
1775                     if (frameView->safeToPropagateScrollToParent()) {
1776                         parentLayer = ownerElement->renderer()->enclosingLayer();
1777                         newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
1778                         newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
1779                     } else
1780                         parentLayer = 0;
1781                 }
1782             } else {
1783                 LayoutRect viewRect = frameView->visibleContentRect();
1784                 LayoutRect r = getRectToExpose(viewRect, rect, alignX, alignY);
1785                 
1786                 frameView->setScrollPosition(roundedIntPoint(r.location()));
1787
1788                 // This is the outermost view of a web page, so after scrolling this view we
1789                 // scroll its container by calling Page::scrollRectIntoView.
1790                 // This only has an effect on the Mac platform in applications
1791                 // that put web views into scrolling containers, such as Mac OS X Mail.
1792                 // The canAutoscroll function in EventHandler also knows about this.
1793                 if (Frame* frame = frameView->frame()) {
1794                     if (Page* page = frame->page())
1795                         page->chrome()->scrollRectIntoView(pixelSnappedIntRect(rect));
1796                 }
1797             }
1798         }
1799     }
1800     
1801     if (parentLayer)
1802         parentLayer->scrollRectToVisible(newRect, alignX, alignY);
1803
1804     if (frameView)
1805         frameView->resumeScheduledEvents();
1806 }
1807
1808 void RenderLayer::updateCompositingLayersAfterScroll()
1809 {
1810 #if USE(ACCELERATED_COMPOSITING)
1811     if (compositor()->inCompositingMode()) {
1812         // Our stacking context is guaranteed to contain all of our descendants that may need
1813         // repositioning, so update compositing layers from there.
1814         if (RenderLayer* compositingAncestor = stackingContext()->enclosingCompositingLayer()) {
1815             if (compositor()->compositingConsultsOverlap())
1816                 compositor()->updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
1817             else {
1818                 bool isUpdateRoot = true;
1819                 compositingAncestor->backing()->updateAfterLayout(RenderLayerBacking::AllDescendants, isUpdateRoot);
1820             }
1821         }
1822     }
1823 #endif
1824 }
1825
1826 LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
1827 {
1828     // Determine the appropriate X behavior.
1829     ScrollBehavior scrollX;
1830     LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
1831     LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
1832     if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
1833         // If the rectangle is fully visible, use the specified visible behavior.
1834         // If the rectangle is partially visible, but over a certain threshold,
1835         // then treat it as fully visible to avoid unnecessary horizontal scrolling
1836         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
1837     else if (intersectWidth == visibleRect.width()) {
1838         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
1839         scrollX = ScrollAlignment::getVisibleBehavior(alignX);
1840         if (scrollX == alignCenter)
1841             scrollX = noScroll;
1842     } else if (intersectWidth > 0)
1843         // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
1844         scrollX = ScrollAlignment::getPartialBehavior(alignX);
1845     else
1846         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
1847     // If we're trying to align to the closest edge, and the exposeRect is further right
1848     // than the visibleRect, and not bigger than the visible area, then align with the right.
1849     if (scrollX == alignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
1850         scrollX = alignRight;
1851
1852     // Given the X behavior, compute the X coordinate.
1853     LayoutUnit x;
1854     if (scrollX == noScroll) 
1855         x = visibleRect.x();
1856     else if (scrollX == alignRight)
1857         x = exposeRect.maxX() - visibleRect.width();
1858     else if (scrollX == alignCenter)
1859         x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
1860     else
1861         x = exposeRect.x();
1862
1863     // Determine the appropriate Y behavior.
1864     ScrollBehavior scrollY;
1865     LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
1866     LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
1867     if (intersectHeight == exposeRect.height())
1868         // If the rectangle is fully visible, use the specified visible behavior.
1869         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
1870     else if (intersectHeight == visibleRect.height()) {
1871         // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
1872         scrollY = ScrollAlignment::getVisibleBehavior(alignY);
1873         if (scrollY == alignCenter)
1874             scrollY = noScroll;
1875     } else if (intersectHeight > 0)
1876         // If the rectangle is partially visible, use the specified partial behavior
1877         scrollY = ScrollAlignment::getPartialBehavior(alignY);
1878     else
1879         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
1880     // If we're trying to align to the closest edge, and the exposeRect is further down
1881     // than the visibleRect, and not bigger than the visible area, then align with the bottom.
1882     if (scrollY == alignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
1883         scrollY = alignBottom;
1884
1885     // Given the Y behavior, compute the Y coordinate.
1886     LayoutUnit y;
1887     if (scrollY == noScroll) 
1888         y = visibleRect.y();
1889     else if (scrollY == alignBottom)
1890         y = exposeRect.maxY() - visibleRect.height();
1891     else if (scrollY == alignCenter)
1892         y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
1893     else
1894         y = exposeRect.y();
1895
1896     return LayoutRect(LayoutPoint(x, y), visibleRect.size());
1897 }
1898
1899 void RenderLayer::autoscroll()
1900 {
1901     Frame* frame = renderer()->frame();
1902     if (!frame)
1903         return;
1904
1905     FrameView* frameView = frame->view();
1906     if (!frameView)
1907         return;
1908
1909 #if ENABLE(DRAG_SUPPORT)
1910     frame->eventHandler()->updateSelectionForMouseDrag();
1911 #endif
1912
1913     IntPoint currentDocumentPosition = frameView->windowToContents(frame->eventHandler()->currentMousePosition());
1914     scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
1915 }
1916
1917 void RenderLayer::resize(const PlatformMouseEvent& evt, const LayoutSize& oldOffset)
1918 {
1919     // FIXME: This should be possible on generated content but is not right now.
1920     if (!inResizeMode() || !renderer()->hasOverflowClip() || !renderer()->node())
1921         return;
1922
1923     ASSERT(renderer()->node()->isElementNode());
1924     Element* element = static_cast<Element*>(renderer()->node());
1925     RenderBox* renderer = toRenderBox(element->renderer());
1926
1927     EResize resize = renderer->style()->resize();
1928     if (resize == RESIZE_NONE)
1929         return;
1930
1931     Document* document = element->document();
1932     if (!document->frame()->eventHandler()->mousePressed())
1933         return;
1934
1935     float zoomFactor = renderer->style()->effectiveZoom();
1936
1937     LayoutSize newOffset = offsetFromResizeCorner(document->view()->windowToContents(evt.position()));
1938     newOffset.setWidth(newOffset.width() / zoomFactor);
1939     newOffset.setHeight(newOffset.height() / zoomFactor);
1940     
1941     LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
1942     LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
1943     element->setMinimumSizeForResizing(minimumSize);
1944     
1945     LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
1946     if (renderer->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
1947         newOffset.setWidth(-newOffset.width());
1948         adjustedOldOffset.setWidth(-adjustedOldOffset.width());
1949     }
1950     
1951     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
1952
1953     ASSERT(element->isStyledElement());
1954     StyledElement* styledElement = static_cast<StyledElement*>(element);
1955     bool isBoxSizingBorder = renderer->style()->boxSizing() == BORDER_BOX;
1956
1957     if (resize != RESIZE_VERTICAL && difference.width()) {
1958         if (element->isFormControlElement()) {
1959             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
1960             styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, String::number(renderer->marginLeft() / zoomFactor) + "px", false);
1961             styledElement->setInlineStyleProperty(CSSPropertyMarginRight, String::number(renderer->marginRight() / zoomFactor) + "px", false);
1962         }
1963         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? ZERO_LAYOUT_UNIT : renderer->borderAndPaddingWidth());
1964         baseWidth = baseWidth / zoomFactor;
1965         styledElement->setInlineStyleProperty(CSSPropertyWidth, String::number(roundToInt(baseWidth + difference.width())) + "px", false);
1966     }
1967
1968     if (resize != RESIZE_HORIZONTAL && difference.height()) {
1969         if (element->isFormControlElement()) {
1970             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
1971             styledElement->setInlineStyleProperty(CSSPropertyMarginTop, String::number(renderer->marginTop() / zoomFactor) + "px", false);
1972             styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, String::number(renderer->marginBottom() / zoomFactor) + "px", false);
1973         }
1974         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? ZERO_LAYOUT_UNIT : renderer->borderAndPaddingHeight());
1975         baseHeight = baseHeight / zoomFactor;
1976         styledElement->setInlineStyleProperty(CSSPropertyHeight, String::number(roundToInt(baseHeight + difference.height())) + "px", false);
1977     }
1978
1979     document->updateLayout();
1980
1981     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
1982 }
1983
1984 int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
1985 {
1986     Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_hBar : m_vBar).get();
1987     return scrollbar ? (scrollbar->totalSize() - scrollbar->visibleSize()) : 0;
1988 }
1989
1990 void RenderLayer::setScrollOffset(const IntPoint& offset)
1991 {
1992     scrollTo(offset.x(), offset.y());
1993 }
1994
1995 int RenderLayer::scrollPosition(Scrollbar* scrollbar) const
1996 {
1997     if (scrollbar->orientation() == HorizontalScrollbar)
1998         return scrollXOffset();
1999     if (scrollbar->orientation() == VerticalScrollbar)
2000         return scrollYOffset();
2001     return 0;
2002 }
2003
2004 IntPoint RenderLayer::scrollPosition() const
2005 {
2006     return scrollOrigin() + m_scrollOffset;
2007 }
2008
2009 IntPoint RenderLayer::minimumScrollPosition() const
2010 {
2011     return scrollOrigin();
2012 }
2013
2014 IntPoint RenderLayer::maximumScrollPosition() const
2015 {
2016     // FIXME: m_scrollSize may not be up-to-date if m_scrollDimensionsDirty is true.
2017     return scrollOrigin() + roundedIntSize(m_scrollSize) - visibleContentRect(true).size();
2018 }
2019
2020 IntRect RenderLayer::visibleContentRect(bool includeScrollbars) const
2021 {
2022     int verticalScrollbarWidth = 0;
2023     int horizontalScrollbarHeight = 0;
2024     if (includeScrollbars) {
2025         verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar()) ? verticalScrollbar()->width() : 0;
2026         horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar()) ? horizontalScrollbar()->height() : 0;
2027     }
2028     
2029     return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
2030                    IntSize(max(0, m_layerSize.width() - verticalScrollbarWidth), 
2031                            max(0, m_layerSize.height() - horizontalScrollbarHeight)));
2032 }
2033
2034 IntSize RenderLayer::overhangAmount() const
2035 {
2036     return IntSize();
2037 }
2038
2039 bool RenderLayer::isActive() const
2040 {
2041     Page* page = renderer()->frame()->page();
2042     return page && page->focusController()->isActive();
2043 }
2044
2045 static int cornerStart(const RenderLayer* layer, int minX, int maxX, int thickness)
2046 {
2047     if (layer->renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2048         return minX + layer->renderer()->style()->borderLeftWidth();
2049     return maxX - thickness - layer->renderer()->style()->borderRightWidth();
2050 }
2051
2052 static IntRect cornerRect(const RenderLayer* layer, const IntRect& bounds)
2053 {
2054     int horizontalThickness;
2055     int verticalThickness;
2056     if (!layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2057         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
2058         // even when they don't exist in order to set the resizer square size properly.
2059         horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
2060         verticalThickness = horizontalThickness;
2061     } else if (layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
2062         horizontalThickness = layer->verticalScrollbar()->width();
2063         verticalThickness = horizontalThickness;
2064     } else if (layer->horizontalScrollbar() && !layer->verticalScrollbar()) {
2065         verticalThickness = layer->horizontalScrollbar()->height();
2066         horizontalThickness = verticalThickness;
2067     } else {
2068         horizontalThickness = layer->verticalScrollbar()->width();
2069         verticalThickness = layer->horizontalScrollbar()->height();
2070     }
2071     return IntRect(cornerStart(layer, bounds.x(), bounds.maxX(), horizontalThickness),
2072                    bounds.maxY() - verticalThickness - layer->renderer()->style()->borderBottomWidth(),
2073                    horizontalThickness, verticalThickness);
2074 }
2075
2076 IntRect RenderLayer::scrollCornerRect() const
2077 {
2078     // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
2079     // This happens when:
2080     // (a) A resizer is present and at least one scrollbar is present
2081     // (b) Both scrollbars are present.
2082     bool hasHorizontalBar = horizontalScrollbar();
2083     bool hasVerticalBar = verticalScrollbar();
2084     bool hasResizer = renderer()->style()->resize() != RESIZE_NONE;
2085     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
2086         return cornerRect(this, renderBox()->pixelSnappedBorderBoxRect());
2087     return IntRect();
2088 }
2089
2090 static IntRect resizerCornerRect(const RenderLayer* layer, const IntRect& bounds)
2091 {
2092     ASSERT(layer->renderer()->isBox());
2093     if (layer->renderer()->style()->resize() == RESIZE_NONE)
2094         return IntRect();
2095     return cornerRect(layer, bounds);
2096 }
2097
2098 IntRect RenderLayer::scrollCornerAndResizerRect() const
2099 {
2100     RenderBox* box = renderBox();
2101     if (!box)
2102         return IntRect();
2103     IntRect scrollCornerAndResizer = scrollCornerRect();
2104     if (scrollCornerAndResizer.isEmpty())
2105         scrollCornerAndResizer = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2106     return scrollCornerAndResizer;
2107 }
2108
2109 bool RenderLayer::isScrollCornerVisible() const
2110 {
2111     ASSERT(renderer()->isBox());
2112     return !scrollCornerRect().isEmpty();
2113 }
2114
2115 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
2116 {
2117     RenderView* view = renderer()->view();
2118     if (!view)
2119         return scrollbarRect;
2120
2121     IntRect rect = scrollbarRect;
2122     rect.move(scrollbarOffset(scrollbar));
2123
2124     return view->frameView()->convertFromRenderer(renderer(), rect);
2125 }
2126
2127 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
2128 {
2129     RenderView* view = renderer()->view();
2130     if (!view)
2131         return parentRect;
2132
2133     IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
2134     rect.move(-scrollbarOffset(scrollbar));
2135     return rect;
2136 }
2137
2138 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
2139 {
2140     RenderView* view = renderer()->view();
2141     if (!view)
2142         return scrollbarPoint;
2143
2144     IntPoint point = scrollbarPoint;
2145     point.move(scrollbarOffset(scrollbar));
2146     return view->frameView()->convertFromRenderer(renderer(), point);
2147 }
2148
2149 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
2150 {
2151     RenderView* view = renderer()->view();
2152     if (!view)
2153         return parentPoint;
2154
2155     IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
2156
2157     point.move(-scrollbarOffset(scrollbar));
2158     return point;
2159 }
2160
2161 IntSize RenderLayer::contentsSize() const
2162 {
2163     return IntSize(scrollWidth(), scrollHeight());
2164 }
2165
2166 int RenderLayer::visibleHeight() const
2167 {
2168     return m_layerSize.height();
2169 }
2170
2171 int RenderLayer::visibleWidth() const
2172 {
2173     return m_layerSize.width();
2174 }
2175
2176 bool RenderLayer::shouldSuspendScrollAnimations() const
2177 {
2178     RenderView* view = renderer()->view();
2179     if (!view)
2180         return true;
2181     return view->frameView()->shouldSuspendScrollAnimations();
2182 }
2183
2184 bool RenderLayer::isOnActivePage() const
2185 {
2186     return !m_renderer->document()->inPageCache();
2187 }
2188
2189 IntPoint RenderLayer::currentMousePosition() const
2190 {
2191     return renderer()->frame() ? renderer()->frame()->eventHandler()->currentMousePosition() : IntPoint();
2192 }
2193
2194 LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
2195 {
2196     const RenderBox* box = renderBox();
2197     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2198         return minX + box->borderLeft();
2199     return maxX - box->borderRight() - m_vBar->width();
2200 }
2201
2202 LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
2203 {
2204     const RenderBox* box = renderBox();
2205     int x = minX + box->borderLeft();
2206     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2207         x += m_vBar ? m_vBar->width() : resizerCornerRect(this, box->pixelSnappedBorderBoxRect()).width();
2208     return x;
2209 }
2210
2211 IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
2212 {
2213     RenderBox* box = renderBox();
2214
2215     if (scrollbar == m_vBar.get())
2216         return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
2217
2218     if (scrollbar == m_hBar.get())
2219         return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2220     
2221     ASSERT_NOT_REACHED();
2222     return IntSize();
2223 }
2224
2225 void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
2226 {
2227 #if USE(ACCELERATED_COMPOSITING)
2228     if (scrollbar == m_vBar.get()) {
2229         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2230             layer->setNeedsDisplayInRect(rect);
2231             return;
2232         }
2233     } else {
2234         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2235             layer->setNeedsDisplayInRect(rect);
2236             return;
2237         }
2238     }
2239 #endif
2240     IntRect scrollRect = rect;
2241     RenderBox* box = renderBox();
2242     ASSERT(box);
2243     // If we are not yet inserted into the tree, there is no need to repaint.
2244     if (!box->parent())
2245         return;
2246
2247     if (scrollbar == m_vBar.get())
2248         scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
2249     else
2250         scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
2251     renderer()->repaintRectangle(scrollRect);
2252 }
2253
2254 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
2255 {
2256 #if USE(ACCELERATED_COMPOSITING)
2257     if (GraphicsLayer* layer = layerForScrollCorner()) {
2258         layer->setNeedsDisplayInRect(rect);
2259         return;
2260     }
2261 #endif
2262     if (m_scrollCorner)
2263         m_scrollCorner->repaintRectangle(rect);
2264     if (m_resizer)
2265         m_resizer->repaintRectangle(rect);
2266 }
2267
2268 PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
2269 {
2270     RefPtr<Scrollbar> widget;
2271     RenderObject* actualRenderer = renderer()->node() ? renderer()->node()->shadowAncestorNode()->renderer() : renderer();
2272     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
2273     if (hasCustomScrollbarStyle)
2274         widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->node());
2275     else {
2276         widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
2277         if (orientation == HorizontalScrollbar)
2278             didAddHorizontalScrollbar(widget.get());
2279         else 
2280             didAddVerticalScrollbar(widget.get());
2281     }
2282     renderer()->document()->view()->addChild(widget.get());        
2283     return widget.release();
2284 }
2285
2286 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
2287 {
2288     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
2289     if (!scrollbar)
2290         return;
2291
2292     if (!scrollbar->isCustomScrollbar()) {
2293         if (orientation == HorizontalScrollbar)
2294             willRemoveHorizontalScrollbar(scrollbar.get());
2295         else
2296             willRemoveVerticalScrollbar(scrollbar.get());
2297     }
2298
2299     scrollbar->removeFromParent();
2300     scrollbar->disconnectFromScrollableArea();
2301     scrollbar = 0;
2302 }
2303
2304 bool RenderLayer::scrollsOverflow() const
2305 {
2306     if (!renderer()->isBox())
2307         return false;
2308
2309     return toRenderBox(renderer())->scrollsOverflow();
2310 }
2311
2312 bool RenderLayer::allowsScrolling() const
2313 {
2314     return (m_hBar && m_hBar->enabled()) || (m_vBar && m_vBar->enabled());
2315 }
2316
2317 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
2318 {
2319     if (hasScrollbar == hasHorizontalScrollbar())
2320         return;
2321
2322     if (hasScrollbar)
2323         m_hBar = createScrollbar(HorizontalScrollbar);
2324     else
2325         destroyScrollbar(HorizontalScrollbar);
2326
2327     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2328     if (m_hBar)
2329         m_hBar->styleChanged();
2330     if (m_vBar)
2331         m_vBar->styleChanged();
2332
2333 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2334     // Force an update since we know the scrollbars have changed things.
2335     if (renderer()->document()->hasDashboardRegions())
2336         renderer()->document()->setDashboardRegionsDirty(true);
2337 #endif
2338 }
2339
2340 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
2341 {
2342     if (hasScrollbar == hasVerticalScrollbar())
2343         return;
2344
2345     if (hasScrollbar)
2346         m_vBar = createScrollbar(VerticalScrollbar);
2347     else
2348         destroyScrollbar(VerticalScrollbar);
2349
2350      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
2351     if (m_hBar)
2352         m_hBar->styleChanged();
2353     if (m_vBar)
2354         m_vBar->styleChanged();
2355
2356 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2357     // Force an update since we know the scrollbars have changed things.
2358     if (renderer()->document()->hasDashboardRegions())
2359         renderer()->document()->setDashboardRegionsDirty(true);
2360 #endif
2361 }
2362
2363 ScrollableArea* RenderLayer::enclosingScrollableArea() const
2364 {
2365     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
2366         return scrollableLayer;
2367
2368     // FIXME: We should return the frame view here (or possibly an ancestor frame view,
2369     // if the frame view isn't scrollable.
2370     return 0;
2371 }
2372
2373 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
2374 {
2375     if (!m_vBar || (m_vBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
2376         return 0;
2377     return m_vBar->width();
2378 }
2379
2380 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
2381 {
2382     if (!m_hBar || (m_hBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
2383         return 0;
2384     return m_hBar->height();
2385 }
2386
2387 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
2388 {
2389     // Currently the resize corner is either the bottom right corner or the bottom left corner.
2390     // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
2391     IntSize elementSize = size();
2392     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2393         elementSize.setWidth(0);
2394     IntPoint resizerPoint = toPoint(elementSize);
2395     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2396     return localPoint - resizerPoint;
2397 }
2398
2399 bool RenderLayer::hasOverflowControls() const
2400 {
2401     return m_hBar || m_vBar || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
2402 }
2403
2404 void RenderLayer::positionOverflowControls(const IntSize& offsetFromLayer)
2405 {
2406     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2407         return;
2408     
2409     RenderBox* box = renderBox();
2410     if (!box)
2411         return;
2412
2413     const IntRect borderBox = box->pixelSnappedBorderBoxRect();
2414     const IntRect& scrollCorner = scrollCornerRect();
2415     IntRect absBounds(borderBox.location() + offsetFromLayer, borderBox.size());
2416     if (m_vBar)
2417         m_vBar->setFrameRect(IntRect(verticalScrollbarStart(absBounds.x(), absBounds.maxX()),
2418                                      absBounds.y() + box->borderTop(),
2419                                      m_vBar->width(),
2420                                      absBounds.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height()));
2421
2422     if (m_hBar)
2423         m_hBar->setFrameRect(IntRect(horizontalScrollbarStart(absBounds.x()),
2424                                      absBounds.maxY() - box->borderBottom() - m_hBar->height(),
2425                                      absBounds.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
2426                                      m_hBar->height()));
2427
2428 #if USE(ACCELERATED_COMPOSITING)
2429     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2430         if (m_hBar) {
2431             layer->setPosition(m_hBar->frameRect().location() - offsetFromLayer);
2432             layer->setSize(m_hBar->frameRect().size());
2433         }
2434         layer->setDrawsContent(m_hBar);
2435     }
2436     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2437         if (m_vBar) {
2438             layer->setPosition(m_vBar->frameRect().location() - offsetFromLayer);
2439             layer->setSize(m_vBar->frameRect().size());
2440         }
2441         layer->setDrawsContent(m_vBar);
2442     }
2443
2444     if (GraphicsLayer* layer = layerForScrollCorner()) {
2445         const LayoutRect& scrollCornerAndResizer = scrollCornerAndResizerRect();
2446         layer->setPosition(scrollCornerAndResizer.location());
2447         layer->setSize(scrollCornerAndResizer.size());
2448         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
2449     }
2450 #endif
2451
2452     if (m_scrollCorner)
2453         m_scrollCorner->setFrameRect(scrollCorner);
2454     if (m_resizer)
2455         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
2456 }
2457
2458 int RenderLayer::scrollWidth() const
2459 {
2460     ASSERT(renderBox());
2461     if (m_scrollDimensionsDirty)
2462         const_cast<RenderLayer*>(this)->computeScrollDimensions();
2463     return snapSizeToPixel(m_scrollSize.width(), renderBox()->clientLeft() + renderBox()->x());
2464 }
2465
2466 int RenderLayer::scrollHeight() const
2467 {
2468     ASSERT(renderBox());
2469     if (m_scrollDimensionsDirty)
2470         const_cast<RenderLayer*>(this)->computeScrollDimensions();
2471     return snapSizeToPixel(m_scrollSize.height(), renderBox()->clientTop() + renderBox()->y());
2472 }
2473
2474 LayoutUnit RenderLayer::overflowTop() const
2475 {
2476     RenderBox* box = renderBox();
2477     LayoutRect overflowRect(box->layoutOverflowRect());
2478     box->flipForWritingMode(overflowRect);
2479     return overflowRect.y();
2480 }
2481
2482 LayoutUnit RenderLayer::overflowBottom() const
2483 {
2484     RenderBox* box = renderBox();
2485     LayoutRect overflowRect(box->layoutOverflowRect());
2486     box->flipForWritingMode(overflowRect);
2487     return overflowRect.maxY();
2488 }
2489
2490 LayoutUnit RenderLayer::overflowLeft() const
2491 {
2492     RenderBox* box = renderBox();
2493     LayoutRect overflowRect(box->layoutOverflowRect());
2494     box->flipForWritingMode(overflowRect);
2495     return overflowRect.x();
2496 }
2497
2498 LayoutUnit RenderLayer::overflowRight() const
2499 {
2500     RenderBox* box = renderBox();
2501     LayoutRect overflowRect(box->layoutOverflowRect());
2502     box->flipForWritingMode(overflowRect);
2503     return overflowRect.maxX();
2504 }
2505
2506 void RenderLayer::computeScrollDimensions()
2507 {
2508     RenderBox* box = renderBox();
2509     ASSERT(box);
2510
2511     m_scrollDimensionsDirty = false;
2512
2513     m_scrollSize.setWidth(overflowRight() - overflowLeft());
2514     m_scrollSize.setHeight(overflowBottom() - overflowTop());
2515
2516     int scrollableLeftOverflow = overflowLeft() - box->borderLeft();
2517     int scrollableTopOverflow = overflowTop() - box->borderTop();
2518     setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
2519 }
2520
2521 bool RenderLayer::hasHorizontalOverflow() const
2522 {
2523     ASSERT(!m_scrollDimensionsDirty);
2524
2525     return scrollWidth() > renderBox()->pixelSnappedClientWidth();
2526 }
2527
2528 bool RenderLayer::hasVerticalOverflow() const
2529 {
2530     ASSERT(!m_scrollDimensionsDirty);
2531
2532     return scrollHeight() > renderBox()->pixelSnappedClientHeight();
2533 }
2534
2535 void RenderLayer::updateScrollbarsAfterLayout()
2536 {
2537     RenderBox* box = renderBox();
2538     ASSERT(box);
2539
2540     // List box parts handle the scrollbars by themselves so we have nothing to do.
2541     if (box->style()->appearance() == ListboxPart)
2542         return;
2543
2544     bool hasHorizontalOverflow = this->hasHorizontalOverflow();
2545     bool hasVerticalOverflow = this->hasVerticalOverflow();
2546
2547     // overflow:scroll should just enable/disable.
2548     if (renderer()->style()->overflowX() == OSCROLL)
2549         m_hBar->setEnabled(hasHorizontalOverflow);
2550     if (renderer()->style()->overflowY() == OSCROLL)
2551         m_vBar->setEnabled(hasVerticalOverflow);
2552
2553     // overflow:auto may need to lay out again if scrollbars got added/removed.
2554     bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
2555     bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
2556
2557     if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
2558         if (box->hasAutoHorizontalScrollbar())
2559             setHasHorizontalScrollbar(hasHorizontalOverflow);
2560         if (box->hasAutoVerticalScrollbar())
2561             setHasVerticalScrollbar(hasVerticalOverflow);
2562
2563         updateSelfPaintingLayer();
2564
2565 #if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
2566         // Force an update since we know the scrollbars have changed things.
2567         if (renderer()->document()->hasDashboardRegions())
2568             renderer()->document()->setDashboardRegionsDirty(true);
2569 #endif
2570
2571         renderer()->repaint();
2572
2573         if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
2574             if (!m_inOverflowRelayout) {
2575                 // Our proprietary overflow: overlay value doesn't trigger a layout.
2576                 m_inOverflowRelayout = true;
2577                 renderer()->setNeedsLayout(true, MarkOnlyThis);
2578                 if (renderer()->isRenderBlock()) {
2579                     RenderBlock* block = toRenderBlock(renderer());
2580                     block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
2581                     block->layoutBlock(true);
2582                 } else
2583                     renderer()->layout();
2584                 m_inOverflowRelayout = false;
2585             }
2586         }
2587     }
2588
2589     // Set up the range (and page step/line step).
2590     if (m_hBar) {
2591         int clientWidth = box->pixelSnappedClientWidth();
2592         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
2593         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2594         m_hBar->setProportion(clientWidth, m_scrollSize.width());
2595     }
2596     if (m_vBar) {
2597         int clientHeight = box->pixelSnappedClientHeight();
2598         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
2599         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2600         m_vBar->setProportion(clientHeight, m_scrollSize.height());
2601     }
2602
2603     updateScrollableAreaSet((hasHorizontalOverflow || hasVerticalOverflow) && scrollsOverflow());
2604 }
2605
2606 void RenderLayer::updateScrollInfoAfterLayout()
2607 {
2608     RenderBox* box = renderBox();
2609     if (!box)
2610         return;
2611
2612     m_scrollDimensionsDirty = true;
2613     IntSize originalScrollOffset = scrollOffset();
2614
2615     computeScrollDimensions();
2616
2617     if (box->style()->overflowX() != OMARQUEE) {
2618         // Layout may cause us to be at an invalid scroll position. In this case we need
2619         // to pull our scroll offsets back to the max (or push them up to the min).
2620         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset());
2621         if (clampedScrollOffset != scrollOffset())
2622             scrollToOffset(clampedScrollOffset);
2623     }
2624
2625     updateScrollbarsAfterLayout();
2626
2627     if (originalScrollOffset != scrollOffset())
2628         scrollToOffsetWithoutAnimation(toPoint(scrollOffset()));
2629 }
2630
2631 void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
2632 {
2633     // Don't do anything if we have no overflow.
2634     if (!renderer()->hasOverflowClip())
2635         return;
2636
2637     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
2638     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
2639     // will be false, and we should just tell the root layer that there are overlay scrollbars
2640     // that need to be painted. That will cause the second pass through the layer tree to run,
2641     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
2642     // second pass doesn't need to re-enter the RenderTree to get it right.
2643     if (hasOverlayScrollbars() && !paintingOverlayControls) {
2644         m_cachedOverlayScrollbarOffset = paintOffset;
2645 #if USE(ACCELERATED_COMPOSITING)
2646         // It's not necessary to do the second pass if the scrollbars paint into layers.
2647         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
2648             return;
2649 #endif
2650         RenderView* renderView = renderer()->view();
2651         renderView->layer()->setContainsDirtyOverlayScrollbars(true);
2652         renderView->frameView()->setContainsScrollableAreaWithOverlayScrollbars(true);
2653         return;
2654     }
2655
2656     // This check is required to avoid painting custom CSS scrollbars twice.
2657     if (paintingOverlayControls && !hasOverlayScrollbars())
2658         return;
2659
2660     IntPoint adjustedPaintOffset = paintOffset;
2661     if (paintingOverlayControls)
2662         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
2663
2664     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
2665     // widgets can move without layout occurring (most notably when you scroll a document that
2666     // contains fixed positioned elements).
2667     positionOverflowControls(toSize(adjustedPaintOffset));
2668
2669     // Now that we're sure the scrollbars are in the right place, paint them.
2670     if (m_hBar
2671 #if USE(ACCELERATED_COMPOSITING)
2672         && !layerForHorizontalScrollbar()
2673 #endif
2674               )
2675         m_hBar->paint(context, damageRect);
2676     if (m_vBar
2677 #if USE(ACCELERATED_COMPOSITING)
2678         && !layerForVerticalScrollbar()
2679 #endif
2680               )
2681         m_vBar->paint(context, damageRect);
2682
2683 #if USE(ACCELERATED_COMPOSITING)
2684     if (layerForScrollCorner())
2685         return;
2686 #endif
2687
2688     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
2689     // edge of the box.
2690     paintScrollCorner(context, adjustedPaintOffset, damageRect);
2691     
2692     // Paint our resizer last, since it sits on top of the scroll corner.
2693     paintResizer(context, adjustedPaintOffset, damageRect);
2694 }
2695
2696 void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2697 {
2698     RenderBox* box = renderBox();
2699     ASSERT(box);
2700
2701     IntRect absRect = scrollCornerRect();
2702     absRect.moveBy(paintOffset);
2703     if (!absRect.intersects(damageRect))
2704         return;
2705
2706     if (context->updatingControlTints()) {
2707         updateScrollCornerStyle();
2708         return;
2709     }
2710
2711     if (m_scrollCorner) {
2712         m_scrollCorner->paintIntoRect(context, paintOffset, absRect);
2713         return;
2714     }
2715
2716     // We don't want to paint white if we have overlay scrollbars, since we need
2717     // to see what is behind it.
2718     if (!hasOverlayScrollbars())
2719         context->fillRect(absRect, Color::white, box->style()->colorSpace());
2720 }
2721
2722 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
2723 {
2724     float deviceScaleFactor = WebCore::deviceScaleFactor(renderer()->frame());
2725
2726     RefPtr<Image> resizeCornerImage;
2727     IntSize cornerResizerSize;
2728     if (deviceScaleFactor >= 2) {
2729         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
2730         resizeCornerImage = resizeCornerImageHiRes;
2731         cornerResizerSize = resizeCornerImage->size();
2732         cornerResizerSize.scale(0.5f);
2733     } else {
2734         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
2735         resizeCornerImage = resizeCornerImageLoRes;
2736         cornerResizerSize = resizeCornerImage->size();
2737     }
2738
2739     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
2740         context->save();
2741         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
2742         context->scale(FloatSize(-1.0, 1.0));
2743         context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), IntRect(IntPoint(), cornerResizerSize));
2744         context->restore();
2745         return;
2746     }
2747     IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
2748     context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), imageRect);
2749 }
2750
2751 void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2752 {
2753     if (renderer()->style()->resize() == RESIZE_NONE)
2754         return;
2755
2756     RenderBox* box = renderBox();
2757     ASSERT(box);
2758
2759     IntRect absRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2760     absRect.moveBy(paintOffset);
2761     if (!absRect.intersects(damageRect))
2762         return;
2763
2764     if (context->updatingControlTints()) {
2765         updateResizerStyle();
2766         return;
2767     }
2768     
2769     if (m_resizer) {
2770         m_resizer->paintIntoRect(context, paintOffset, absRect);
2771         return;
2772     }
2773
2774     drawPlatformResizerImage(context, absRect);
2775
2776     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
2777     // Clipping will exclude the right and bottom edges of this frame.
2778     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
2779         GraphicsContextStateSaver stateSaver(*context);
2780         context->clip(absRect);
2781         IntRect largerCorner = absRect;
2782         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
2783         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
2784         context->setStrokeThickness(1.0f);
2785         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
2786         context->drawRect(largerCorner);
2787     }
2788 }
2789
2790 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
2791 {
2792     if (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE)
2793         return false;
2794     
2795     RenderBox* box = renderBox();
2796     ASSERT(box);
2797
2798     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2799
2800     IntRect localBounds(0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
2801     return resizerCornerRect(this, localBounds).contains(localPoint);
2802 }
2803     
2804 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
2805 {
2806     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2807         return false;
2808
2809     RenderBox* box = renderBox();
2810     ASSERT(box);
2811     
2812     IntRect resizeControlRect;
2813     if (renderer()->style()->resize() != RESIZE_NONE) {
2814         resizeControlRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2815         if (resizeControlRect.contains(localPoint))
2816             return true;
2817     }
2818
2819     int resizeControlSize = max(resizeControlRect.height(), 0);
2820
2821     if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
2822         LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
2823                             box->borderTop(),
2824                             m_vBar->width(),
2825                             box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
2826         if (vBarRect.contains(localPoint)) {
2827             result.setScrollbar(m_vBar.get());
2828             return true;
2829         }
2830     }
2831
2832     resizeControlSize = max(resizeControlRect.width(), 0);
2833     if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
2834         LayoutRect hBarRect(horizontalScrollbarStart(0),
2835                             box->height() - box->borderBottom() - m_hBar->height(),
2836                             box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
2837                             m_hBar->height());
2838         if (hBarRect.contains(localPoint)) {
2839             result.setScrollbar(m_hBar.get());
2840             return true;
2841         }
2842     }
2843
2844     return false;
2845 }
2846
2847 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
2848 {
2849     return ScrollableArea::scroll(direction, granularity, multiplier);
2850 }
2851
2852 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
2853 {
2854     OverlapTestRequestMap overlapTestRequests;
2855     paintLayer(this, context, enclosingIntRect(damageRect), LayoutSize(), paintBehavior, paintingRoot, region, &overlapTestRequests, paintFlags);
2856     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2857     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
2858         it->first->setOverlapTestResult(false);
2859 }
2860
2861 void RenderLayer::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot)
2862 {
2863     if (!m_containsDirtyOverlayScrollbars)
2864         return;
2865     paintLayer(this, context, damageRect, LayoutSize(), paintBehavior, paintingRoot, 0, 0, PaintLayerHaveTransparency | PaintLayerTemporaryClipRects 
2866                | PaintLayerPaintingOverlayScrollbars);
2867     m_containsDirtyOverlayScrollbars = false;
2868 }
2869
2870 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2871 static bool inContainingBlockChain(RenderLayer* startLayer, RenderLayer* endLayer)
2872 {
2873     if (startLayer == endLayer)
2874         return true;
2875     
2876     RenderView* view = startLayer->renderer()->view();
2877     for (RenderBlock* currentBlock = startLayer->renderer()->containingBlock(); currentBlock && currentBlock != view; currentBlock = currentBlock->containingBlock()) {
2878         if (currentBlock->layer() == endLayer)
2879             return true;
2880     }
2881     
2882     return false;
2883 }
2884 #endif
2885
2886 void RenderLayer::clipToRect(RenderLayer* rootLayer, GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect,
2887                              BorderRadiusClippingRule rule)
2888 {
2889     if (clipRect.rect() == paintDirtyRect)
2890         return;
2891     context->save();
2892     context->clip(pixelSnappedIntRect(clipRect.rect()));
2893     
2894     if (!clipRect.hasRadius())
2895         return;
2896
2897 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2898     // If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
2899     // any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
2900     // containing block chain so we check that also.
2901     for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
2902         if (layer->renderer()->hasOverflowClip() && layer->renderer()->style()->hasBorderRadius() && inContainingBlockChain(this, layer)) {
2903                 LayoutPoint delta;
2904                 layer->convertToLayerCoords(rootLayer, delta);
2905                 context->addRoundedRectClip(layer->renderer()->style()->getRoundedInnerBorderFor(LayoutRect(delta, layer->size())));
2906         }
2907
2908         if (layer == rootLayer)
2909             break;
2910     }
2911 #endif
2912 }
2913
2914 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
2915 {
2916     if (clipRect.rect() == paintDirtyRect)
2917         return;
2918     context->restore();
2919 }
2920
2921 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
2922 {
2923     Vector<OverlapTestRequestClient*> overlappedRequestClients;
2924     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2925     LayoutRect boundingBox = layer->boundingBox(rootLayer);
2926     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
2927         if (!boundingBox.intersects(it->second))
2928             continue;
2929
2930         it->first->setOverlapTestResult(true);
2931         overlappedRequestClients.append(it->first);
2932     }
2933     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
2934         overlapTestRequests.remove(overlappedRequestClients[i]);
2935 }
2936
2937 #if USE(ACCELERATED_COMPOSITING)
2938 static bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
2939 {
2940     return paintingReflection && !layer->has3DTransform();
2941 }
2942 #endif
2943     
2944 static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
2945 {
2946     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
2947     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2948     // will do a full repaint().
2949     if (layer->renderer()->document()->didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer()->isRoot())
2950         return true;
2951
2952     // Avoid painting all layers if the document is in a state where visual updates aren't allowed.
2953     // A full repaint will occur in Document::implicitClose() if painting is suppressed here.
2954     if (!layer->renderer()->document()->visualUpdatesAllowed())
2955         return true;
2956
2957     return false;
2958 }
2959
2960
2961 void RenderLayer::paintLayer(RenderLayer* rootLayer, GraphicsContext* context,
2962                         const LayoutRect& paintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
2963                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
2964                         PaintLayerFlags paintFlags)
2965 {
2966 #if USE(ACCELERATED_COMPOSITING)
2967     if (isComposited()) {
2968         // The updatingControlTints() painting pass goes through compositing layers,
2969         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
2970         if (context->updatingControlTints() || (paintBehavior & PaintBehaviorFlattenCompositingLayers))
2971             paintFlags |= PaintLayerTemporaryClipRects;
2972         else if (!backing()->paintsIntoWindow() && !backing()->paintsIntoCompositedAncestor() && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection) && !(rootLayer->containsDirtyOverlayScrollbars() && (paintFlags & PaintLayerPaintingOverlayScrollbars))) {
2973             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
2974             return;
2975         }
2976     }
2977 #endif
2978
2979     // Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
2980     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
2981         return;
2982
2983     if (shouldSuppressPaintingLayer(this))
2984         return;
2985     
2986     // If this layer is totally invisible then there is nothing to paint.
2987     if (!renderer()->opacity())
2988         return;
2989
2990     if (paintsWithTransparency(paintBehavior))
2991         paintFlags |= PaintLayerHaveTransparency;
2992
2993     // PaintLayerAppliedTransform is used in RenderReplica, to avoid applying the transform twice.
2994     if (paintsWithTransform(paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
2995         TransformationMatrix layerTransform = renderableTransform(paintBehavior);
2996         // If the transform can't be inverted, then don't paint anything.
2997         if (!layerTransform.isInvertible())
2998             return;
2999
3000         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
3001         // layer from the parent now, assuming there is a parent
3002         if (paintFlags & PaintLayerHaveTransparency) {
3003             if (parent())
3004                 parent()->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
3005             else
3006                 beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
3007         }
3008
3009         // Make sure the parent's clip rects have been calculated.
3010         ClipRect clipRect = paintDirtyRect;
3011         if (parent()) {
3012             clipRect = backgroundClipRect(rootLayer, region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects);
3013             clipRect.intersect(paintDirtyRect);
3014         
3015             // Push the parent coordinate space's clip.
3016             parent()->clipToRect(rootLayer, context, paintDirtyRect, clipRect);
3017         }
3018
3019         // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
3020         // This involves subtracting out the position of the layer in our current coordinate space, but preserving
3021         // the accumulated error for sub-pixel layout.
3022         LayoutPoint delta;
3023         convertToLayerCoords(rootLayer, delta);
3024         TransformationMatrix transform(layerTransform);
3025         IntPoint roundedDelta = roundedIntPoint(delta);
3026         transform.translateRight(roundedDelta.x(), roundedDelta.y());
3027         LayoutSize adjustedSubPixelAccumulation = subPixelAccumulation + (delta - roundedDelta);
3028         
3029         // Apply the transform.
3030         {
3031             GraphicsContextStateSaver stateSaver(*context);
3032             context->concatCTM(transform.toAffineTransform());
3033
3034             // Now do a paint with the root layer shifted to be us.
3035             paintLayerContentsAndReflection(this, context, enclosingIntRect(transform.inverse().mapRect(paintDirtyRect)), adjustedSubPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3036         }        
3037
3038         // Restore the clip.
3039         if (parent())
3040             parent()->restoreClip(context, paintDirtyRect, clipRect);
3041
3042         return;
3043     }
3044     
3045     paintLayerContentsAndReflection(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3046 }
3047
3048 void RenderLayer::paintLayerContentsAndReflection(RenderLayer* rootLayer, GraphicsContext* context,
3049                         const LayoutRect& paintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
3050                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3051                         PaintLayerFlags paintFlags)
3052 {
3053     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3054
3055     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3056
3057     // Paint the reflection first if we have one.
3058     if (m_reflection && !m_paintingInsideReflection) {
3059         // Mark that we are now inside replica painting.
3060         m_paintingInsideReflection = true;
3061         reflectionLayer()->paintLayer(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags | PaintLayerPaintingReflection);
3062         m_paintingInsideReflection = false;
3063     }
3064
3065     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
3066     paintLayerContents(rootLayer, context, paintDirtyRect, subPixelAccumulation, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3067 }
3068
3069 void RenderLayer::paintLayerContents(RenderLayer* rootLayer, GraphicsContext* context, 
3070                         const LayoutRect& parentPaintDirtyRect, const LayoutSize& subPixelAccumulation, PaintBehavior paintBehavior,
3071                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3072                         PaintLayerFlags paintFlags)
3073 {
3074     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3075
3076     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3077     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
3078     bool isSelfPaintingLayer = this->isSelfPaintingLayer();
3079     bool isPaintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
3080     // Outline always needs to be painted even if we have no visible content.
3081     bool shouldPaintOutline = isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3082     bool shouldPaintContent = m_hasVisibleContent && isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3083
3084     // Calculate the clip rects we should use only when we need them.
3085     LayoutRect layerBounds;
3086     ClipRect damageRect, clipRectToApply, outlineRect;
3087     LayoutPoint paintOffset;
3088     LayoutRect paintDirtyRect = parentPaintDirtyRect;
3089     
3090     bool useClipRect = true;
3091     GraphicsContext* transparencyLayerContext = context;
3092     
3093     // Ensure our lists are up-to-date.
3094     updateLayerListsIfNeeded();
3095
3096 #if ENABLE(CSS_FILTERS)
3097     FilterEffectRendererHelper filterPainter(filterRenderer() && paintsWithFilters());
3098     if (filterPainter.haveFilterEffect() && !context->paintingDisabled()) {
3099         LayoutPoint rootLayerOffset;
3100         convertToLayerCoords(rootLayer, rootLayerOffset);
3101         RenderLayerFilterInfo* filterInfo = this->filterInfo();
3102         ASSERT(filterInfo);
3103         LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
3104         filterRepaintRect.move(rootLayerOffset.x(), rootLayerOffset.y());
3105         if (filterPainter.prepareFilterEffect(this, calculateLayerBounds(this, rootLayer, 0), parentPaintDirtyRect, filterRepaintRect)) {
3106             // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
3107             filterInfo->resetDirtySourceRect();
3108
3109             // Rewire the old context to a memory buffer, so that we can capture the contents of the layer.
3110             // NOTE: We saved the old context in the "transparencyLayerContext" local variable, to be able to start a transparency layer
3111             // on the original context and avoid duplicating "beginFilterEffect" after each transpareny layer call. Also, note that 
3112             // beginTransparencyLayers will only create a single lazy transparency layer, even though it is called twice in this method.
3113             context = filterPainter.beginFilterEffect(context);
3114
3115             // Check that we didn't fail to allocate the graphics context for the offscreen buffer.
3116             if (filterPainter.hasStartedFilterEffect()) {
3117                 paintDirtyRect = filterPainter.repaintRect();
3118                 // If the filter needs the full source image, we need to avoid using the clip rectangles.
3119                 // Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
3120                 // Note that we will still apply the clipping on the final rendering of the filter.
3121                 useClipRect = !filterRenderer()->hasFilterThatMovesPixels();
3122             }
3123         }
3124     }
3125 #endif
3126     
3127     if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
3128         calculateRects(rootLayer, region, (localPaintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
3129         paintOffset = toPoint(layerBounds.location() - renderBoxLocation() + subPixelAccumulation);
3130     }
3131
3132     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
3133     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
3134     
3135     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
3136     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
3137     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
3138     // so it will be tested against as we descend through the renderers.
3139     RenderObject* paintingRootForRenderer = 0;
3140     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
3141         paintingRootForRenderer = paintingRoot;
3142
3143     if (overlapTestRequests && isSelfPaintingLayer)
3144         performOverlapTests(*overlapTestRequests, rootLayer, this);
3145
3146     // We want to paint our layer, but only if we intersect the damage rect.
3147     shouldPaintContent &= intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
3148     
3149     if (localPaintFlags & PaintLayerPaintingCompositingBackgroundPhase) {
3150         if (shouldPaintContent && !selectionOnly) {
3151             // Begin transparency layers lazily now that we know we have to paint something.
3152             if (haveTransparency)
3153                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3154         
3155             if (useClipRect) {
3156                 // Paint our background first, before painting any child layers.
3157                 // Establish the clip used to paint our background.
3158                 clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Background painting will handle clipping to self.
3159             }
3160             
3161             // Paint the background.
3162             PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseBlockBackground, false, paintingRootForRenderer, region, 0);
3163             renderer()->paint(paintInfo, paintOffset);
3164
3165             if (useClipRect) {
3166                 // Restore the clip.
3167                 restoreClip(context, paintDirtyRect, damageRect);
3168             }
3169         }
3170
3171         // Now walk the sorted list of children with negative z-indices.
3172         paintList(negZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3173     }
3174     
3175     if (localPaintFlags & PaintLayerPaintingCompositingForegroundPhase) {
3176         // Now establish the appropriate clip and paint our child RenderObjects.
3177         if (shouldPaintContent && !clipRectToApply.isEmpty()) {
3178             // Begin transparency layers lazily now that we know we have to paint something.
3179             if (haveTransparency)
3180                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3181
3182             if (useClipRect) {
3183                 // Set up the clip used when painting our children.
3184                 clipToRect(rootLayer, context, paintDirtyRect, clipRectToApply);
3185             }
3186             
3187             PaintInfo paintInfo(context, pixelSnappedIntRect(clipRectToApply.rect()),
3188                                 selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
3189                                 forceBlackText, paintingRootForRenderer, region, 0);
3190             renderer()->paint(paintInfo, paintOffset);
3191             if (!selectionOnly) {
3192                 paintInfo.phase = PaintPhaseFloat;
3193                 renderer()->paint(paintInfo, paintOffset);
3194                 paintInfo.phase = PaintPhaseForeground;
3195                 paintInfo.overlapTestRequests = overlapTestRequests;
3196                 renderer()->paint(paintInfo, paintOffset);
3197                 paintInfo.phase = PaintPhaseChildOutlines;
3198                 renderer()->paint(paintInfo, paintOffset);
3199             }
3200
3201             if (useClipRect) {
3202                 // Now restore our clip.
3203                 restoreClip(context, paintDirtyRect, clipRectToApply);
3204             }
3205         }
3206
3207         if (shouldPaintOutline && !outlineRect.isEmpty()) {
3208             // Paint our own outline
3209             PaintInfo paintInfo(context, pixelSnappedIntRect(outlineRect.rect()), PaintPhaseSelfOutline, false, paintingRootForRenderer, region, 0);
3210             clipToRect(rootLayer, context, paintDirtyRect, outlineRect, DoNotIncludeSelfForBorderRadius);
3211             renderer()->paint(paintInfo, paintOffset);
3212             restoreClip(context, paintDirtyRect, outlineRect);
3213         }
3214     
3215         // Paint any child layers that have overflow.
3216         paintList(m_normalFlowList, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3217     
3218         // Now walk the sorted list of children with positive z-indices.
3219         paintList(posZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3220     }
3221
3222     if (isPaintingOverlayScrollbars) {
3223         clipToRect(rootLayer, context, paintDirtyRect, damageRect);
3224         paintOverflowControls(context, roundedIntPoint(paintOffset), pixelSnappedIntRect(damageRect.rect()), true);
3225         restoreClip(context, paintDirtyRect, damageRect);
3226     }
3227
3228 #if ENABLE(CSS_FILTERS)
3229     if (filterPainter.hasStartedFilterEffect()) {
3230         // Apply the correct clipping (ie. overflow: hidden).
3231         clipToRect(rootLayer, transparencyLayerContext, paintDirtyRect, damageRect);
3232         context = filterPainter.applyFilterEffect();
3233         restoreClip(transparencyLayerContext, paintDirtyRect, damageRect);
3234     }
3235 #endif
3236
3237     // Make sure that we now use the original transparency context.
3238     ASSERT(transparencyLayerContext == context);
3239
3240     if ((localPaintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && renderer()->hasMask() && !selectionOnly) {
3241         if (useClipRect)
3242             clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Mask painting will handle clipping to self.
3243         
3244         // Paint the mask.
3245         PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseMask, false, paintingRootForRenderer, region, 0);
3246         renderer()->paint(paintInfo, paintOffset);
3247         
3248         if (useClipRect) {
3249             // Restore the clip.
3250             restoreClip(context, paintDirtyRect, damageRect);
3251         }
3252     }
3253
3254     // End our transparency layer
3255     if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
3256         context->endTransparencyLayer();
3257         context->restore();
3258         m_usedTransparency = false;
3259     }
3260 }
3261
3262 void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* context,
3263                             const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3264                             RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3265                             PaintLayerFlags paintFlags)
3266 {
3267     if (!list)
3268         return;
3269
3270     if (!hasSelfPaintingLayerDescendant())
3271         return;
3272
3273 #if !ASSERT_DISABLED
3274     LayerListMutationDetector mutationChecker(this);
3275 #endif
3276
3277     for (size_t i = 0; i < list->size(); ++i) {
3278         RenderLayer* childLayer = list->at(i);
3279         if (!childLayer->isPaginated())
3280             childLayer->paintLayer(rootLayer, context, paintDirtyRect, LayoutSize(), paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3281         else
3282             paintPaginatedChildLayer(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3283     }
3284 }
3285
3286 void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3287                                            const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3288                                            RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3289                                            PaintLayerFlags paintFlags)
3290 {
3291     // We need to do multiple passes, breaking up our child layer into strips.
3292     Vector<RenderLayer*> columnLayers;
3293     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3294     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3295         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3296             columnLayers.append(curr);
3297         if (curr == ancestorLayer)
3298             break;
3299     }
3300
3301     // It is possible for paintLayer() to be called after the child layer ceases to be paginated but before
3302     // updateLayerPositions() is called and resets the isPaginated() flag, see <rdar://problem/10098679>.
3303     // If this is the case, just bail out, since the upcoming call to updateLayerPositions() will repaint the layer.
3304     if (!columnLayers.size())
3305         return;
3306
3307     paintChildLayerIntoColumns(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags, columnLayers, columnLayers.size() - 1);
3308 }
3309
3310 void RenderLayer::paintChildLayerIntoColumns(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3311                                              const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3312                                              RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3313                                              PaintLayerFlags paintFlags, const Vector<RenderLayer*>& columnLayers, size_t colIndex)
3314 {
3315     RenderBlock* columnBlock = toRenderBlock(columnLayers[colIndex]->renderer());
3316
3317     ASSERT(columnBlock && columnBlock->hasColumns());
3318     if (!columnBlock || !columnBlock->hasColumns())
3319         return;
3320     
3321     LayoutPoint layerOffset;
3322     // FIXME: It looks suspicious to call convertToLayerCoords here
3323     // as canUseConvertToLayerCoords is true for this layer.
3324     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3325     
3326     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3327
3328     ColumnInfo* colInfo = columnBlock->columnInfo();
3329     unsigned colCount = columnBlock->columnCount(colInfo);
3330     LayoutUnit currLogicalTopOffset = 0;
3331     for (unsigned i = 0; i < colCount; i++) {
3332         // For each rect, we clip to the rect, and then we adjust our coords.
3333         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3334         columnBlock->flipForWritingMode(colRect);
3335         LayoutUnit logicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - columnBlock->logicalLeftOffsetForContent();
3336         LayoutSize offset;
3337         if (isHorizontal) {
3338             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3339                 offset = LayoutSize(logicalLeftOffset, currLogicalTopOffset);
3340             else
3341                 offset = LayoutSize(0, colRect.y() + currLogicalTopOffset - columnBlock->borderTop() - columnBlock->paddingTop());
3342         } else {
3343             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3344                 offset = LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3345             else
3346                 offset = LayoutSize(colRect.x() + currLogicalTopOffset - columnBlock->borderLeft() - columnBlock->paddingLeft(), 0);
3347         }
3348
3349         colRect.moveBy(layerOffset);
3350
3351         LayoutRect localDirtyRect(paintDirtyRect);
3352         localDirtyRect.intersect(colRect);
3353         
3354         if (!localDirtyRect.isEmpty()) {
3355             GraphicsContextStateSaver stateSaver(*context);
3356             
3357             // Each strip pushes a clip, since column boxes are specified as being
3358             // like overflow:hidden.
3359             context->clip(pixelSnappedIntRect(colRect));
3360
3361             if (!colIndex) {
3362                 // Apply a translation transform to change where the layer paints.
3363                 TransformationMatrix oldTransform;
3364                 bool oldHasTransform = childLayer->transform();
3365                 if (oldHasTransform)
3366                     oldTransform = *childLayer->transform();
3367                 TransformationMatrix newTransform(oldTransform);
3368                 newTransform.translateRight(roundToInt(offset.width()), roundToInt(offset.height()));
3369                 
3370                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3371                 childLayer->paintLayer(rootLayer, context, localDirtyRect, LayoutSize(), paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3372                 if (oldHasTransform)
3373                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3374                 else
3375                     childLayer->m_transform.clear();
3376             } else {
3377                 // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
3378                 // This involves subtracting out the position of the layer in our current coordinate space.
3379                 LayoutPoint childOffset;
3380                 columnLayers[colIndex - 1]->convertToLayerCoords(rootLayer, childOffset);
3381                 TransformationMatrix transform;
3382                 transform.translateRight(roundToInt(childOffset.x() + offset.width()), roundToInt(childOffset.y() + offset.height()));
3383                 
3384                 // Apply the transform.
3385                 context->concatCTM(transform.toAffineTransform());
3386
3387                 // Now do a paint with the root layer shifted to be the next multicol block.
3388                 paintChildLayerIntoColumns(childLayer, columnLayers[colIndex - 1], context, transform.inverse().mapRect(localDirtyRect), paintBehavior, 
3389                                            paintingRoot, region, overlapTestRequests, paintFlags, 
3390                                            columnLayers, colIndex - 1);
3391             }
3392         }
3393
3394         // Move to the next position.
3395         LayoutUnit blockDelta = isHorizontal ? colRect.height() : colRect.width();
3396         if (columnBlock->style()->isFlippedBlocksWritingMode())
3397             currLogicalTopOffset += blockDelta;
3398         else
3399             currLogicalTopOffset -= blockDelta;
3400     }
3401 }
3402
3403 static inline LayoutRect frameVisibleRect(RenderObject* renderer)
3404 {
3405     FrameView* frameView = renderer->document()->view();
3406     if (!frameView)
3407         return LayoutRect();
3408
3409     return frameView->visibleContentRect();
3410 }
3411
3412 bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
3413 {
3414     return hitTest(request, result.hitTestPoint(), result);
3415 }
3416
3417 bool RenderLayer::hitTest(const HitTestRequest& request, const HitTestPoint& hitTestPoint, HitTestResult& result)
3418 {
3419     renderer()->document()->updateLayout();
3420     
3421     LayoutRect hitTestArea = renderer()->isRenderFlowThread() ? toRenderFlowThread(renderer())->borderBoxRect() : renderer()->view()->documentRect();
3422     if (!request.ignoreClipping())
3423         hitTestArea.intersect(frameVisibleRect(renderer()));
3424
3425     RenderLayer* insideLayer = hitTestLayer(this, 0, request, result, hitTestArea, hitTestPoint, false);
3426     if (!insideLayer) {
3427         // We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down, 
3428         // return ourselves. We do this so mouse events continue getting delivered after a drag has 
3429         // exited the WebView, and so hit testing over a scrollbar hits the content document.
3430         if ((request.active() || request.release()) && isRootLayer()) {
3431             renderer()->updateHitTestResult(result, toRenderView(renderer())->flipForWritingMode(result.point()));
3432             insideLayer = this;
3433         }
3434     }
3435
3436     // Now determine if the result is inside an anchor - if the urlElement isn't already set.
3437     Node* node = result.innerNode();
3438     if (node && !result.URLElement())
3439         result.setURLElement(static_cast<Element*>(node->enclosingLinkEventParentOrSelf()));
3440
3441     // Next set up the correct :hover/:active state along the new chain.
3442     updateHoverActiveState(request, result);
3443     
3444     // Now return whether we were inside this layer (this will always be true for the root
3445     // layer).
3446     return insideLayer;
3447 }
3448
3449 Node* RenderLayer::enclosingElement() const
3450 {
3451     for (RenderObject* r = renderer(); r; r = r->parent()) {
3452         if (Node* e = r->node())
3453             return e;
3454     }
3455     ASSERT_NOT_REACHED();
3456     return 0;
3457 }
3458
3459 // Compute the z-offset of the point in the transformState.
3460 // This is effectively projecting a ray normal to the plane of ancestor, finding where that
3461 // ray intersects target, and computing the z delta between those two points.
3462 static double computeZOffset(const HitTestingTransformState& transformState)
3463 {
3464     // We got an affine transform, so no z-offset
3465     if (transformState.m_accumulatedTransform.isAffine())
3466         return 0;
3467
3468     // Flatten the point into the target plane
3469     FloatPoint targetPoint = transformState.mappedPoint();
3470     
3471     // Now map the point back through the transform, which computes Z.
3472     FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
3473     return backmappedPoint.z();
3474 }
3475
3476 PassRefPtr<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
3477                                         const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3478                                         const HitTestingTransformState* containerTransformState) const
3479 {
3480     RefPtr<HitTestingTransformState> transformState;
3481     LayoutPoint offset;
3482     if (containerTransformState) {
3483         // If we're already computing transform state, then it's relative to the container (which we know is non-null).
3484         transformState = HitTestingTransformState::create(*containerTransformState);
3485         convertToLayerCoords(containerLayer, offset);
3486     } else {
3487         // If this is the first time we need to make transform state, then base it off of hitTestPoint,
3488         // which is relative to rootLayer.
3489         transformState = HitTestingTransformState::create(hitTestPoint.transformedPoint(), hitTestPoint.transformedRect(), FloatQuad(hitTestRect));
3490         convertToLayerCoords(rootLayer, offset);
3491     }
3492     
3493     RenderObject* containerRenderer = containerLayer ? containerLayer->renderer() : 0;
3494     if (renderer()->shouldUseTransformFromContainer(containerRenderer)) {
3495         TransformationMatrix containerTransform;
3496         renderer()->getTransformFromContainer(containerRenderer, toLayoutSize(offset), containerTransform);
3497         transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
3498     } else {
3499         transformState->translate(offset.x(), offset.y(), HitTestingTransformState::AccumulateTransform);
3500     }
3501     
3502     return transformState;
3503 }
3504
3505
3506 static bool isHitCandidate(const RenderLayer* hitLayer, bool canDepthSort, double* zOffset, const HitTestingTransformState* transformState)
3507 {
3508     if (!hitLayer)
3509         return false;
3510
3511     // The hit layer is depth-sorting with other layers, so just say that it was hit.
3512     if (canDepthSort)
3513         return true;
3514     
3515     // We need to look at z-depth to decide if this layer was hit.
3516     if (zOffset) {
3517         ASSERT(transformState);
3518         // This is actually computing our z, but that's OK because the hitLayer is coplanar with us.
3519         double childZOffset = computeZOffset(*transformState);
3520         if (childZOffset > *zOffset) {
3521             *zOffset = childZOffset;
3522             return true;
3523         }
3524         return false;
3525     }
3526
3527     return true;
3528 }
3529
3530 // hitTestPoint and hitTestRect are relative to rootLayer.
3531 // A 'flattening' layer is one preserves3D() == false.
3532 // transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
3533 // transformState.m_lastPlanarPoint is the hitTestPoint in the plane of the containing flattening layer.
3534 // transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
3535 // 
3536 // If zOffset is non-null (which indicates that the caller wants z offset information), 
3537 //  *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
3538 RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
3539                                        const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, bool appliedTransform,
3540                                        const HitTestingTransformState* transformState, double* zOffset)
3541 {
3542     // The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
3543
3544     bool useTemporaryClipRects = renderer()->view()->frameView()->containsScrollableAreaWithOverlayScrollbars();
3545
3546     // Apply a transform if we have one.
3547     if (transform() && !appliedTransform) {
3548         // Make sure the parent's clip rects have been calculated.
3549         if (parent()) {
3550             ClipRect clipRect = backgroundClipRect(rootLayer, hitTestPoint.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, IncludeOverlayScrollbarSize);
3551             // Go ahead and test the enclosing clip now.
3552             if (!clipRect.intersects(hitTestPoint))
3553                 return 0;
3554         }
3555
3556         // Create a transform state to accumulate this transform.
3557         RefPtr<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3558
3559         // If the transform can't be inverted, then don't hit test this layer at all.
3560         if (!newTransformState->m_accumulatedTransform.isInvertible())
3561             return 0;
3562
3563         // Compute the point and the hit test rect in the coords of this layer by using the values
3564         // from the transformState, which store the point and quad in the coords of the last flattened
3565         // layer, and the accumulated transform which lets up map through preserve-3d layers.
3566         //
3567         // We can't just map hitTestPoint and hitTestRect because they may have been flattened (losing z)
3568         // by our container.
3569         FloatPoint localPoint = newTransformState->mappedPoint();
3570         FloatQuad localPointQuad = newTransformState->mappedQuad();
3571         LayoutRect localHitTestRect = newTransformState->boundsOfMappedArea();
3572         HitTestPoint newHitTestPoint;
3573         if (hitTestPoint.isRectBasedTest())
3574             newHitTestPoint = HitTestPoint(localPoint, localPointQuad);
3575         else
3576             newHitTestPoint = HitTestPoint(localPoint);
3577
3578         // Now do a hit test with the root layer shifted to be us.
3579         return hitTestLayer(this, containerLayer, request, result, localHitTestRect, newHitTestPoint, true, newTransformState.get(), zOffset);
3580     }
3581
3582     // Ensure our lists and 3d status are up-to-date.
3583     updateCompositingAndLayerListsIfNeeded();
3584     update3DTransformedDescendantStatus();
3585
3586     RefPtr<HitTestingTransformState> localTransformState;
3587     if (appliedTransform) {
3588         // We computed the correct state in the caller (above code), so just reference it.
3589         ASSERT(transformState);
3590         localTransformState = const_cast<HitTestingTransformState*>(transformState);
3591     } else if (transformState || m_has3DTransformedDescendant || preserves3D()) {
3592         // We need transform state for the first time, or to offset the container state, so create it here.
3593         localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3594     }
3595
3596     // Check for hit test on backface if backface-visibility is 'hidden'
3597     if (localTransformState && renderer()->style()->backfaceVisibility() == BackfaceVisibilityHidden) {
3598         TransformationMatrix invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
3599         // If the z-vector of the matrix is negative, the back is facing towards the viewer.
3600         if (invertedMatrix.m33() < 0)
3601             return 0;
3602     }
3603
3604     RefPtr<HitTestingTransformState> unflattenedTransformState = localTransformState;
3605     if (localTransformState && !preserves3D()) {
3606         // Keep a copy of the pre-flattening state, for computing z-offsets for the container
3607         unflattenedTransformState = HitTestingTransformState::create(*localTransformState);
3608         // This layer is flattening, so flatten the state passed to descendants.
3609         localTransformState->flatten();
3610     }
3611     
3612     // Calculate the clip rects we should use.
3613     LayoutRect layerBounds;
3614     ClipRect bgRect;
3615     ClipRect fgRect;
3616     ClipRect outlineRect;
3617     calculateRects(rootLayer, hitTestPoint.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, hitTestRect, layerBounds, bgRect, fgRect, outlineRect, IncludeOverlayScrollbarSize);
3618     
3619     // The following are used for keeping track of the z-depth of the hit point of 3d-transformed
3620     // descendants.
3621     double localZOffset = -numeric_limits<double>::infinity();
3622     double* zOffsetForDescendantsPtr = 0;
3623     double* zOffsetForContentsPtr = 0;
3624     
3625     bool depthSortDescendants = false;
3626     if (preserves3D()) {
3627         depthSortDescendants = true;
3628         // Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
3629         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3630         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3631     } else if (m_has3DTransformedDescendant) {
3632         // Flattening layer with 3d children; use a local zOffset pointer to depth-test children and foreground.
3633         depthSortDescendants = true;
3634         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3635         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3636     } else if (zOffset) {
3637         zOffsetForDescendantsPtr = 0;
3638         // Container needs us to give back a z offset for the hit layer.
3639         zOffsetForContentsPtr = zOffset;
3640     }
3641
3642     // This variable tracks which layer the mouse ends up being inside.
3643     RenderLayer* candidateLayer = 0;
3644
3645     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
3646     RenderLayer* hitLayer = hitTestList(posZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3647                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3648     if (hitLayer) {
3649         if (!depthSortDescendants)
3650             return hitLayer;
3651         candidateLayer = hitLayer;
3652     }
3653
3654     // Now check our overflow objects.
3655     hitLayer = hitTestList(m_normalFlowList, rootLayer, request, result, hitTestRect, hitTestPoint,
3656                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3657     if (hitLayer) {
3658         if (!depthSortDescendants)
3659             return hitLayer;
3660         candidateLayer = hitLayer;
3661     }
3662
3663     // Next we want to see if the mouse pos is inside the child RenderObjects of the layer.
3664     if (fgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3665         // Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
3666         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3667         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestDescendants) &&
3668             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3669             if (result.isRectBasedTest())
3670                 result.append(tempResult);
3671             else
3672                 result = tempResult;
3673             if (!depthSortDescendants)
3674                 return this;
3675             // Foreground can depth-sort with descendant layers, so keep this as a candidate.
3676             candidateLayer = this;
3677         } else if (result.isRectBasedTest())
3678             result.append(tempResult);
3679     }
3680
3681     // Now check our negative z-index children.
3682     hitLayer = hitTestList(negZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3683                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3684     if (hitLayer) {
3685         if (!depthSortDescendants)
3686             return hitLayer;
3687         candidateLayer = hitLayer;
3688     }
3689
3690     // If we found a layer, return. Child layers, and foreground always render in front of background.
3691     if (candidateLayer)
3692         return candidateLayer;
3693
3694     if (bgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3695         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3696         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestSelf) &&
3697             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3698             if (result.isRectBasedTest())
3699                 result.append(tempResult);
3700             else
3701                 result = tempResult;
3702             return this;
3703         } else if (result.isRectBasedTest())
3704             result.append(tempResult);
3705     }
3706
3707     return 0;
3708 }
3709
3710 bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const LayoutRect& layerBounds, const HitTestPoint& hitTestPoint, HitTestFilter hitTestFilter) const
3711 {
3712     if (!renderer()->hitTest(request, result, hitTestPoint,
3713                             toLayoutPoint(layerBounds.location() - renderBoxLocation()),
3714                             hitTestFilter)) {
3715         // It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
3716         // a rect-based test.
3717         ASSERT(!result.innerNode() || (result.isRectBasedTest() && result.rectBasedTestResult().size()));
3718         return false;
3719     }
3720
3721     // For positioned generated content, we might still not have a
3722     // node by the time we get to the layer level, since none of
3723     // the content in the layer has an element. So just walk up
3724     // the tree.
3725     if (!result.innerNode() || !result.innerNonSharedNode()) {
3726         Node* e = enclosingElement();
3727         if (!result.innerNode())
3728             result.setInnerNode(e);
3729         if (!result.innerNonSharedNode())
3730             result.setInnerNonSharedNode(e);
3731     }
3732         
3733     return true;
3734 }
3735
3736 RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
3737                                       const HitTestRequest& request, HitTestResult& result,
3738                                       const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3739                                       const HitTestingTransformState* transformState, 
3740                                       double* zOffsetForDescendants, double* zOffset,
3741                                       const HitTestingTransformState* unflattenedTransformState,
3742                                       bool depthSortDescendants)
3743 {
3744     if (!list)
3745         return 0;
3746     
3747     RenderLayer* resultLayer = 0;
3748     for (int i = list->size() - 1; i >= 0; --i) {
3749         RenderLayer* childLayer = list->at(i);
3750         RenderLayer* hitLayer = 0;
3751         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3752         if (childLayer->isPaginated())
3753             hitLayer = hitTestPaginatedChildLayer(childLayer, rootLayer, request, tempResult, hitTestRect, hitTestPoint, transformState, zOffsetForDescendants);
3754         else
3755             hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestPoint, false, transformState, zOffsetForDescendants);
3756
3757         // If it a rect-based test, we can safely append the temporary result since it might had hit
3758         // nodes but not necesserily had hitLayer set.
3759         if (result.isRectBasedTest())
3760             result.append(tempResult);
3761
3762         if (isHitCandidate(hitLayer, depthSortDescendants, zOffset, unflattenedTransformState)) {
3763             resultLayer = hitLayer;
3764             if (!result.isRectBasedTest())
3765                 result = tempResult;
3766             if (!depthSortDescendants)
3767                 break;
3768         }
3769     }
3770
3771     return resultLayer;
3772 }
3773
3774 RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3775                                                      const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset)
3776 {
3777     Vector<RenderLayer*> columnLayers;
3778     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3779     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3780         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3781             columnLayers.append(curr);
3782         if (curr == ancestorLayer)
3783             break;
3784     }
3785
3786     ASSERT(columnLayers.size());
3787     return hitTestChildLayerColumns(childLayer, rootLayer, request, result, hitTestRect, hitTestPoint, transformState, zOffset,
3788                                     columnLayers, columnLayers.size() - 1);
3789 }
3790
3791 RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3792                                                    const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset,
3793                                                    const Vector<RenderLayer*>& columnLayers, size_t columnIndex)
3794 {
3795     RenderBlock* columnBlock = toRenderBlock(columnLayers[columnIndex]->renderer());
3796
3797     ASSERT(columnBlock && columnBlock->hasColumns());
3798     if (!columnBlock || !columnBlock->hasColumns())
3799         return 0;
3800
3801     LayoutPoint layerOffset;
3802     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3803
3804     ColumnInfo* colInfo = columnBlock->columnInfo();
3805     int colCount = columnBlock->columnCount(colInfo);
3806
3807     // We have to go backwards from the last column to the first.
3808     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3809     LayoutUnit logicalLeft = columnBlock->logicalLeftOffsetForContent();
3810     LayoutUnit currLogicalTopOffset = 0;
3811     int i;
3812     for (i = 0; i < colCount; i++) {
3813         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3814         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3815         if (columnBlock->style()->isFlippedBlocksWritingMode())
3816             currLogicalTopOffset += blockDelta;
3817         else
3818             currLogicalTopOffset -= blockDelta;
3819     }
3820     for (i = colCount - 1; i >= 0; i--) {
3821         // For each rect, we clip to the rect, and then we adjust our coords.
3822         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3823         columnBlock->flipForWritingMode(colRect);
3824         LayoutUnit currLogicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - logicalLeft;
3825         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3826         if (columnBlock->style()->isFlippedBlocksWritingMode())
3827             currLogicalTopOffset -= blockDelta;
3828         else
3829             currLogicalTopOffset += blockDelta;
3830
3831         LayoutSize offset;
3832         if (isHorizontal) {
3833             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3834                 offset = LayoutSize(currLogicalLeftOffset, currLogicalTopOffset);
3835             else
3836                 offset = LayoutSize(0, colRect.y() + currLogicalTopOffset - columnBlock->borderTop() - columnBlock->paddingTop());
3837         } else {
3838             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3839                 offset = LayoutSize(currLogicalTopOffset, currLogicalLeftOffset);
3840             else
3841                 offset = LayoutSize(colRect.x() + currLogicalTopOffset - columnBlock->borderLeft() - columnBlock->paddingLeft(), 0);
3842         }
3843
3844         colRect.moveBy(layerOffset);
3845
3846         LayoutRect localClipRect(hitTestRect);
3847         localClipRect.intersect(colRect);
3848
3849         if (!localClipRect.isEmpty() && hitTestPoint.intersects(localClipRect)) {
3850             RenderLayer* hitLayer = 0;
3851             if (!columnIndex) {