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