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