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