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