2011-05-11 Simon Fraser <simon.fraser@apple.com>
[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(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 the disableLayoutState() call
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::setHasHorizontalScrollbar(bool hasScrollbar)
1934 {
1935     if (hasScrollbar == (m_hBar != 0))
1936         return;
1937
1938     if (hasScrollbar)
1939         m_hBar = createScrollbar(HorizontalScrollbar);
1940     else
1941         destroyScrollbar(HorizontalScrollbar);
1942
1943     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
1944     if (m_hBar)
1945         m_hBar->styleChanged();
1946     if (m_vBar)
1947         m_vBar->styleChanged();
1948
1949 #if ENABLE(DASHBOARD_SUPPORT)
1950     // Force an update since we know the scrollbars have changed things.
1951     if (renderer()->document()->hasDashboardRegions())
1952         renderer()->document()->setDashboardRegionsDirty(true);
1953 #endif
1954 }
1955
1956 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
1957 {
1958     if (hasScrollbar == (m_vBar != 0))
1959         return;
1960
1961     if (hasScrollbar)
1962         m_vBar = createScrollbar(VerticalScrollbar);
1963     else
1964         destroyScrollbar(VerticalScrollbar);
1965
1966      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
1967     if (m_hBar)
1968         m_hBar->styleChanged();
1969     if (m_vBar)
1970         m_vBar->styleChanged();
1971
1972 #if ENABLE(DASHBOARD_SUPPORT)
1973     // Force an update since we know the scrollbars have changed things.
1974     if (renderer()->document()->hasDashboardRegions())
1975         renderer()->document()->setDashboardRegionsDirty(true);
1976 #endif
1977 }
1978
1979 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
1980 {
1981     if (!m_vBar || (m_vBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
1982         return 0;
1983     return m_vBar->width();
1984 }
1985
1986 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
1987 {
1988     if (!m_hBar || (m_hBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
1989         return 0;
1990     return m_hBar->height();
1991 }
1992
1993 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
1994 {
1995     // Currently the resize corner is always the bottom right corner
1996     IntPoint bottomRight(width(), height());
1997     IntPoint localPoint = absoluteToContents(absolutePoint);
1998     return localPoint - bottomRight;
1999 }
2000
2001 bool RenderLayer::hasOverflowControls() const
2002 {
2003     return m_hBar || m_vBar || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
2004 }
2005
2006 void RenderLayer::positionOverflowControls(int tx, int ty)
2007 {
2008     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2009         return;
2010     
2011     RenderBox* box = renderBox();
2012     if (!box)
2013         return;
2014
2015     const IntRect& borderBox = box->borderBoxRect();
2016     const IntRect& scrollCorner = scrollCornerRect();
2017     IntRect absBounds(borderBox.x() + tx, borderBox.y() + ty, borderBox.width(), borderBox.height());
2018     if (m_vBar)
2019         m_vBar->setFrameRect(IntRect(absBounds.maxX() - box->borderRight() - m_vBar->width(),
2020                                      absBounds.y() + box->borderTop(),
2021                                      m_vBar->width(),
2022                                      absBounds.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height()));
2023
2024     if (m_hBar)
2025         m_hBar->setFrameRect(IntRect(absBounds.x() + box->borderLeft(),
2026                                      absBounds.maxY() - box->borderBottom() - m_hBar->height(),
2027                                      absBounds.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
2028                                      m_hBar->height()));
2029
2030 #if USE(ACCELERATED_COMPOSITING)
2031     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
2032         if (m_hBar) {
2033             layer->setPosition(IntPoint(m_hBar->frameRect().x() - tx, m_hBar->frameRect().y() - ty));
2034             layer->setSize(m_hBar->frameRect().size());
2035         }
2036         layer->setDrawsContent(m_hBar);
2037     }
2038     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2039         if (m_vBar) {
2040             layer->setPosition(IntPoint(m_vBar->frameRect().x() - tx, m_vBar->frameRect().y() - ty));
2041             layer->setSize(m_vBar->frameRect().size());
2042         }
2043         layer->setDrawsContent(m_vBar);
2044     }
2045
2046     if (GraphicsLayer* layer = layerForScrollCorner()) {
2047         const IntRect& scrollCornerAndResizer = scrollCornerAndResizerRect();
2048         layer->setPosition(scrollCornerAndResizer.location());
2049         layer->setSize(scrollCornerAndResizer.size());
2050         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
2051     }
2052 #endif
2053
2054     if (m_scrollCorner)
2055         m_scrollCorner->setFrameRect(scrollCorner);
2056     if (m_resizer)
2057         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
2058 }
2059
2060 int RenderLayer::scrollWidth()
2061 {
2062     if (m_scrollDimensionsDirty)
2063         computeScrollDimensions();
2064     return m_scrollSize.width();
2065 }
2066
2067 int RenderLayer::scrollHeight()
2068 {
2069     if (m_scrollDimensionsDirty)
2070         computeScrollDimensions();
2071     return m_scrollSize.height();
2072 }
2073
2074 int RenderLayer::overflowTop() const
2075 {
2076     RenderBox* box = renderBox();
2077     IntRect overflowRect(box->layoutOverflowRect());
2078     box->flipForWritingMode(overflowRect);
2079     return overflowRect.y();
2080 }
2081
2082 int RenderLayer::overflowBottom() const
2083 {
2084     RenderBox* box = renderBox();
2085     IntRect overflowRect(box->layoutOverflowRect());
2086     box->flipForWritingMode(overflowRect);
2087     return overflowRect.maxY();
2088 }
2089
2090 int RenderLayer::overflowLeft() const
2091 {
2092     RenderBox* box = renderBox();
2093     IntRect overflowRect(box->layoutOverflowRect());
2094     box->flipForWritingMode(overflowRect);
2095     return overflowRect.x();
2096 }
2097
2098 int RenderLayer::overflowRight() const
2099 {
2100     RenderBox* box = renderBox();
2101     IntRect overflowRect(box->layoutOverflowRect());
2102     box->flipForWritingMode(overflowRect);
2103     return overflowRect.maxX();
2104 }
2105
2106 void RenderLayer::computeScrollDimensions(bool* needHBar, bool* needVBar)
2107 {
2108     RenderBox* box = renderBox();
2109     ASSERT(box);
2110     
2111     m_scrollDimensionsDirty = false;
2112
2113     m_scrollOverflow.setWidth(overflowLeft() - box->borderLeft());
2114     m_scrollOverflow.setHeight(overflowTop() - box->borderTop());
2115
2116     m_scrollSize.setWidth(overflowRight() - overflowLeft());
2117     m_scrollSize.setHeight(overflowBottom() - overflowTop());
2118     
2119     m_scrollOrigin = IntPoint(-m_scrollOverflow.width(), -m_scrollOverflow.height());
2120
2121     if (needHBar)
2122         *needHBar = m_scrollSize.width() > box->clientWidth();
2123     if (needVBar)
2124         *needVBar = m_scrollSize.height() > box->clientHeight();
2125 }
2126
2127 void RenderLayer::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
2128 {
2129     if (m_overflowStatusDirty) {
2130         m_horizontalOverflow = horizontalOverflow;
2131         m_verticalOverflow = verticalOverflow;
2132         m_overflowStatusDirty = false;
2133         return;
2134     }
2135     
2136     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
2137     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
2138     
2139     if (horizontalOverflowChanged || verticalOverflowChanged) {
2140         m_horizontalOverflow = horizontalOverflow;
2141         m_verticalOverflow = verticalOverflow;
2142         
2143         if (FrameView* frameView = renderer()->document()->view()) {
2144             frameView->scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow),
2145                 renderer()->node());
2146         }
2147     }
2148 }
2149
2150 void RenderLayer::updateScrollInfoAfterLayout()
2151 {
2152     RenderBox* box = renderBox();
2153     if (!box)
2154         return;
2155
2156     m_scrollDimensionsDirty = true;
2157
2158     bool horizontalOverflow, verticalOverflow;
2159     computeScrollDimensions(&horizontalOverflow, &verticalOverflow);
2160
2161     if (box->style()->overflowX() != OMARQUEE) {
2162         // Layout may cause us to be in an invalid scroll position.  In this case we need
2163         // to pull our scroll offsets back to the max (or push them up to the min).
2164         int newX = max(0, min(scrollXOffset(), scrollWidth() - box->clientWidth()));
2165         int newY = max(0, min(scrollYOffset(), scrollHeight() - box->clientHeight()));
2166         if (newX != scrollXOffset() || newY != scrollYOffset()) {
2167             RenderView* view = renderer()->view();
2168             ASSERT(view);
2169             // scrollToOffset() may call updateLayerPositions(), which doesn't work
2170             // with LayoutState.
2171             // FIXME: Remove the disableLayoutState/enableLayoutState if the above changes.
2172             if (view)
2173                 view->disableLayoutState();
2174             scrollToOffset(newX, newY);
2175             if (view)
2176                 view->enableLayoutState();
2177         }
2178     }
2179
2180     bool haveHorizontalBar = m_hBar;
2181     bool haveVerticalBar = m_vBar;
2182     
2183     // overflow:scroll should just enable/disable.
2184     if (renderer()->style()->overflowX() == OSCROLL)
2185         m_hBar->setEnabled(horizontalOverflow);
2186     if (renderer()->style()->overflowY() == OSCROLL)
2187         m_vBar->setEnabled(verticalOverflow);
2188
2189     // A dynamic change from a scrolling overflow to overflow:hidden means we need to get rid of any
2190     // scrollbars that may be present.
2191     if (renderer()->style()->overflowX() == OHIDDEN && haveHorizontalBar)
2192         setHasHorizontalScrollbar(false);
2193     if (renderer()->style()->overflowY() == OHIDDEN && haveVerticalBar)
2194         setHasVerticalScrollbar(false);
2195     
2196     // overflow:auto may need to lay out again if scrollbars got added/removed.
2197     bool scrollbarsChanged = (box->hasAutoHorizontalScrollbar() && haveHorizontalBar != horizontalOverflow) || 
2198                              (box->hasAutoVerticalScrollbar() && haveVerticalBar != verticalOverflow);    
2199     if (scrollbarsChanged) {
2200         if (box->hasAutoHorizontalScrollbar())
2201             setHasHorizontalScrollbar(horizontalOverflow);
2202         if (box->hasAutoVerticalScrollbar())
2203             setHasVerticalScrollbar(verticalOverflow);
2204
2205 #if ENABLE(DASHBOARD_SUPPORT)
2206         // Force an update since we know the scrollbars have changed things.
2207         if (renderer()->document()->hasDashboardRegions())
2208             renderer()->document()->setDashboardRegionsDirty(true);
2209 #endif
2210
2211         renderer()->repaint();
2212
2213         if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
2214             if (!m_inOverflowRelayout) {
2215                 // Our proprietary overflow: overlay value doesn't trigger a layout.
2216                 m_inOverflowRelayout = true;
2217                 renderer()->setNeedsLayout(true, false);
2218                 if (renderer()->isRenderBlock()) {
2219                     RenderBlock* block = toRenderBlock(renderer());
2220                     block->scrollbarsChanged(box->hasAutoHorizontalScrollbar() && haveHorizontalBar != horizontalOverflow,
2221                                              box->hasAutoVerticalScrollbar() && haveVerticalBar != verticalOverflow);
2222                     block->layoutBlock(true);
2223                 } else
2224                     renderer()->layout();
2225                 m_inOverflowRelayout = false;
2226             }
2227         }
2228     }
2229     
2230     // If overflow:scroll is turned into overflow:auto a bar might still be disabled (Bug 11985).
2231     if (m_hBar && box->hasAutoHorizontalScrollbar())
2232         m_hBar->setEnabled(true);
2233     if (m_vBar && box->hasAutoVerticalScrollbar())
2234         m_vBar->setEnabled(true);
2235
2236     // Set up the range (and page step/line step).
2237     if (m_hBar) {
2238         int clientWidth = box->clientWidth();
2239         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
2240         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2241         m_hBar->setProportion(clientWidth, m_scrollSize.width());
2242     }
2243     if (m_vBar) {
2244         int clientHeight = box->clientHeight();
2245         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
2246         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2247         m_vBar->setProportion(clientHeight, m_scrollSize.height());
2248     }
2249  
2250     RenderView* view = renderer()->view();
2251     view->disableLayoutState();
2252     scrollToOffset(scrollXOffset(), scrollYOffset());
2253     view->enableLayoutState();
2254  
2255     if (renderer()->node() && renderer()->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
2256         updateOverflowStatus(horizontalOverflow, verticalOverflow);
2257 }
2258
2259 void RenderLayer::paintOverflowControls(GraphicsContext* context, int tx, int ty, const IntRect& damageRect, bool paintingOverlayControls)
2260 {
2261     // Don't do anything if we have no overflow.
2262     if (!renderer()->hasOverflowClip())
2263         return;
2264
2265     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
2266     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
2267     // will be false, and we should just tell the root layer that there are overlay scrollbars
2268     // that need to be painted. That will cause the second pass through the layer tree to run,
2269     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
2270     // second pass doesn't need to re-enter the RenderTree to get it right.
2271     if (hasOverlayScrollbars() && !paintingOverlayControls) {
2272         RenderView* renderView = renderer()->view();
2273         renderView->layer()->setContainsDirtyOverlayScrollbars(true);
2274         m_cachedOverlayScrollbarOffset = IntPoint(tx, ty);
2275         renderView->frameView()->setContainsScrollableAreaWithOverlayScrollbars(true);
2276         return;
2277     }
2278
2279     // This check is required to avoid painting custom CSS scrollbars twice.
2280     if (paintingOverlayControls && !hasOverlayScrollbars())
2281         return;
2282
2283     int offsetX = tx;
2284     int offsetY = ty;
2285     if (paintingOverlayControls) {
2286         offsetX = m_cachedOverlayScrollbarOffset.x();
2287         offsetY = m_cachedOverlayScrollbarOffset.y();
2288     }
2289
2290     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
2291     // widgets can move without layout occurring (most notably when you scroll a document that
2292     // contains fixed positioned elements).
2293     positionOverflowControls(offsetX, offsetY);
2294
2295     // Now that we're sure the scrollbars are in the right place, paint them.
2296     if (m_hBar
2297 #if USE(ACCELERATED_COMPOSITING)
2298         && !layerForHorizontalScrollbar()
2299 #endif
2300               )
2301         m_hBar->paint(context, damageRect);
2302     if (m_vBar
2303 #if USE(ACCELERATED_COMPOSITING)
2304         && !layerForVerticalScrollbar()
2305 #endif
2306               )
2307         m_vBar->paint(context, damageRect);
2308
2309 #if USE(ACCELERATED_COMPOSITING)
2310     if (layerForScrollCorner())
2311         return;
2312 #endif
2313
2314     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
2315     // edge of the box.
2316     paintScrollCorner(context, offsetX, offsetY, damageRect);
2317     
2318     // Paint our resizer last, since it sits on top of the scroll corner.
2319     paintResizer(context, offsetX, offsetY, damageRect);
2320 }
2321
2322 void RenderLayer::paintScrollCorner(GraphicsContext* context, int tx, int ty, const IntRect& damageRect)
2323 {
2324     RenderBox* box = renderBox();
2325     ASSERT(box);
2326
2327     IntRect cornerRect = scrollCornerRect();
2328     IntRect absRect = IntRect(cornerRect.x() + tx, cornerRect.y() + ty, cornerRect.width(), cornerRect.height());
2329     if (!absRect.intersects(damageRect))
2330         return;
2331
2332     if (context->updatingControlTints()) {
2333         updateScrollCornerStyle();
2334         return;
2335     }
2336
2337     if (m_scrollCorner) {
2338         m_scrollCorner->paintIntoRect(context, tx, ty, absRect);
2339         return;
2340     }
2341
2342     // We don't want to paint white if we have overlay scrollbars, since we need
2343     // to see what is behind it.
2344     if (!hasOverlayScrollbars())
2345         context->fillRect(absRect, Color::white, box->style()->colorSpace());
2346 }
2347
2348 void RenderLayer::paintResizer(GraphicsContext* context, int tx, int ty, const IntRect& damageRect)
2349 {
2350     if (renderer()->style()->resize() == RESIZE_NONE)
2351         return;
2352
2353     RenderBox* box = renderBox();
2354     ASSERT(box);
2355
2356     IntRect cornerRect = resizerCornerRect(this, box->borderBoxRect());
2357     IntRect absRect = IntRect(cornerRect.x() + tx, cornerRect.y() + ty, cornerRect.width(), cornerRect.height());
2358     if (!absRect.intersects(damageRect))
2359         return;
2360
2361     if (context->updatingControlTints()) {
2362         updateResizerStyle();
2363         return;
2364     }
2365     
2366     if (m_resizer) {
2367         m_resizer->paintIntoRect(context, tx, ty, absRect);
2368         return;
2369     }
2370
2371     // Paint the resizer control.
2372     DEFINE_STATIC_LOCAL(RefPtr<Image>, resizeCornerImage, (Image::loadPlatformResource("textAreaResizeCorner")));
2373     IntPoint imagePoint(absRect.maxX() - resizeCornerImage->width(), absRect.maxY() - resizeCornerImage->height());
2374     context->drawImage(resizeCornerImage.get(), box->style()->colorSpace(), imagePoint);
2375
2376     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
2377     // Clipping will exclude the right and bottom edges of this frame.
2378     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
2379         GraphicsContextStateSaver stateSaver(*context);
2380         context->clip(absRect);
2381         IntRect largerCorner = absRect;
2382         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
2383         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
2384         context->setStrokeThickness(1.0f);
2385         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
2386         context->drawRect(largerCorner);
2387     }
2388 }
2389
2390 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
2391 {
2392     if (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE)
2393         return false;
2394     
2395     RenderBox* box = renderBox();
2396     ASSERT(box);
2397
2398     IntPoint localPoint = absoluteToContents(absolutePoint);
2399
2400     IntRect localBounds(0, 0, box->width(), box->height());
2401     return resizerCornerRect(this, localBounds).contains(localPoint);
2402 }
2403     
2404 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
2405 {
2406     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2407         return false;
2408
2409     RenderBox* box = renderBox();
2410     ASSERT(box);
2411     
2412     IntRect resizeControlRect;
2413     if (renderer()->style()->resize() != RESIZE_NONE) {
2414         resizeControlRect = resizerCornerRect(this, box->borderBoxRect());
2415         if (resizeControlRect.contains(localPoint))
2416             return true;
2417     }
2418
2419     int resizeControlSize = max(resizeControlRect.height(), 0);
2420
2421     if (m_vBar) {
2422         IntRect vBarRect(box->width() - box->borderRight() - m_vBar->width(), 
2423                          box->borderTop(),
2424                          m_vBar->width(),
2425                          box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
2426         if (vBarRect.contains(localPoint)) {
2427             result.setScrollbar(m_vBar.get());
2428             return true;
2429         }
2430     }
2431
2432     resizeControlSize = max(resizeControlRect.width(), 0);
2433     if (m_hBar) {
2434         IntRect hBarRect(box->borderLeft(),
2435                          box->height() - box->borderBottom() - m_hBar->height(),
2436                          box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
2437                          m_hBar->height());
2438         if (hBarRect.contains(localPoint)) {
2439             result.setScrollbar(m_hBar.get());
2440             return true;
2441         }
2442     }
2443
2444     return false;
2445 }
2446
2447 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
2448 {
2449     return ScrollableArea::scroll(direction, granularity, multiplier);
2450 }
2451
2452 void RenderLayer::paint(GraphicsContext* p, const IntRect& damageRect, PaintBehavior paintBehavior, RenderObject *paintingRoot)
2453 {
2454     OverlapTestRequestMap overlapTestRequests;
2455     paintLayer(this, p, damageRect, paintBehavior, paintingRoot, &overlapTestRequests);
2456     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2457     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
2458         it->first->setOverlapTestResult(false);
2459 }
2460
2461 void RenderLayer::paintOverlayScrollbars(GraphicsContext* p, const IntRect& damageRect, PaintBehavior paintBehavior, RenderObject *paintingRoot)
2462 {
2463     if (!m_containsDirtyOverlayScrollbars)
2464         return;
2465     paintLayer(this, p, damageRect, paintBehavior, paintingRoot, 0, PaintLayerHaveTransparency | PaintLayerTemporaryClipRects 
2466                | PaintLayerPaintingOverlayScrollbars);
2467     m_containsDirtyOverlayScrollbars = false;
2468 }
2469
2470 static void setClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
2471 {
2472     if (paintDirtyRect == clipRect)
2473         return;
2474     p->save();
2475     p->clip(clipRect);
2476 }
2477
2478 static void restoreClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
2479 {
2480     if (paintDirtyRect == clipRect)
2481         return;
2482     p->restore();
2483 }
2484
2485 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
2486 {
2487     Vector<OverlapTestRequestClient*> overlappedRequestClients;
2488     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2489     IntRect boundingBox = layer->boundingBox(rootLayer);
2490     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
2491         if (!boundingBox.intersects(it->second))
2492             continue;
2493
2494         it->first->setOverlapTestResult(true);
2495         overlappedRequestClients.append(it->first);
2496     }
2497     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
2498         overlapTestRequests.remove(overlappedRequestClients[i]);
2499 }
2500
2501 #if USE(ACCELERATED_COMPOSITING)
2502 static bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
2503 {
2504     return paintingReflection && !layer->has3DTransform();
2505 }
2506 #endif
2507
2508 void RenderLayer::paintLayer(RenderLayer* rootLayer, GraphicsContext* p,
2509                         const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2510                         RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2511                         PaintLayerFlags paintFlags)
2512 {
2513 #if USE(ACCELERATED_COMPOSITING)
2514     if (isComposited()) {
2515         // The updatingControlTints() painting pass goes through compositing layers,
2516         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
2517         if (p->updatingControlTints() || (paintBehavior & PaintBehaviorFlattenCompositingLayers))
2518             paintFlags |= PaintLayerTemporaryClipRects;
2519         else if (!backing()->paintingGoesToWindow() && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)) {
2520             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
2521             return;
2522         }
2523     }
2524 #endif
2525
2526     // Avoid painting layers when stylesheets haven't loaded.  This eliminates FOUC.
2527     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2528     // will do a full repaint().
2529     if (renderer()->document()->didLayoutWithPendingStylesheets() && !renderer()->isRenderView() && !renderer()->isRoot())
2530         return;
2531     
2532     // If this layer is totally invisible then there is nothing to paint.
2533     if (!renderer()->opacity())
2534         return;
2535
2536     if (paintsWithTransparency(paintBehavior))
2537         paintFlags |= PaintLayerHaveTransparency;
2538
2539     // Apply a transform if we have one.  A reflection is considered to be a transform, since it is a flip and a translate.
2540     if (paintsWithTransform(paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
2541         TransformationMatrix layerTransform = renderableTransform(paintBehavior);
2542         // If the transform can't be inverted, then don't paint anything.
2543         if (!layerTransform.isInvertible())
2544             return;
2545
2546         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
2547         // layer from the parent now, assuming there is a parent
2548         if (paintFlags & PaintLayerHaveTransparency) {
2549             if (parent())
2550                 parent()->beginTransparencyLayers(p, rootLayer, paintBehavior);
2551             else
2552                 beginTransparencyLayers(p, rootLayer, paintBehavior);
2553         }
2554
2555         // Make sure the parent's clip rects have been calculated.
2556         IntRect clipRect = paintDirtyRect;
2557         if (parent()) {
2558             clipRect = backgroundClipRect(rootLayer, paintFlags & PaintLayerTemporaryClipRects);
2559             clipRect.intersect(paintDirtyRect);
2560         }
2561         
2562         // Push the parent coordinate space's clip.
2563         setClip(p, paintDirtyRect, clipRect);
2564
2565         // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
2566         // This involves subtracting out the position of the layer in our current coordinate space.
2567         int x = 0;
2568         int y = 0;
2569         convertToLayerCoords(rootLayer, x, y);
2570         TransformationMatrix transform(layerTransform);
2571         transform.translateRight(x, y);
2572         
2573         // Apply the transform.
2574         {
2575             GraphicsContextStateSaver stateSaver(*p);
2576             p->concatCTM(transform.toAffineTransform());
2577
2578             // Now do a paint with the root layer shifted to be us.
2579             paintLayer(this, p, transform.inverse().mapRect(paintDirtyRect), paintBehavior, paintingRoot, overlapTestRequests, paintFlags | PaintLayerAppliedTransform);
2580         }        
2581
2582         // Restore the clip.
2583         restoreClip(p, paintDirtyRect, clipRect);
2584         
2585         return;
2586     }
2587
2588     PaintLayerFlags localPaintFlags = paintFlags & ~PaintLayerAppliedTransform;
2589     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
2590
2591     // Paint the reflection first if we have one.
2592     if (m_reflection && !m_paintingInsideReflection) {
2593         // Mark that we are now inside replica painting.
2594         m_paintingInsideReflection = true;
2595         reflectionLayer()->paintLayer(rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags | PaintLayerPaintingReflection);
2596         m_paintingInsideReflection = false;
2597     }
2598
2599     // Calculate the clip rects we should use.
2600     IntRect layerBounds, damageRect, clipRectToApply, outlineRect;
2601     calculateRects(rootLayer, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect, localPaintFlags & PaintLayerTemporaryClipRects);
2602     int x = layerBounds.x();
2603     int y = layerBounds.y();
2604     int tx = x - renderBoxX();
2605     int ty = y - renderBoxY();
2606                              
2607     // Ensure our lists are up-to-date.
2608     updateCompositingAndLayerListsIfNeeded();
2609
2610     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
2611     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
2612     
2613     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
2614     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
2615     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
2616     // so it will be tested against as we descend through the renderers.
2617     RenderObject* paintingRootForRenderer = 0;
2618     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
2619         paintingRootForRenderer = paintingRoot;
2620
2621     if (overlapTestRequests && isSelfPaintingLayer())
2622         performOverlapTests(*overlapTestRequests, rootLayer, this);
2623
2624     bool paintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
2625
2626     // We want to paint our layer, but only if we intersect the damage rect.
2627     bool shouldPaint = intersectsDamageRect(layerBounds, damageRect, rootLayer) && m_hasVisibleContent && isSelfPaintingLayer();
2628     if (shouldPaint && !selectionOnly && !damageRect.isEmpty() && !paintingOverlayScrollbars) {
2629         // Begin transparency layers lazily now that we know we have to paint something.
2630         if (haveTransparency)
2631             beginTransparencyLayers(p, rootLayer, paintBehavior);
2632         
2633         // Paint our background first, before painting any child layers.
2634         // Establish the clip used to paint our background.
2635         setClip(p, paintDirtyRect, damageRect);
2636
2637         // Paint the background.
2638         PaintInfo paintInfo(p, damageRect, PaintPhaseBlockBackground, false, paintingRootForRenderer, 0);
2639         renderer()->paint(paintInfo, tx, ty);
2640
2641         // Restore the clip.
2642         restoreClip(p, paintDirtyRect, damageRect);
2643     }
2644
2645     // Now walk the sorted list of children with negative z-indices.
2646     paintList(m_negZOrderList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2647
2648     // Now establish the appropriate clip and paint our child RenderObjects.
2649     if (shouldPaint && !clipRectToApply.isEmpty() && !paintingOverlayScrollbars) {
2650         // Begin transparency layers lazily now that we know we have to paint something.
2651         if (haveTransparency)
2652             beginTransparencyLayers(p, rootLayer, paintBehavior);
2653
2654         // Set up the clip used when painting our children.
2655         setClip(p, paintDirtyRect, clipRectToApply);
2656         PaintInfo paintInfo(p, clipRectToApply, 
2657                                           selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
2658                                           forceBlackText, paintingRootForRenderer, 0);
2659         renderer()->paint(paintInfo, tx, ty);
2660         if (!selectionOnly) {
2661             paintInfo.phase = PaintPhaseFloat;
2662             renderer()->paint(paintInfo, tx, ty);
2663             paintInfo.phase = PaintPhaseForeground;
2664             paintInfo.overlapTestRequests = overlapTestRequests;
2665             renderer()->paint(paintInfo, tx, ty);
2666             paintInfo.phase = PaintPhaseChildOutlines;
2667             renderer()->paint(paintInfo, tx, ty);
2668         }
2669
2670         // Now restore our clip.
2671         restoreClip(p, paintDirtyRect, clipRectToApply);
2672     }
2673     
2674     if (!outlineRect.isEmpty() && isSelfPaintingLayer() && !paintingOverlayScrollbars) {
2675         // Paint our own outline
2676         PaintInfo paintInfo(p, outlineRect, PaintPhaseSelfOutline, false, paintingRootForRenderer, 0);
2677         setClip(p, paintDirtyRect, outlineRect);
2678         renderer()->paint(paintInfo, tx, ty);
2679         restoreClip(p, paintDirtyRect, outlineRect);
2680     }
2681     
2682     // Paint any child layers that have overflow.
2683     paintList(m_normalFlowList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2684     
2685     // Now walk the sorted list of children with positive z-indices.
2686     paintList(m_posZOrderList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2687         
2688     if (renderer()->hasMask() && shouldPaint && !selectionOnly && !damageRect.isEmpty() && !paintingOverlayScrollbars) {
2689         setClip(p, paintDirtyRect, damageRect);
2690
2691         // Paint the mask.
2692         PaintInfo paintInfo(p, damageRect, PaintPhaseMask, false, paintingRootForRenderer, 0);
2693         renderer()->paint(paintInfo, tx, ty);
2694         
2695         // Restore the clip.
2696         restoreClip(p, paintDirtyRect, damageRect);
2697     }
2698
2699     if (paintingOverlayScrollbars) {
2700         setClip(p, paintDirtyRect, damageRect);
2701         paintOverflowControls(p, tx, ty, damageRect, true);
2702         restoreClip(p, paintDirtyRect, damageRect);
2703     }
2704
2705     // End our transparency layer
2706     if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
2707         p->endTransparencyLayer();
2708         p->restore();
2709         m_usedTransparency = false;
2710     }
2711 }
2712
2713 void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* p,
2714                             const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2715                             RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2716                             PaintLayerFlags paintFlags)
2717 {
2718     if (!list)
2719         return;
2720     
2721     for (size_t i = 0; i < list->size(); ++i) {
2722         RenderLayer* childLayer = list->at(i);
2723         if (!childLayer->isPaginated())
2724             childLayer->paintLayer(rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2725         else
2726             paintPaginatedChildLayer(childLayer, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2727     }
2728 }
2729
2730 void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
2731                                            const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2732                                            RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2733                                            PaintLayerFlags paintFlags)
2734 {
2735     // We need to do multiple passes, breaking up our child layer into strips.
2736     Vector<RenderLayer*> columnLayers;
2737     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
2738     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
2739         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
2740             columnLayers.append(curr);
2741         if (curr == ancestorLayer)
2742             break;
2743     }
2744
2745     ASSERT(columnLayers.size());
2746     
2747     paintChildLayerIntoColumns(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags, columnLayers, columnLayers.size() - 1);
2748 }
2749
2750 void RenderLayer::paintChildLayerIntoColumns(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
2751                                              const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2752                                              RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2753                                              PaintLayerFlags paintFlags, const Vector<RenderLayer*>& columnLayers, size_t colIndex)
2754 {
2755     RenderBlock* columnBlock = toRenderBlock(columnLayers[colIndex]->renderer());
2756
2757     ASSERT(columnBlock && columnBlock->hasColumns());
2758     if (!columnBlock || !columnBlock->hasColumns())
2759         return;
2760     
2761     int layerX = 0;
2762     int layerY = 0;
2763     columnBlock->layer()->convertToLayerCoords(rootLayer, layerX, layerY);
2764     
2765     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
2766
2767     ColumnInfo* colInfo = columnBlock->columnInfo();
2768     unsigned colCount = columnBlock->columnCount(colInfo);
2769     int currLogicalTopOffset = 0;
2770     for (unsigned i = 0; i < colCount; i++) {
2771         // For each rect, we clip to the rect, and then we adjust our coords.
2772         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
2773         columnBlock->flipForWritingMode(colRect);
2774         int logicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - columnBlock->logicalLeftOffsetForContent();
2775         IntSize offset = isHorizontal ? IntSize(logicalLeftOffset, currLogicalTopOffset) : IntSize(currLogicalTopOffset, logicalLeftOffset);
2776
2777         colRect.move(layerX, layerY);
2778
2779         IntRect localDirtyRect(paintDirtyRect);
2780         localDirtyRect.intersect(colRect);
2781         
2782         if (!localDirtyRect.isEmpty()) {
2783             GraphicsContextStateSaver stateSaver(*context);
2784             
2785             // Each strip pushes a clip, since column boxes are specified as being
2786             // like overflow:hidden.
2787             context->clip(colRect);
2788
2789             if (!colIndex) {
2790                 // Apply a translation transform to change where the layer paints.
2791                 TransformationMatrix oldTransform;
2792                 bool oldHasTransform = childLayer->transform();
2793                 if (oldHasTransform)
2794                     oldTransform = *childLayer->transform();
2795                 TransformationMatrix newTransform(oldTransform);
2796                 newTransform.translateRight(offset.width(), offset.height());
2797                 
2798                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
2799                 childLayer->paintLayer(rootLayer, context, localDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2800                 if (oldHasTransform)
2801                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
2802                 else
2803                     childLayer->m_transform.clear();
2804             } else {
2805                 // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
2806                 // This involves subtracting out the position of the layer in our current coordinate space.
2807                 int childX = 0;
2808                 int childY = 0;
2809                 columnLayers[colIndex - 1]->convertToLayerCoords(rootLayer, childX, childY);
2810                 TransformationMatrix transform;
2811                 transform.translateRight(childX + offset.width(), childY + offset.height());
2812                 
2813                 // Apply the transform.
2814                 context->concatCTM(transform.toAffineTransform());
2815
2816                 // Now do a paint with the root layer shifted to be the next multicol block.
2817                 paintChildLayerIntoColumns(childLayer, columnLayers[colIndex - 1], context, transform.inverse().mapRect(localDirtyRect), paintBehavior, 
2818                                            paintingRoot, overlapTestRequests, paintFlags, 
2819                                            columnLayers, colIndex - 1);
2820             }
2821         }
2822
2823         // Move to the next position.
2824         int blockDelta = isHorizontal ? colRect.height() : colRect.width();
2825         if (columnBlock->style()->isFlippedBlocksWritingMode())
2826             currLogicalTopOffset += blockDelta;
2827         else
2828             currLogicalTopOffset -= blockDelta;
2829     }
2830 }
2831
2832 static inline IntRect frameVisibleRect(RenderObject* renderer)
2833 {
2834     FrameView* frameView = renderer->document()->view();
2835     if (!frameView)
2836         return IntRect();
2837
2838     return frameView->visibleContentRect();
2839 }
2840
2841 bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
2842 {
2843     renderer()->document()->updateLayout();
2844     
2845     IntRect hitTestArea = renderer()->view()->documentRect();
2846     if (!request.ignoreClipping())
2847         hitTestArea.intersect(frameVisibleRect(renderer()));
2848
2849     RenderLayer* insideLayer = hitTestLayer(this, 0, request, result, hitTestArea, result.point(), false);
2850     if (!insideLayer) {
2851         // We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down, 
2852         // return ourselves. We do this so mouse events continue getting delivered after a drag has 
2853         // exited the WebView, and so hit testing over a scrollbar hits the content document.
2854         if ((request.active() || request.mouseUp()) && renderer()->isRenderView()) {
2855             renderer()->updateHitTestResult(result, result.point());
2856             insideLayer = this;
2857         }
2858     }
2859
2860     // Now determine if the result is inside an anchor - if the urlElement isn't already set.
2861     Node* node = result.innerNode();
2862     if (node && !result.URLElement())
2863         result.setURLElement(static_cast<Element*>(node->enclosingLinkEventParentOrSelf()));
2864
2865     // Next set up the correct :hover/:active state along the new chain.
2866     updateHoverActiveState(request, result);
2867     
2868     // Now return whether we were inside this layer (this will always be true for the root
2869     // layer).
2870     return insideLayer;
2871 }
2872
2873 Node* RenderLayer::enclosingElement() const
2874 {
2875     for (RenderObject* r = renderer(); r; r = r->parent()) {
2876         if (Node* e = r->node())
2877             return e;
2878     }
2879     ASSERT_NOT_REACHED();
2880     return 0;
2881 }
2882
2883 // Compute the z-offset of the point in the transformState.
2884 // This is effectively projecting a ray normal to the plane of ancestor, finding where that
2885 // ray intersects target, and computing the z delta between those two points.
2886 static double computeZOffset(const HitTestingTransformState& transformState)
2887 {
2888     // We got an affine transform, so no z-offset
2889     if (transformState.m_accumulatedTransform.isAffine())
2890         return 0;
2891
2892     // Flatten the point into the target plane
2893     FloatPoint targetPoint = transformState.mappedPoint();
2894     
2895     // Now map the point back through the transform, which computes Z.
2896     FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
2897     return backmappedPoint.z();
2898 }
2899
2900 PassRefPtr<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
2901                                         const IntRect& hitTestRect, const IntPoint& hitTestPoint,
2902                                         const HitTestingTransformState* containerTransformState) const
2903 {
2904     RefPtr<HitTestingTransformState> transformState;
2905     int offsetX = 0;
2906     int offsetY = 0;
2907     if (containerTransformState) {
2908         // If we're already computing transform state, then it's relative to the container (which we know is non-null).
2909         transformState = HitTestingTransformState::create(*containerTransformState);
2910         convertToLayerCoords(containerLayer, offsetX, offsetY);
2911     } else {
2912         // If this is the first time we need to make transform state, then base it off of hitTestPoint,
2913         // which is relative to rootLayer.
2914         transformState = HitTestingTransformState::create(hitTestPoint, FloatQuad(hitTestRect));
2915         convertToLayerCoords(rootLayer, offsetX, offsetY);
2916     }
2917     
2918     RenderObject* containerRenderer = containerLayer ? containerLayer->renderer() : 0;
2919     if (renderer()->shouldUseTransformFromContainer(containerRenderer)) {
2920         TransformationMatrix containerTransform;
2921         renderer()->getTransformFromContainer(containerRenderer, IntSize(offsetX, offsetY), containerTransform);
2922         transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
2923     } else {
2924         transformState->translate(offsetX, offsetY, HitTestingTransformState::AccumulateTransform);
2925     }
2926     
2927     return transformState;
2928 }
2929
2930
2931 static bool isHitCandidate(const RenderLayer* hitLayer, bool canDepthSort, double* zOffset, const HitTestingTransformState* transformState)
2932 {
2933     if (!hitLayer)
2934         return false;
2935
2936     // The hit layer is depth-sorting with other layers, so just say that it was hit.
2937     if (canDepthSort)
2938         return true;
2939     
2940     // We need to look at z-depth to decide if this layer was hit.
2941     if (zOffset) {
2942         ASSERT(transformState);
2943         // This is actually computing our z, but that's OK because the hitLayer is coplanar with us.
2944         double childZOffset = computeZOffset(*transformState);
2945         if (childZOffset > *zOffset) {
2946             *zOffset = childZOffset;
2947             return true;
2948         }
2949         return false;
2950     }
2951
2952     return true;
2953 }
2954
2955 // hitTestPoint and hitTestRect are relative to rootLayer.
2956 // A 'flattening' layer is one preserves3D() == false.
2957 // transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
2958 // transformState.m_lastPlanarPoint is the hitTestPoint in the plane of the containing flattening layer.
2959 // transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
2960 // 
2961 // If zOffset is non-null (which indicates that the caller wants z offset information), 
2962 //  *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
2963 RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
2964                                        const IntRect& hitTestRect, const IntPoint& hitTestPoint, bool appliedTransform,
2965                                        const HitTestingTransformState* transformState, double* zOffset)
2966 {
2967     // The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
2968
2969     bool useTemporaryClipRects = false;
2970 #if USE(ACCELERATED_COMPOSITING)
2971     useTemporaryClipRects = compositor()->inCompositingMode();
2972 #endif
2973     useTemporaryClipRects |= renderer()->view()->frameView()->containsScrollableAreaWithOverlayScrollbars();
2974
2975     IntRect hitTestArea = result.rectForPoint(hitTestPoint);
2976
2977     // Apply a transform if we have one.
2978     if (transform() && !appliedTransform) {
2979         // Make sure the parent's clip rects have been calculated.
2980         if (parent()) {
2981             IntRect clipRect = backgroundClipRect(rootLayer, useTemporaryClipRects, IncludeOverlayScrollbarSize);
2982             // Go ahead and test the enclosing clip now.
2983             if (!clipRect.intersects(hitTestArea))
2984                 return 0;
2985         }
2986
2987         // Create a transform state to accumulate this transform.
2988         RefPtr<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
2989
2990         // If the transform can't be inverted, then don't hit test this layer at all.
2991         if (!newTransformState->m_accumulatedTransform.isInvertible())
2992             return 0;
2993
2994         // Compute the point and the hit test rect in the coords of this layer by using the values
2995         // from the transformState, which store the point and quad in the coords of the last flattened
2996         // layer, and the accumulated transform which lets up map through preserve-3d layers.
2997         //
2998         // We can't just map hitTestPoint and hitTestRect because they may have been flattened (losing z)
2999         // by our container.
3000         IntPoint localPoint = roundedIntPoint(newTransformState->mappedPoint());
3001         IntRect localHitTestRect;
3002 #if USE(ACCELERATED_COMPOSITING)
3003         if (isComposited()) {
3004             // It doesn't make sense to project hitTestRect into the plane of this layer, so use the same bounds we use for painting.
3005             localHitTestRect = backing()->compositedBounds();
3006         } else
3007 #endif
3008             localHitTestRect = newTransformState->mappedQuad().enclosingBoundingBox();
3009
3010         // Now do a hit test with the root layer shifted to be us.
3011         return hitTestLayer(this, containerLayer, request, result, localHitTestRect, localPoint, true, newTransformState.get(), zOffset);
3012     }
3013
3014     // Ensure our lists and 3d status are up-to-date.
3015     updateCompositingAndLayerListsIfNeeded();
3016     update3DTransformedDescendantStatus();
3017     
3018     RefPtr<HitTestingTransformState> localTransformState;
3019     if (appliedTransform) {
3020         // We computed the correct state in the caller (above code), so just reference it.
3021         ASSERT(transformState);
3022         localTransformState = const_cast<HitTestingTransformState*>(transformState);
3023     } else if (transformState || m_has3DTransformedDescendant || preserves3D()) {
3024         // We need transform state for the first time, or to offset the container state, so create it here.
3025         localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3026     }
3027
3028     // Check for hit test on backface if backface-visibility is 'hidden'
3029     if (localTransformState && renderer()->style()->backfaceVisibility() == BackfaceVisibilityHidden) {
3030         TransformationMatrix invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
3031         // If the z-vector of the matrix is negative, the back is facing towards the viewer.
3032         if (invertedMatrix.m33() < 0)
3033             return 0;
3034     }
3035
3036     RefPtr<HitTestingTransformState> unflattenedTransformState = localTransformState;
3037     if (localTransformState && !preserves3D()) {
3038         // Keep a copy of the pre-flattening state, for computing z-offsets for the container
3039         unflattenedTransformState = HitTestingTransformState::create(*localTransformState);
3040         // This layer is flattening, so flatten the state passed to descendants.
3041         localTransformState->flatten();
3042     }
3043     
3044     // Calculate the clip rects we should use.
3045     IntRect layerBounds;
3046     IntRect bgRect;
3047     IntRect fgRect;
3048     IntRect outlineRect;
3049     calculateRects(rootLayer, hitTestRect, layerBounds, bgRect, fgRect, outlineRect, useTemporaryClipRects, IncludeOverlayScrollbarSize);
3050     
3051     // The following are used for keeping track of the z-depth of the hit point of 3d-transformed
3052     // descendants.
3053     double localZOffset = -numeric_limits<double>::infinity();
3054     double* zOffsetForDescendantsPtr = 0;
3055     double* zOffsetForContentsPtr = 0;
3056     
3057     bool depthSortDescendants = false;
3058     if (preserves3D()) {
3059         depthSortDescendants = true;
3060         // Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
3061         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3062         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3063     } else if (m_has3DTransformedDescendant) {
3064         // Flattening layer with 3d children; use a local zOffset pointer to depth-test children and foreground.
3065         depthSortDescendants = true;
3066         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3067         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3068     } else if (zOffset) {
3069         zOffsetForDescendantsPtr = 0;
3070         // Container needs us to give back a z offset for the hit layer.
3071         zOffsetForContentsPtr = zOffset;
3072     }
3073     
3074     // This variable tracks which layer the mouse ends up being inside. 
3075     RenderLayer* candidateLayer = 0;
3076
3077     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
3078     RenderLayer* hitLayer = hitTestList(m_posZOrderList, rootLayer, request, result, hitTestRect, hitTestPoint,
3079                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3080     if (hitLayer) {
3081         if (!depthSortDescendants)
3082             return hitLayer;
3083         candidateLayer = hitLayer;
3084     }
3085
3086     // Now check our overflow objects.
3087     hitLayer = hitTestList(m_normalFlowList, rootLayer, request, result, hitTestRect, hitTestPoint,
3088                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3089     if (hitLayer) {
3090         if (!depthSortDescendants)
3091             return hitLayer;
3092         candidateLayer = hitLayer;
3093     }
3094
3095     // Next we want to see if the mouse pos is inside the child RenderObjects of the layer.
3096     if (fgRect.intersects(hitTestArea) && isSelfPaintingLayer()) {
3097         // Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
3098         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3099         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestDescendants) &&
3100             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3101             if (result.isRectBasedTest())
3102                 result.append(tempResult);
3103             else
3104                 result = tempResult;
3105             if (!depthSortDescendants)
3106                 return this;
3107             // Foreground can depth-sort with descendant layers, so keep this as a candidate.
3108             candidateLayer = this;
3109         } else if (result.isRectBasedTest())
3110             result.append(tempResult);
3111     }
3112
3113     // Now check our negative z-index children.
3114     hitLayer = hitTestList(m_negZOrderList, rootLayer, request, result, hitTestRect, hitTestPoint,
3115                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3116     if (hitLayer) {
3117         if (!depthSortDescendants)
3118             return hitLayer;
3119         candidateLayer = hitLayer;
3120     }
3121
3122     // If we found a layer, return. Child layers, and foreground always render in front of background.
3123     if (candidateLayer)
3124         return candidateLayer;
3125
3126     if (bgRect.intersects(hitTestArea) && isSelfPaintingLayer()) {
3127         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3128         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestSelf) &&
3129             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3130             if (result.isRectBasedTest())
3131                 result.append(tempResult);
3132             else
3133                 result = tempResult;
3134             return this;
3135         } else if (result.isRectBasedTest())
3136             result.append(tempResult);
3137     }
3138     
3139     return 0;
3140 }
3141
3142 bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const IntRect& layerBounds, const IntPoint& hitTestPoint, HitTestFilter hitTestFilter) const
3143 {
3144     if (!renderer()->hitTest(request, result, hitTestPoint,
3145                             layerBounds.x() - renderBoxX(),
3146                             layerBounds.y() - renderBoxY(), 
3147                             hitTestFilter)) {
3148         // It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
3149         // a rect-based test.
3150         ASSERT(!result.innerNode() || (result.isRectBasedTest() && result.rectBasedTestResult().size()));
3151         return false;
3152     }
3153
3154     // For positioned generated content, we might still not have a
3155     // node by the time we get to the layer level, since none of
3156     // the content in the layer has an element. So just walk up
3157     // the tree.
3158     if (!result.innerNode() || !result.innerNonSharedNode()) {
3159         Node* e = enclosingElement();
3160         if (!result.innerNode())
3161             result.setInnerNode(e);
3162         if (!result.innerNonSharedNode())
3163             result.setInnerNonSharedNode(e);
3164     }
3165         
3166     return true;
3167 }
3168
3169 RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
3170                                       const HitTestRequest& request, HitTestResult& result,
3171                                       const IntRect& hitTestRect, const IntPoint& hitTestPoint,
3172                                       const HitTestingTransformState* transformState, 
3173                                       double* zOffsetForDescendants, double* zOffset,
3174                                       const HitTestingTransformState* unflattenedTransformState,
3175                                       bool depthSortDescendants)
3176 {
3177     if (!list)
3178         return 0;
3179     
3180     RenderLayer* resultLayer = 0;
3181     for (int i = list->size() - 1; i >= 0; --i) {
3182         RenderLayer* childLayer = list->at(i);
3183         RenderLayer* hitLayer = 0;
3184         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3185         if (childLayer->isPaginated())
3186             hitLayer = hitTestPaginatedChildLayer(childLayer, rootLayer, request, tempResult, hitTestRect, hitTestPoint, transformState, zOffsetForDescendants);
3187         else
3188             hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestPoint, false, transformState, zOffsetForDescendants);
3189
3190         // If it a rect-based test, we can safely append the temporary result since it might had hit
3191         // nodes but not necesserily had hitLayer set.
3192         if (result.isRectBasedTest())
3193             result.append(tempResult);
3194
3195         if (isHitCandidate(hitLayer, depthSortDescendants, zOffset, unflattenedTransformState)) {
3196             resultLayer = hitLayer;
3197             if (!result.isRectBasedTest())
3198                 result = tempResult;
3199             if (!depthSortDescendants)
3200                 break;
3201         }
3202     }
3203     
3204     return resultLayer;
3205 }
3206
3207 RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3208                                                      const IntRect& hitTestRect, const IntPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset)
3209 {
3210     Vector<RenderLayer*> columnLayers;
3211     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3212     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3213         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3214             columnLayers.append(curr);
3215         if (curr == ancestorLayer)
3216             break;
3217     }
3218
3219     ASSERT(columnLayers.size());
3220     return hitTestChildLayerColumns(childLayer, rootLayer, request, result, hitTestRect, hitTestPoint, transformState, zOffset,
3221                                     columnLayers, columnLayers.size() - 1);
3222 }
3223
3224 RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3225                                                    const IntRect& hitTestRect, const IntPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset,
3226                                                    const Vector<RenderLayer*>& columnLayers, size_t columnIndex)
3227 {
3228     RenderBlock* columnBlock = toRenderBlock(columnLayers[columnIndex]->renderer());
3229
3230     ASSERT(columnBlock && columnBlock->hasColumns());
3231     if (!columnBlock || !columnBlock->hasColumns())
3232         return 0;
3233     
3234     int layerX = 0;
3235     int layerY = 0;
3236     columnBlock->layer()->convertToLayerCoords(rootLayer, layerX, layerY);
3237     
3238     ColumnInfo* colInfo = columnBlock->columnInfo();
3239     int colCount = columnBlock->columnCount(colInfo);
3240     
3241     // We have to go backwards from the last column to the first.
3242     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3243     int logicalLeft = columnBlock->logicalLeftOffsetForContent();
3244     int currLogicalTopOffset = 0;
3245     int i;
3246     for (i = 0; i < colCount; i++) {
3247         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
3248         int blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3249         if (columnBlock->style()->isFlippedBlocksWritingMode())
3250             currLogicalTopOffset += blockDelta;
3251         else
3252             currLogicalTopOffset -= blockDelta;
3253     }
3254     for (i = colCount - 1; i >= 0; i--) {
3255         // For each rect, we clip to the rect, and then we adjust our coords.
3256         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
3257         columnBlock->flipForWritingMode(colRect);
3258         int currLogicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - logicalLeft;
3259         int blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3260         if (columnBlock->style()->isFlippedBlocksWritingMode())
3261             currLogicalTopOffset -= blockDelta;
3262         else
3263             currLogicalTopOffset += blockDelta;
3264         colRect.move(layerX, layerY);
3265
3266         IntRect localClipRect(hitTestRect);
3267         localClipRect.intersect(colRect);
3268         
3269         IntSize offset = isHorizontal ? IntSize(currLogicalLeftOffset, currLogicalTopOffset) : IntSize(currLogicalTopOffset, currLogicalLeftOffset);
3270
3271         if (!localClipRect.isEmpty() && localClipRect.intersects(result.rectForPoint(hitTestPoint))) {
3272             RenderLayer* hitLayer = 0;
3273             if (!columnIndex) {
3274                 // Apply a translation transform to change where the layer paints.
3275                 TransformationMatrix oldTransform;
3276                 bool oldHasTransform = childLayer->transform();
3277                 if (oldHasTransform)
3278                     oldTransform = *childLayer->transform();
3279                 TransformationMatrix newTransform(oldTransform);
3280                 newTransform.translateRight(offset.width(), offset.height());
3281                 
3282                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3283                 hitLayer = childLayer->hitTestLayer(rootLayer, columnLayers[0], request, result, localClipRect, hitTestPoint, false, transformState, zOffset);
3284                 if (oldHasTransform)
3285                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3286                 else
3287                     childLayer->m_transform.clear();
3288             } else {
3289                 // Adjust the transform such that the renderer's upper left corner will be at (0,0) in user space.
3290                 // This involves subtracting out the position of the layer in our current coordinate space.
3291                 RenderLayer* nextLayer = columnLayers[columnIndex - 1];
3292                 RefPtr<HitTestingTransformState> newTransformState = nextLayer->createLocalTransformState(rootLayer, nextLayer, localClipRect, hitTestPoint, transformState);
3293                 newTransformState->translate(offset.width(), offset.height(), HitTestingTransformState::AccumulateTransform);
3294                 IntPoint localPoint = roundedIntPoint(newTransformState->mappedPoint());
3295                 IntRect localHitTestRect = newTransformState->mappedQuad().enclosingBoundingBox();
3296                 newTransformState->flatten();
3297
3298                 hitLayer = hitTestChildLayerColumns(childLayer, columnLayers[columnIndex - 1], request, result, localHitTestRect, localPoint,
3299                                                     newTransformState.get(), zOffset, columnLayers, columnIndex - 1);
3300             }
3301
3302             if (hitLayer)
3303                 return hitLayer;
3304         }
3305     }
3306
3307     return 0;
3308 }
3309
3310 void RenderLayer::updateClipRects(const RenderLayer* rootLayer, OverlayScrollbarSizeRelevancy relevancy)
3311 {
3312     if (m_clipRects) {
3313         ASSERT(rootLayer == m_clipRectsRoot);
3314         return; // We have the correct cached value.
3315     }
3316     
3317     // For transformed layers, the root layer was shifted to be us, so there is no need to
3318     // examine the parent.  We want to cache clip rects with us as the root.
3319     RenderLayer* parentLayer = rootLayer != this ? parent() : 0;
3320     if (parentLayer)
3321         parentLayer->updateClipRects(rootLayer, relevancy);
3322
3323     ClipRects clipRects;
3324     calculateClipRects(rootLayer, clipRects, true, relevancy);
3325
3326     if (parentLayer && parentLayer->clipRects() && clipRects == *parentLayer->clipRects())
3327         m_clipRects = parentLayer->clipRects();
3328     else
3329         m_clipRects = new (renderer()->renderArena()) ClipRects(clipRects);
3330     m_clipRects->ref();
3331 #ifndef NDEBUG
3332     m_clipRectsRoot = rootLayer;
3333 #endif
3334 }
3335
3336 void RenderLayer::calculateClipRects(const RenderLayer* rootLayer, ClipRects& clipRects, bool useCached, OverlayScrollbarSizeRelevancy relevancy) const
3337 {
3338     if (!parent()) {
3339         // The root layer's clip rect is always infinite.
3340         clipRects.reset(PaintInfo::infiniteRect());
3341         return;
3342     }
3343
3344     // For transformed layers, the root layer was shifted to be us, so there is no need to
3345     // examine the parent.  We want to cache clip rects with us as the root.
3346     RenderLayer* parentLayer = rootLayer != this ? parent() : 0;
3347     
3348     // Ensure that our parent's clip has been calculated so that we can examine the values.
3349     if (parentLayer) {
3350         if (useCached && parentLayer->clipRects())
3351             clipRects = *parentLayer->clipRects();
3352         else
3353             parentLayer->calculateClipRects(rootLayer, clipRects);
3354     }
3355     else
3356         clipRects.reset(PaintInfo::infiniteRect());
3357
3358     // A fixed object is essentially the root of its containing block hierarchy, so when
3359     // we encounter such an object, we reset our clip rects to the fixedClipRect.
3360     if (renderer()->style()->position() == FixedPosition) {
3361         clipRects.setPosClipRect(clipRects.fixedClipRect());
3362         clipRects.setOverflowClipRect(clipRects.fixedClipRect());
3363         clipRects.setFixed(true);
3364     }
3365     else if (renderer()->style()->position() == RelativePosition)
3366         clipRects.setPosClipRect(clipRects.overflowClipRect());
3367     else if (renderer()->style()->position() == AbsolutePosition)
3368         clipRects.setOverflowClipRect(clipRects.posClipRect());
3369     
3370     // Update the clip rects that will be passed to child layers.
3371     if (renderer()->hasOverflowClip() || renderer()->hasClip()) {
3372         // This layer establishes a clip of some kind.
3373         int x = 0;
3374         int y = 0;
3375         convertToLayerCoords(rootLayer, x, y);
3376         RenderView* view = renderer()->view();
3377         ASSERT(view);
3378         if (view && clipRects.fixed() && rootLayer->renderer() == view) {
3379             x -= view->frameView()->scrollXForFixedPosition();
3380             y -= view->frameView()->scrollYForFixedPosition();
3381         }
3382         
3383         if (renderer()->hasOverflowClip()) {
3384             IntRect newOverflowClip = toRenderBox(renderer())->overflowClipRect(x, y, relevancy);
3385             clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
3386             if (renderer()->isPositioned() || renderer()->isRelPositioned())
3387                 clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
3388         }
3389         if (renderer()->hasClip()) {
3390             IntRect newPosClip = toRenderBox(renderer())->clipRect(x, y);
3391             clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
3392             clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
3393             clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
3394         }
3395     }
3396 }
3397
3398 void RenderLayer::parentClipRects(const RenderLayer* rootLayer, ClipRects& clipRects, bool temporaryClipRects, OverlayScrollbarSizeRelevancy relevancy) const
3399 {
3400     ASSERT(parent());
3401     if (temporaryClipRects) {
3402         parent()->calculateClipRects(rootLayer, clipRects, false, relevancy);
3403         return;
3404     }
3405
3406     parent()->updateClipRects(rootLayer, relevancy);
3407     clipRects = *parent()->clipRects();
3408 }
3409
3410 IntRect RenderLayer::backgroundClipRect(const RenderLayer* rootLayer, bool temporaryClipRects, OverlayScrollbarSizeRelevancy relevancy) const
3411 {
3412     IntRect backgroundRect;
3413     if (parent()) {
3414         ClipRects parentRects;
3415         parentClipRects(rootLayer, parentRects, temporaryClipRects, relevancy);
3416         backgroundRect = renderer()->style()->position() == FixedPosition ? parentRects.fixedClipRect() :
3417                          (renderer()->isPositioned() ? parentRects.posClipRect() : 
3418                                                        parentRects.overflowClipRect());
3419         RenderView* view = renderer()->view();
3420         ASSERT(view);
3421         if (view && parentRects.fixed() && rootLayer->renderer() == view)
3422             backgroundRect.move(view->frameView()->scrollXForFixedPosition(), view->frameView()->scrollYForFixedPosition());
3423     }
3424     return backgroundRect;
3425 }
3426
3427 void RenderLayer::calculateRects(const RenderLayer* rootLayer, const IntRect& paintDirtyRect, IntRect& layerBounds,
3428                                  IntRect& backgroundRect, IntRect& foregroundRect, IntRect& outlineRect, bool temporaryClipRects,
3429                                  OverlayScrollbarSizeRelevancy relevancy) const
3430 {
3431     if (rootLayer != this && parent()) {
3432         backgroundRect = backgroundClipRect(rootLayer, temporaryClipRects, relevancy);
3433         backgroundRect.intersect(paintDirtyRect);
3434     } else
3435         backgroundRect = paintDirtyRect;
3436
3437     foregroundRect = backgroundRect;
3438     outlineRect = backgroundRect;
3439     
3440     int x = 0;
3441     int y = 0;
3442     convertToLayerCoords(rootLayer, x, y);
3443     layerBounds = IntRect(x, y, width(), height());
3444     
3445     // Update the clip rects that will be passed to child layers.
3446     if (renderer()->hasOverflowClip() || renderer()->hasClip()) {
3447         // This layer establishes a clip of some kind.
3448         if (renderer()->hasOverflowClip())
3449             foregroundRect.intersect(toRenderBox(renderer())->overflowClipRect(x, y, relevancy));
3450         if (renderer()->hasClip()) {
3451             // Clip applies to *us* as well, so go ahead and update the damageRect.
3452             IntRect newPosClip = toRenderBox(renderer())->clipRect(x, y);
3453             backgroundRect.intersect(newPosClip);
3454             foregroundRect.intersect(newPosClip);
3455             outlineRect.intersect(newPosClip);
3456         }
3457
3458         // If we establish a clip at all, then go ahead and make sure our background
3459         // rect is intersected with our layer's bounds.
3460         // FIXME: This could be changed to just use generic visual overflow.
3461         // See https://bugs.webkit.org/show_bug.cgi?id=37467 for more information.
3462         if (const ShadowData* boxShadow = renderer()->style()->boxShadow()) {
3463             IntRect overflow = layerBounds;
3464             do {
3465                 if (boxShadow->style() == Normal) {
3466                     IntRect shadowRect = layerBounds;
3467                     shadowRect.move(boxShadow->x(), boxShadow->y());
3468                     shadowRect.inflate(boxShadow->blur() + boxShadow->spread());
3469                     overflow.unite(shadowRect);
3470                 }
3471
3472                 boxShadow = boxShadow->next();
3473             } while (boxShadow);
3474             backgroundRect.intersect(overflow);
3475         } else
3476             backgroundRect.intersect(layerBounds);
3477     }
3478 }
3479
3480 IntRect RenderLayer::childrenClipRect() const
3481 {
3482     RenderView* renderView = renderer()->view();
3483     RenderLayer* clippingRootLayer = clippingRoot();
3484     IntRect layerBounds, backgroundRect, foregroundRect, outlineRect;
3485     calculateRects(clippingRootLayer, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
3486     return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(foregroundRect)).enclosingBoundingBox();
3487 }
3488
3489 IntRect RenderLayer::selfClipRect() const
3490 {
3491     RenderView* renderView = renderer()->view();
3492     RenderLayer* clippingRootLayer = clippingRoot();
3493     IntRect layerBounds, backgroundRect, foregroundRect, outlineRect;
3494     calculateRects(clippingRootLayer, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
3495     return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(backgroundRect)).enclosingBoundingBox();
3496 }
3497
3498 void RenderLayer::addBlockSelectionGapsBounds(const IntRect& bounds)
3499 {
3500     m_blockSelectionGapsBounds.unite(bounds);
3501 }
3502
3503 void RenderLayer::clearBlockSelectionGapsBounds()
3504 {
3505     m_blockSelectionGapsBounds = IntRect();
3506     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3507         child->clearBlockSelectionGapsBounds();
3508 }
3509
3510 void RenderLayer::repaintBlockSelectionGaps()
3511 {
3512     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3513         child->repaintBlockSelectionGaps();
3514
3515     if (m_blockSelectionGapsBounds.isEmpty())
3516         return;
3517
3518     IntRect rect = m_blockSelectionGapsBounds;
3519     rect.move(-scrolledContentOffset());
3520     if (renderer()->hasOverflowClip())
3521         rect.intersect(toRenderBox(renderer())->overflowClipRect(0, 0));
3522     if (renderer()->hasClip())
3523         rect.intersect(toRenderBox(renderer())->clipRect(0, 0));
3524     if (!rect.isEmpty())
3525         renderer()->repaintRectangle(rect);
3526 }
3527
3528 bool RenderLayer::intersectsDamageRect(const IntRect& layerBounds, const IntRect& damageRect, const RenderLayer* rootLayer) const
3529 {
3530     // Always examine the canvas and the root.
3531     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
3532     // paints the root's background.
3533     if (renderer()->isRenderView() || renderer()->isRoot())
3534         return true;
3535
3536     // If we aren't an inline flow, and our layer bounds do intersect the damage rect, then we 
3537     // can go ahead and return true.
3538     RenderView* view = renderer()->view();
3539     ASSERT(view);
3540     if (view && !renderer()->isRenderInline()) {
3541         IntRect b = layerBounds;
3542         b.inflate(view->maximalOutlineSize());
3543         if (b.intersects(damageRect))
3544             return true;
3545     }
3546         
3547     // Otherwise we need to compute the bounding box of this single layer and see if it intersects
3548     // the damage rect.
3549     return boundingBox(rootLayer).intersects(damageRect);
3550 }
3551
3552 IntRect RenderLayer::localBoundingBox() const
3553 {
3554     // There are three special cases we need to consider.
3555     // (1) Inline Flows.  For inline flows we will create a bounding box that fully encompasses all of the lines occupied by the
3556     // inline.  In other words, if some <span> wraps to three lines, we'll create a bounding box that fully encloses the
3557     // line boxes of all three lines (including overflow on those lines).
3558     // (2) Left/Top Overflow.  The width/height of layers already includes right/bottom overflow.  However, in the case of left/top
3559     // overflow, we have to create a bounding box that will extend to include this overflow.
3560     // (3) Floats.  When a layer has overhanging floats that it paints, we need to make sure to include these overhanging floats
3561     // as part of our bounding box.  We do this because we are the responsible layer for both hit testing and painting those
3562     // floats.
3563     IntRect result;
3564     if (renderer()->isRenderInline())
3565         result = toRenderInline(renderer())->linesVisualOverflowBoundingBox();
3566     else if (renderer()->isTableRow()) {
3567         // Our bounding box is just the union of all of our cells' border/overflow rects.
3568         for (RenderObject* child = renderer()->firstChild(); child; child = child->nextSibling()) {
3569             if (child->isTableCell()) {
3570                 IntRect bbox = toRenderBox(child)->borderBoxRect();
3571                 result.unite(bbox);
3572                 IntRect overflowRect = renderBox()->visualOverflowRect();
3573                 if (bbox != overflowRect)
3574                     result.unite(overflowRect);
3575             }
3576         }
3577     } else {
3578         RenderBox* box = renderBox();
3579         ASSERT(box);
3580         if (box->hasMask())
3581             result = box->maskClipRect();
3582         else {
3583             IntRect bbox = box->borderBoxRect();
3584             result = bbox;
3585             IntRect overflowRect = box->visualOverflowRect();
3586             if (bbox != overflowRect)
3587                 result.unite(overflowRect);
3588         }
3589     }
3590
3591     RenderView* view = renderer()->view();
3592     ASSERT(view);
3593     if (view)
3594         result.inflate(view->maximalOutlineSize()); // Used to apply a fudge factor to dirty-rect checks on blocks/tables.
3595
3596     return result;
3597 }
3598
3599 IntRect RenderLayer::boundingBox(const RenderLayer* ancestorLayer) const
3600 {    
3601     IntRect result = localBoundingBox();
3602     if (renderer()->isBox())
3603         renderBox()->flipForWritingMode(result);
3604     else
3605         renderer()->containingBlock()->flipForWritingMode(result);
3606     int deltaX = 0, deltaY = 0;
3607     convertToLayerCoords(ancestorLayer, deltaX, deltaY);
3608     result.move(deltaX, deltaY);
3609     return result;
3610 }
3611
3612 IntRect RenderLayer::absoluteBoundingBox() const
3613 {
3614     return boundingBox(root());
3615 }
3616
3617 void RenderLayer::clearClipRectsIncludingDescendants()
3618 {
3619     if (!m_clipRects)
3620         return;
3621
3622     clearClipRects();
3623     
3624     for (RenderLayer* l = firstChild(); l; l = l->nextSibling())
3625         l->clearClipRectsIncludingDescendants();
3626 }
3627
3628 void RenderLayer::clearClipRects()
3629 {
3630     if (m_clipRects) {
3631         m_clipRects->deref(renderer()->renderArena());
3632         m_clipRects = 0;
3633 #ifndef NDEBUG
3634         m_clipRectsRoot = 0;
3635 #endif    
3636     }
3637 }
3638
3639 #if USE(ACCELERATED_COMPOSITING)
3640 RenderLayerBacking* RenderLayer::ensureBacking()
3641 {
3642     if (!m_backing)
3643         m_backing = adoptPtr(new RenderLayerBacking(this));
3644     return m_backing.get();
3645 }
3646
3647 void RenderLayer::clearBacking()
3648 {
3649     m_backing.clear();
3650 }
3651
3652 bool RenderLayer::hasCompositedMask() const
3653 {
3654     return m_backing && m_backing->hasMaskLayer();
3655 }
3656
3657 GraphicsLayer* RenderLayer::layerForHorizontalScrollbar() const
3658 {
3659     return m_backing ? m_backing->layerForHorizontalScrollbar() : 0;
3660 }
3661
3662 GraphicsLayer* RenderLayer::layerForVerticalScrollbar() const
3663 {
3664     return m_backing ? m_backing->layerForVerticalScrollbar() : 0;
3665 }
3666
3667 GraphicsLayer* RenderLayer::layerForScrollCorner() const
3668 {
3669     return m_backing ? m_backing->layerForScrollCorner() : 0;
3670 }
3671 #endif
3672
3673 bool RenderLayer::paintsWithTransform(PaintBehavior paintBehavior) const
3674 {
3675 #if USE(ACCELERATED_COMPOSITING)
3676     bool paintsToWindow = !isComposited() || backing()->paintingGoesToWindow();
3677 #else
3678     bool paintsToWindow = true;
3679 #endif    
3680     return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || paintsToWindow);
3681 }
3682
3683 void RenderLayer::setParent(RenderLayer* parent)
3684 {
3685     if (parent == m_parent)
3686         return;
3687
3688 #if USE(ACCELERATED_COMPOSITING)
3689     if (m_parent && !renderer()->documentBeingDestroyed())
3690         compositor()->layerWillBeRemoved(m_parent, this);
3691 #endif
3692     
3693     m_parent = parent;
3694     
3695 #if USE(ACCELERATED_COMPOSITING)
3696     if (m_parent && !renderer()->documentBeingDestroyed())
3697         compositor()->layerWasAdded(m_parent, this);
3698 #endif
3699 }
3700
3701 static RenderObject* commonAncestor(RenderObject* obj1, RenderObject* obj2)
3702 {
3703     if (!obj1 || !obj2)
3704         return 0;
3705
3706     for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor())
3707         for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor())
3708             if (currObj1 == currObj2)
3709                 return currObj1;
3710
3711     return 0;
3712 }
3713
3714 void RenderLayer::updateHoverActiveState(const HitTestRequest& request, HitTestResult& result)
3715 {
3716     // We don't update :hover/:active state when the result is marked as readOnly.
3717     if (request.readOnly())
3718         return;
3719
3720     Document* doc = renderer()->document();
3721
3722     Node* activeNode = doc->activeNode();
3723     if (activeNode && !request.active()) {
3724         // We are clearing the :active chain because the mouse has been released.
3725         for (RenderObject* curr = activeNode->renderer(); curr; curr = curr->parent()) {
3726             if (curr->node() && !curr->isText())
3727                 curr->node()->clearInActiveChain();
3728         }
3729         doc->setActiveNode(0);
3730     } else {
3731         Node* newActiveNode = result.innerNode();
3732         if (!activeNode && newActiveNode && request.active()) {
3733             // We are setting the :active chain and freezing it. If future moves happen, they
3734             // will need to reference this chain.
3735             for (RenderObject* curr = newActiveNode->renderer(); curr; curr = curr->parent()) {
3736                 if (curr->node() && !curr->isText()) {
3737                     curr->node()->setInActiveChain();
3738                 }
3739             }
3740             doc->setActiveNode(newActiveNode);
3741         }
3742     }
3743
3744     // If the mouse is down and if this is a mouse move event, we want to restrict changes in 
3745     // :hover/:active to only apply to elements that are in the :active chain that we froze
3746     // at the time the mouse went down.
3747     bool mustBeInActiveChain = request.active() && request.mouseMove();
3748
3749     // Check to see if the hovered node has changed.  If not, then we don't need to
3750     // do anything.  
3751     RefPtr<Node> oldHoverNode = doc->hoverNode();
3752     Node* newHoverNode = result.innerNode();
3753
3754     // Update our current hover node.
3755     doc->setHoverNode(newHoverNode);
3756
3757     // We have two different objects.  Fetch their renderers.
3758     RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
3759     RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
3760     
3761     // Locate the common ancestor render object for the two renderers.
3762     RenderObject* ancestor = commonAncestor(oldHoverObj, newHoverObj);
3763
3764     Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
3765     Vector<RefPtr<Node>, 32> nodesToAddToChain;
3766
3767     if (oldHoverObj != newHoverObj) {
3768         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
3769         for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
3770             if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
3771                 nodesToRemoveFromChain.append(curr->node());
3772         }
3773     }
3774
3775     // Now set the hover state for our new object up to the root.
3776     for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
3777         if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
3778             nodesToAddToChain.append(curr->node());
3779     }
3780
3781     size_t removeCount = nodesToRemoveFromChain.size();
3782     for (size_t i = 0; i < removeCount; ++i) {
3783         nodesToRemoveFromChain[i]->setActive(false);
3784         nodesToRemoveFromChain[i]->setHovered(false);
3785     }
3786
3787     size_t addCount = nodesToAddToChain.size();
3788     for (size_t i = 0; i < addCount; ++i) {
3789         nodesToAddToChain[i]->setActive(request.active());
3790         nodesToAddToChain[i]->setHovered(true);
3791     }
3792 }
3793
3794 // Helper for the sorting of layers by z-index.
3795 static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
3796 {
3797     return first->zIndex() < second->zIndex();
3798 }
3799
3800 void RenderLayer::dirtyZOrderLists()
3801 {
3802     if (m_posZOrderList)
3803         m_posZOrderList->clear();
3804     if (m_negZOrderList)
3805         m_negZOrderList->clear();
3806     m_zOrderListsDirty = true;
3807
3808 #if USE(ACCELERATED_COMPOSITING)
3809     if (!renderer()->documentBeingDestroyed())
3810         compositor()->setCompositingLayersNeedRebuild();
3811 #endif
3812 }
3813
3814 void RenderLayer::dirtyStackingContextZOrderLists()
3815 {
3816     RenderLayer* sc = stackingContext();
3817     if (sc)
3818         sc->dirtyZOrderLists();
3819 }
3820
3821 void RenderLayer::dirtyNormalFlowList()
3822 {
3823     if (m_normalFlowList)
3824         m_normalFlowList->clear();
3825     m_normalFlowListDirty = true;
3826
3827 #if USE(ACCELERATED_COMPOSITING)
3828     if (!renderer()->documentBeingDestroyed())
3829         compositor()->setCompositingLayersNeedRebuild();
3830 #endif
3831 }
3832
3833 void RenderLayer::updateZOrderLists()
3834 {
3835     if (!isStackingContext() || !m_zOrderListsDirty)
3836         return;
3837
3838     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3839         if (!m_reflection || reflectionLayer() != child)
3840             child->collectLayers(m_posZOrderList, m_negZOrderList);
3841
3842     // Sort the two lists.
3843     if (m_posZOrderList)
3844         std::stable_sort(m_posZOrderList->begin(), m_posZOrderList->end(), compareZIndex);
3845
3846     if (m_negZOrderList)
3847         std::stable_sort(m_negZOrderList->begin(), m_negZOrderList->end(), compareZIndex);
3848
3849     m_zOrderListsDirty = false;
3850 }
3851
3852 void RenderLayer::updateNormalFlowList()
3853 {
3854     if (!m_normalFlowListDirty)
3855         return;
3856         
3857     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
3858         // Ignore non-overflow layers and reflections.
3859  &nbs