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