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