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