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