2011-05-10 Emil A Eklund <eae@chromium.org>
[WebKit-https.git] / Source / WebCore / rendering / RenderLayer.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
3  *
4  * Portions are Copyright (C) 1998 Netscape Communications Corporation.
5  *
6  * Other contributors:
7  *   Robert O'Callahan <roc+@cs.cmu.edu>
8  *   David Baron <dbaron@fas.harvard.edu>
9  *   Christian Biesinger <cbiesinger@web.de>
10  *   Randall Jesup <rjesup@wgate.com>
11  *   Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
12  *   Josh Soref <timeless@mac.com>
13  *   Boris Zbarsky <bzbarsky@mit.edu>
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28  *
29  * Alternatively, the contents of this file may be used under the terms
30  * of either the Mozilla Public License Version 1.1, found at
31  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
32  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
33  * (the "GPL"), in which case the provisions of the MPL or the GPL are
34  * applicable instead of those above.  If you wish to allow use of your
35  * version of this file only under the terms of one of those two
36  * licenses (the MPL or the GPL) and not to allow others to use your
37  * version of this file under the LGPL, indicate your decision by
38  * deletingthe provisions above and replace them with the notice and
39  * other provisions required by the MPL or the GPL, as the case may be.
40  * If you do not delete the provisions above, a recipient may use your
41  * version of this file under any of the LGPL, the MPL or the GPL.
42  */
43
44 #include "config.h"
45 #include "RenderLayer.h"
46
47 #include "ColumnInfo.h"
48 #include "CSSPropertyNames.h"
49 #include "CSSStyleDeclaration.h"
50 #include "CSSStyleSelector.h"
51 #include "Chrome.h"
52 #include "Document.h"
53 #include "EventHandler.h"
54 #include "EventQueue.h"
55 #include "FloatPoint3D.h"
56 #include "FloatRect.h"
57 #include "FocusController.h"
58 #include "Frame.h"
59 #include "FrameSelection.h"
60 #include "FrameTree.h"
61 #include "FrameView.h"
62 #include "Gradient.h"
63 #include "GraphicsContext.h"
64 #include "HTMLFrameOwnerElement.h"
65 #include "HTMLNames.h"
66 #include "HitTestRequest.h"
67 #include "HitTestResult.h"
68 #include "OverflowEvent.h"
69 #include "OverlapTestRequestClient.h"
70 #include "Page.h"
71 #include "PlatformMouseEvent.h"
72 #include "RenderArena.h"
73 #include "RenderInline.h"
74 #include "RenderMarquee.h"
75 #include "RenderReplica.h"
76 #include "RenderScrollbar.h"
77 #include "RenderScrollbarPart.h"
78 #include "RenderTheme.h"
79 #include "RenderTreeAsText.h"
80 #include "RenderView.h"
81 #include "ScaleTransformOperation.h"
82 #include "Scrollbar.h"
83 #include "ScrollbarTheme.h"
84 #include "TextStream.h"
85 #include "TransformState.h"
86 #include "TransformationMatrix.h"
87 #include "TranslateTransformOperation.h"
88 #include <wtf/StdLibExtras.h>
89 #include <wtf/UnusedParam.h>
90 #include <wtf/text/CString.h>
91
92 #if USE(ACCELERATED_COMPOSITING)
93 #include "RenderLayerBacking.h"
94 #include "RenderLayerCompositor.h"
95 #endif
96
97 #if ENABLE(SVG)
98 #include "SVGNames.h"
99 #endif
100
101 #define MIN_INTERSECT_FOR_REVEAL 32
102
103 using namespace std;
104
105 namespace WebCore {
106
107 using namespace HTMLNames;
108
109 const int MinimumWidthWhileResizing = 100;
110 const int MinimumHeightWhileResizing = 40;
111
112 void* ClipRects::operator new(size_t sz, RenderArena* renderArena) throw()
113 {
114     return renderArena->allocate(sz);
115 }
116
117 void ClipRects::operator delete(void* ptr, size_t sz)
118 {
119     // Stash size where destroy can find it.
120     *(size_t *)ptr = sz;
121 }
122
123 void ClipRects::destroy(RenderArena* renderArena)
124 {
125     delete this;
126     
127     // Recover the size left there for us by operator delete and free the memory.
128     renderArena->free(*(size_t *)this, this);
129 }
130
131 RenderLayer::RenderLayer(RenderBoxModelObject* renderer)
132     : m_renderer(renderer)
133     , m_parent(0)
134     , m_previous(0)
135     , m_next(0)
136     , m_first(0)
137     , m_last(0)
138     , m_inResizeMode(false)
139     , m_posZOrderList(0)
140     , m_negZOrderList(0)
141     , m_normalFlowList(0)
142     , m_clipRects(0) 
143 #ifndef NDEBUG    
144     , m_clipRectsRoot(0)
145 #endif
146     , m_scrollDimensionsDirty(true)
147     , m_zOrderListsDirty(true)
148     , m_normalFlowListDirty(true)
149     , m_isNormalFlowOnly(shouldBeNormalFlowOnly())
150     , m_usedTransparency(false)
151     , m_paintingInsideReflection(false)
152     , m_inOverflowRelayout(false)
153     , m_needsFullRepaint(false)
154     , m_overflowStatusDirty(true)
155     , m_visibleContentStatusDirty(true)
156     , m_hasVisibleContent(false)
157     , m_visibleDescendantStatusDirty(false)
158     , m_hasVisibleDescendant(false)
159     , m_isPaginated(false)
160     , m_3DTransformedDescendantStatusDirty(true)
161     , m_has3DTransformedDescendant(false)
162 #if USE(ACCELERATED_COMPOSITING)
163     , m_hasCompositingDescendant(false)
164     , m_mustOverlapCompositedLayers(false)
165 #endif
166     , m_containsDirtyOverlayScrollbars(false)
167     , m_marquee(0)
168     , m_staticInlinePosition(0)
169     , m_staticBlockPosition(0)
170     , m_reflection(0)
171     , m_scrollCorner(0)
172     , m_resizer(0)
173     , m_scrollableAreaPage(0)
174 {
175     ScrollableArea::setConstrainsScrollingToContentEdge(false);
176
177     if (!renderer->firstChild() && renderer->style()) {
178         m_visibleContentStatusDirty = false;
179         m_hasVisibleContent = renderer->style()->visibility() == VISIBLE;
180     }
181 }
182
183 RenderLayer::~RenderLayer()
184 {
185     if (inResizeMode() && !renderer()->documentBeingDestroyed()) {
186         if (Frame* frame = renderer()->frame())
187             frame->eventHandler()->resizeLayerDestroyed();
188     }
189
190     if (m_scrollableAreaPage)
191         m_scrollableAreaPage->removeScrollableArea(this);
192
193     destroyScrollbar(HorizontalScrollbar);
194     destroyScrollbar(VerticalScrollbar);
195
196     if (m_reflection)
197         removeReflection();
198
199     // Child layers will be deleted by their corresponding render objects, so
200     // we don't need to delete them ourselves.
201
202     delete m_posZOrderList;
203     delete m_negZOrderList;
204     delete m_normalFlowList;
205     delete m_marquee;
206
207 #if USE(ACCELERATED_COMPOSITING)
208     clearBacking();
209 #endif
210     
211     // Make sure we have no lingering clip rects.
212     ASSERT(!m_clipRects);
213     
214     if (m_scrollCorner)
215         m_scrollCorner->destroy();
216     if (m_resizer)
217         m_resizer->destroy();
218 }
219
220 #if USE(ACCELERATED_COMPOSITING)
221 RenderLayerCompositor* RenderLayer::compositor() const
222 {
223     ASSERT(renderer()->view());
224     return renderer()->view()->compositor();
225 }
226
227 void RenderLayer::contentChanged(ContentChangeType changeType)
228 {
229     // This can get called when video becomes accelerated, so the layers may change.
230     if ((changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged) && compositor()->updateLayerCompositingState(this))
231         compositor()->setCompositingLayersNeedRebuild();
232
233     if (m_backing)
234         m_backing->contentChanged(changeType);
235 }
236 #endif // USE(ACCELERATED_COMPOSITING)
237
238 bool RenderLayer::hasAcceleratedCompositing() const
239 {
240 #if USE(ACCELERATED_COMPOSITING)
241     return compositor()->hasAcceleratedCompositing();
242 #else
243     return false;
244 #endif
245 }
246
247 bool RenderLayer::canRender3DTransforms() const
248 {
249 #if USE(ACCELERATED_COMPOSITING)
250     return compositor()->canRender3DTransforms();
251 #else
252     return false;
253 #endif
254 }
255
256 void RenderLayer::updateLayerPositions(UpdateLayerPositionsFlags flags, IntPoint* cachedOffset)
257 {
258     updateLayerPosition(); // For relpositioned layers or non-positioned layers,
259                            // we need to keep in sync, since we may have shifted relative
260                            // to our parent layer.
261     IntPoint oldCachedOffset;
262     if (cachedOffset) {
263         // We can't cache our offset to the repaint container if the mapping is anything more complex than a simple translation
264         bool disableOffsetCache = renderer()->hasColumns() || renderer()->hasTransform() || isComposited();
265 #if ENABLE(SVG)
266         disableOffsetCache = disableOffsetCache || renderer()->isSVGRoot();
267 #endif
268         if (disableOffsetCache)
269             cachedOffset = 0; // If our cached offset is invalid make sure it's not passed to any of our children
270         else {
271             oldCachedOffset = *cachedOffset;
272             // Frequently our parent layer's renderer will be the same as our renderer's containing block.  In that case,
273             // we just update the cache using our offset to our parent (which is m_topLeft). Otherwise, regenerated cached
274             // offsets to the root from the render tree.
275             if (!m_parent || m_parent->renderer() == renderer()->containingBlock())
276                 cachedOffset->move(m_topLeft.x(), m_topLeft.y()); // Fast case
277             else {
278                 int x = 0;
279                 int y = 0;
280                 convertToLayerCoords(root(), x, y);
281                 *cachedOffset = IntPoint(x, y);
282             }
283         }
284     }
285
286     int x = 0;
287     int y = 0;
288     if (cachedOffset) {
289         x += cachedOffset->x();
290         y += cachedOffset->y();
291 #ifndef NDEBUG
292         int nonCachedX = 0;
293         int nonCachedY = 0;
294         convertToLayerCoords(root(), nonCachedX, nonCachedY);
295         ASSERT(x == nonCachedX);
296         ASSERT(y == nonCachedY);
297 #endif
298     } else
299         convertToLayerCoords(root(), x, y);
300     positionOverflowControls(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 bool RenderLayer::isActive() const
1654 {
1655     Page* page = renderer()->frame()->page();
1656     return page && page->focusController()->isActive();
1657 }
1658
1659 static IntRect cornerRect(const RenderLayer* layer, const IntRect& bounds)
1660 {
1661     int horizontalThickness;
1662     int verticalThickness;
1663     if (!layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
1664         // FIXME: This isn't right.  We need to know the thickness of custom scrollbars
1665         // even when they don't exist in order to set the resizer square size properly.
1666         horizontalThickness = ScrollbarTheme::nativeTheme()->scrollbarThickness();
1667         verticalThickness = horizontalThickness;
1668     } else if (layer->verticalScrollbar() && !layer->horizontalScrollbar()) {
1669         horizontalThickness = layer->verticalScrollbar()->width();
1670         verticalThickness = horizontalThickness;
1671     } else if (layer->horizontalScrollbar() && !layer->verticalScrollbar()) {
1672         verticalThickness = layer->horizontalScrollbar()->height();
1673         horizontalThickness = verticalThickness;
1674     } else {
1675         horizontalThickness = layer->verticalScrollbar()->width();
1676         verticalThickness = layer->horizontalScrollbar()->height();
1677     }
1678     return IntRect(bounds.maxX() - horizontalThickness - layer->renderer()->style()->borderRightWidth(), 
1679                    bounds.maxY() - verticalThickness - layer->renderer()->style()->borderBottomWidth(),
1680                    horizontalThickness, verticalThickness);
1681 }
1682
1683 IntRect RenderLayer::scrollCornerRect() const
1684 {
1685     // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
1686     // This happens when:
1687     // (a) A resizer is present and at least one scrollbar is present
1688     // (b) Both scrollbars are present.
1689     bool hasHorizontalBar = horizontalScrollbar();
1690     bool hasVerticalBar = verticalScrollbar();
1691     bool hasResizer = renderer()->style()->resize() != RESIZE_NONE;
1692     if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
1693         return cornerRect(this, renderBox()->borderBoxRect());
1694     return IntRect();
1695 }
1696
1697 static IntRect resizerCornerRect(const RenderLayer* layer, const IntRect& bounds)
1698 {
1699     ASSERT(layer->renderer()->isBox());
1700     if (layer->renderer()->style()->resize() == RESIZE_NONE)
1701         return IntRect();
1702     return cornerRect(layer, bounds);
1703 }
1704
1705 IntRect RenderLayer::scrollCornerAndResizerRect() const
1706 {
1707     RenderBox* box = renderBox();
1708     if (!box)
1709         return IntRect();
1710     IntRect scrollCornerAndResizer = scrollCornerRect();
1711     if (scrollCornerAndResizer.isEmpty())
1712         scrollCornerAndResizer = resizerCornerRect(this, box->borderBoxRect());
1713     return scrollCornerAndResizer;
1714 }
1715
1716 bool RenderLayer::isScrollCornerVisible() const
1717 {
1718     ASSERT(renderer()->isBox());
1719     return !scrollCornerRect().isEmpty();
1720 }
1721
1722 IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
1723 {
1724     RenderView* view = renderer()->view();
1725     if (!view)
1726         return scrollbarRect;
1727
1728     IntRect rect = scrollbarRect;
1729     rect.move(scrollbarOffset(scrollbar));
1730
1731     return view->frameView()->convertFromRenderer(renderer(), rect);
1732 }
1733
1734 IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
1735 {
1736     RenderView* view = renderer()->view();
1737     if (!view)
1738         return parentRect;
1739
1740     IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
1741     rect.move(-scrollbarOffset(scrollbar));
1742     return rect;
1743 }
1744
1745 IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
1746 {
1747     RenderView* view = renderer()->view();
1748     if (!view)
1749         return scrollbarPoint;
1750
1751     IntPoint point = scrollbarPoint;
1752     point.move(scrollbarOffset(scrollbar));
1753     return view->frameView()->convertFromRenderer(renderer(), point);
1754 }
1755
1756 IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
1757 {
1758     RenderView* view = renderer()->view();
1759     if (!view)
1760         return parentPoint;
1761
1762     IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
1763
1764     point.move(-scrollbarOffset(scrollbar));
1765     return point;
1766 }
1767
1768 IntSize RenderLayer::contentsSize() const
1769 {
1770     return IntSize(const_cast<RenderLayer*>(this)->scrollWidth(), const_cast<RenderLayer*>(this)->scrollHeight());
1771 }
1772
1773 int RenderLayer::visibleHeight() const
1774 {
1775     return m_layerSize.height();
1776 }
1777
1778 int RenderLayer::visibleWidth() const
1779 {
1780     return m_layerSize.width();
1781 }
1782
1783 bool RenderLayer::shouldSuspendScrollAnimations() const
1784 {
1785     RenderView* view = renderer()->view();
1786     if (!view)
1787         return true;
1788     return view->frameView()->shouldSuspendScrollAnimations();
1789 }
1790
1791 IntPoint RenderLayer::currentMousePosition() const
1792 {
1793     return renderer()->frame() ? renderer()->frame()->eventHandler()->currentMousePosition() : IntPoint();
1794 }
1795
1796 IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
1797 {
1798     RenderBox* box = renderBox();
1799
1800     if (scrollbar == m_vBar.get())
1801         return IntSize(box->width() - box->borderRight() - scrollbar->width(), box->borderTop());
1802
1803     if (scrollbar == m_hBar.get())
1804         return IntSize(box->borderLeft(), box->height() - box->borderBottom() - scrollbar->height());
1805     
1806     ASSERT_NOT_REACHED();
1807     return IntSize();
1808 }
1809
1810 void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
1811 {
1812 #if USE(ACCELERATED_COMPOSITING)
1813     if (scrollbar == m_vBar.get()) {
1814         if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
1815             layer->setNeedsDisplayInRect(rect);
1816             return;
1817         }
1818     } else {
1819         if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1820             layer->setNeedsDisplayInRect(rect);
1821             return;
1822         }
1823     }
1824 #endif
1825     IntRect scrollRect = rect;
1826     RenderBox* box = renderBox();
1827     ASSERT(box);
1828     if (scrollbar == m_vBar.get())
1829         scrollRect.move(box->width() - box->borderRight() - scrollbar->width(), box->borderTop());
1830     else
1831         scrollRect.move(box->borderLeft(), box->height() - box->borderBottom() - scrollbar->height());
1832     renderer()->repaintRectangle(scrollRect);
1833 }
1834
1835 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
1836 {
1837 #if USE(ACCELERATED_COMPOSITING)
1838     if (GraphicsLayer* layer = layerForScrollCorner()) {
1839         layer->setNeedsDisplayInRect(rect);
1840         return;
1841     }
1842 #endif
1843     if (m_scrollCorner)
1844         m_scrollCorner->repaintRectangle(rect);
1845     if (m_resizer)
1846         m_resizer->repaintRectangle(rect);
1847 }
1848
1849 PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
1850 {
1851     RefPtr<Scrollbar> widget;
1852     RenderObject* actualRenderer = renderer()->node() ? renderer()->node()->shadowAncestorNode()->renderer() : renderer();
1853     bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
1854     if (hasCustomScrollbarStyle)
1855         widget = RenderScrollbar::createCustomScrollbar(this, orientation, toRenderBox(actualRenderer));
1856     else {
1857         widget = Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
1858         if (orientation == HorizontalScrollbar)
1859             didAddHorizontalScrollbar(widget.get());
1860         else 
1861             didAddVerticalScrollbar(widget.get());
1862     }
1863     renderer()->document()->view()->addChild(widget.get());        
1864     return widget.release();
1865 }
1866
1867 void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
1868 {
1869     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
1870     if (scrollbar) {
1871         if (scrollbar->isCustomScrollbar())
1872             static_cast<RenderScrollbar*>(scrollbar.get())->clearOwningRenderer();
1873         else {
1874             if (orientation == HorizontalScrollbar)
1875                 willRemoveHorizontalScrollbar(scrollbar.get());
1876             else
1877                 willRemoveVerticalScrollbar(scrollbar.get());
1878         }
1879
1880         scrollbar->removeFromParent();
1881         scrollbar->disconnectFromScrollableArea();
1882         scrollbar = 0;
1883     }
1884 }
1885
1886 bool RenderLayer::scrollsOverflow() const
1887 {
1888     if (!renderer()->isBox())
1889         return false;
1890     
1891     return toRenderBox(renderer())->scrollsOverflow();
1892 }
1893
1894 void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
1895 {
1896     if (hasScrollbar == (m_hBar != 0))
1897         return;
1898
1899     if (hasScrollbar)
1900         m_hBar = createScrollbar(HorizontalScrollbar);
1901     else
1902         destroyScrollbar(HorizontalScrollbar);
1903
1904     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
1905     if (m_hBar)
1906         m_hBar->styleChanged();
1907     if (m_vBar)
1908         m_vBar->styleChanged();
1909
1910 #if ENABLE(DASHBOARD_SUPPORT)
1911     // Force an update since we know the scrollbars have changed things.
1912     if (renderer()->document()->hasDashboardRegions())
1913         renderer()->document()->setDashboardRegionsDirty(true);
1914 #endif
1915 }
1916
1917 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
1918 {
1919     if (hasScrollbar == (m_vBar != 0))
1920         return;
1921
1922     if (hasScrollbar)
1923         m_vBar = createScrollbar(VerticalScrollbar);
1924     else
1925         destroyScrollbar(VerticalScrollbar);
1926
1927      // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
1928     if (m_hBar)
1929         m_hBar->styleChanged();
1930     if (m_vBar)
1931         m_vBar->styleChanged();
1932
1933 #if ENABLE(DASHBOARD_SUPPORT)
1934     // Force an update since we know the scrollbars have changed things.
1935     if (renderer()->document()->hasDashboardRegions())
1936         renderer()->document()->setDashboardRegionsDirty(true);
1937 #endif
1938 }
1939
1940 int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
1941 {
1942     if (!m_vBar || (m_vBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
1943         return 0;
1944     return m_vBar->width();
1945 }
1946
1947 int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
1948 {
1949     if (!m_hBar || (m_hBar->isOverlayScrollbar() && relevancy == IgnoreOverlayScrollbarSize))
1950         return 0;
1951     return m_hBar->height();
1952 }
1953
1954 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
1955 {
1956     // Currently the resize corner is always the bottom right corner
1957     IntPoint bottomRight(width(), height());
1958     IntPoint localPoint = absoluteToContents(absolutePoint);
1959     return localPoint - bottomRight;
1960 }
1961
1962 bool RenderLayer::hasOverflowControls() const
1963 {
1964     return m_hBar || m_vBar || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
1965 }
1966
1967 void RenderLayer::positionOverflowControls(int tx, int ty)
1968 {
1969     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
1970         return;
1971     
1972     RenderBox* box = renderBox();
1973     if (!box)
1974         return;
1975
1976     const IntRect& borderBox = box->borderBoxRect();
1977     const IntRect& scrollCorner = scrollCornerRect();
1978     IntRect absBounds(borderBox.x() + tx, borderBox.y() + ty, borderBox.width(), borderBox.height());
1979     if (m_vBar)
1980         m_vBar->setFrameRect(IntRect(absBounds.maxX() - box->borderRight() - m_vBar->width(),
1981                                      absBounds.y() + box->borderTop(),
1982                                      m_vBar->width(),
1983                                      absBounds.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height()));
1984
1985     if (m_hBar)
1986         m_hBar->setFrameRect(IntRect(absBounds.x() + box->borderLeft(),
1987                                      absBounds.maxY() - box->borderBottom() - m_hBar->height(),
1988                                      absBounds.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
1989                                      m_hBar->height()));
1990
1991 #if USE(ACCELERATED_COMPOSITING)
1992     if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
1993         if (m_hBar) {
1994             layer->setPosition(IntPoint(m_hBar->frameRect().x() - tx, m_hBar->frameRect().y() - ty));
1995             layer->setSize(m_hBar->frameRect().size());
1996         }
1997         layer->setDrawsContent(m_hBar);
1998     }
1999     if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
2000         if (m_vBar) {
2001             layer->setPosition(IntPoint(m_vBar->frameRect().x() - tx, m_vBar->frameRect().y() - ty));
2002             layer->setSize(m_vBar->frameRect().size());
2003         }
2004         layer->setDrawsContent(m_vBar);
2005     }
2006
2007     if (GraphicsLayer* layer = layerForScrollCorner()) {
2008         const IntRect& scrollCornerAndResizer = scrollCornerAndResizerRect();
2009         layer->setPosition(scrollCornerAndResizer.location());
2010         layer->setSize(scrollCornerAndResizer.size());
2011         layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
2012     }
2013 #endif
2014
2015     if (m_scrollCorner)
2016         m_scrollCorner->setFrameRect(scrollCorner);
2017     if (m_resizer)
2018         m_resizer->setFrameRect(resizerCornerRect(this, borderBox));
2019 }
2020
2021 int RenderLayer::scrollWidth()
2022 {
2023     if (m_scrollDimensionsDirty)
2024         computeScrollDimensions();
2025     return m_scrollSize.width();
2026 }
2027
2028 int RenderLayer::scrollHeight()
2029 {
2030     if (m_scrollDimensionsDirty)
2031         computeScrollDimensions();
2032     return m_scrollSize.height();
2033 }
2034
2035 int RenderLayer::overflowTop() const
2036 {
2037     RenderBox* box = renderBox();
2038     IntRect overflowRect(box->layoutOverflowRect());
2039     box->flipForWritingMode(overflowRect);
2040     return overflowRect.y();
2041 }
2042
2043 int RenderLayer::overflowBottom() const
2044 {
2045     RenderBox* box = renderBox();
2046     IntRect overflowRect(box->layoutOverflowRect());
2047     box->flipForWritingMode(overflowRect);
2048     return overflowRect.maxY();
2049 }
2050
2051 int RenderLayer::overflowLeft() const
2052 {
2053     RenderBox* box = renderBox();
2054     IntRect overflowRect(box->layoutOverflowRect());
2055     box->flipForWritingMode(overflowRect);
2056     return overflowRect.x();
2057 }
2058
2059 int RenderLayer::overflowRight() const
2060 {
2061     RenderBox* box = renderBox();
2062     IntRect overflowRect(box->layoutOverflowRect());
2063     box->flipForWritingMode(overflowRect);
2064     return overflowRect.maxX();
2065 }
2066
2067 void RenderLayer::computeScrollDimensions(bool* needHBar, bool* needVBar)
2068 {
2069     RenderBox* box = renderBox();
2070     ASSERT(box);
2071     
2072     m_scrollDimensionsDirty = false;
2073
2074     m_scrollOverflow.setWidth(overflowLeft() - box->borderLeft());
2075     m_scrollOverflow.setHeight(overflowTop() - box->borderTop());
2076
2077     m_scrollSize.setWidth(overflowRight() - overflowLeft());
2078     m_scrollSize.setHeight(overflowBottom() - overflowTop());
2079     
2080     m_scrollOrigin = IntPoint(-m_scrollOverflow.width(), -m_scrollOverflow.height());
2081
2082     if (needHBar)
2083         *needHBar = m_scrollSize.width() > box->clientWidth();
2084     if (needVBar)
2085         *needVBar = m_scrollSize.height() > box->clientHeight();
2086 }
2087
2088 void RenderLayer::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
2089 {
2090     if (m_overflowStatusDirty) {
2091         m_horizontalOverflow = horizontalOverflow;
2092         m_verticalOverflow = verticalOverflow;
2093         m_overflowStatusDirty = false;
2094         return;
2095     }
2096     
2097     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
2098     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
2099     
2100     if (horizontalOverflowChanged || verticalOverflowChanged) {
2101         m_horizontalOverflow = horizontalOverflow;
2102         m_verticalOverflow = verticalOverflow;
2103         
2104         if (FrameView* frameView = renderer()->document()->view()) {
2105             frameView->scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow),
2106                 renderer()->node());
2107         }
2108     }
2109 }
2110
2111 void RenderLayer::updateScrollInfoAfterLayout()
2112 {
2113     RenderBox* box = renderBox();
2114     if (!box)
2115         return;
2116
2117     m_scrollDimensionsDirty = true;
2118
2119     bool horizontalOverflow, verticalOverflow;
2120     computeScrollDimensions(&horizontalOverflow, &verticalOverflow);
2121
2122     if (box->style()->overflowX() != OMARQUEE) {
2123         // Layout may cause us to be in an invalid scroll position.  In this case we need
2124         // to pull our scroll offsets back to the max (or push them up to the min).
2125         int newX = max(0, min(scrollXOffset(), scrollWidth() - box->clientWidth()));
2126         int newY = max(0, min(scrollYOffset(), scrollHeight() - box->clientHeight()));
2127         if (newX != scrollXOffset() || newY != scrollYOffset()) {
2128             RenderView* view = renderer()->view();
2129             ASSERT(view);
2130             // scrollToOffset() may call updateLayerPositions(), which doesn't work
2131             // with LayoutState.
2132             // FIXME: Remove the disableLayoutState/enableLayoutState if the above changes.
2133             if (view)
2134                 view->disableLayoutState();
2135             scrollToOffset(newX, newY);
2136             if (view)
2137                 view->enableLayoutState();
2138         }
2139     }
2140
2141     bool haveHorizontalBar = m_hBar;
2142     bool haveVerticalBar = m_vBar;
2143     
2144     // overflow:scroll should just enable/disable.
2145     if (renderer()->style()->overflowX() == OSCROLL)
2146         m_hBar->setEnabled(horizontalOverflow);
2147     if (renderer()->style()->overflowY() == OSCROLL)
2148         m_vBar->setEnabled(verticalOverflow);
2149
2150     // A dynamic change from a scrolling overflow to overflow:hidden means we need to get rid of any
2151     // scrollbars that may be present.
2152     if (renderer()->style()->overflowX() == OHIDDEN && haveHorizontalBar)
2153         setHasHorizontalScrollbar(false);
2154     if (renderer()->style()->overflowY() == OHIDDEN && haveVerticalBar)
2155         setHasVerticalScrollbar(false);
2156     
2157     // overflow:auto may need to lay out again if scrollbars got added/removed.
2158     bool scrollbarsChanged = (box->hasAutoHorizontalScrollbar() && haveHorizontalBar != horizontalOverflow) || 
2159                              (box->hasAutoVerticalScrollbar() && haveVerticalBar != verticalOverflow);    
2160     if (scrollbarsChanged) {
2161         if (box->hasAutoHorizontalScrollbar())
2162             setHasHorizontalScrollbar(horizontalOverflow);
2163         if (box->hasAutoVerticalScrollbar())
2164             setHasVerticalScrollbar(verticalOverflow);
2165
2166 #if ENABLE(DASHBOARD_SUPPORT)
2167         // Force an update since we know the scrollbars have changed things.
2168         if (renderer()->document()->hasDashboardRegions())
2169             renderer()->document()->setDashboardRegionsDirty(true);
2170 #endif
2171
2172         renderer()->repaint();
2173
2174         if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
2175             if (!m_inOverflowRelayout) {
2176                 // Our proprietary overflow: overlay value doesn't trigger a layout.
2177                 m_inOverflowRelayout = true;
2178                 renderer()->setNeedsLayout(true, false);
2179                 if (renderer()->isRenderBlock()) {
2180                     RenderBlock* block = toRenderBlock(renderer());
2181                     block->scrollbarsChanged(box->hasAutoHorizontalScrollbar() && haveHorizontalBar != horizontalOverflow,
2182                                              box->hasAutoVerticalScrollbar() && haveVerticalBar != verticalOverflow);
2183                     block->layoutBlock(true);
2184                 } else
2185                     renderer()->layout();
2186                 m_inOverflowRelayout = false;
2187             }
2188         }
2189     }
2190     
2191     // If overflow:scroll is turned into overflow:auto a bar might still be disabled (Bug 11985).
2192     if (m_hBar && box->hasAutoHorizontalScrollbar())
2193         m_hBar->setEnabled(true);
2194     if (m_vBar && box->hasAutoVerticalScrollbar())
2195         m_vBar->setEnabled(true);
2196
2197     // Set up the range (and page step/line step).
2198     if (m_hBar) {
2199         int clientWidth = box->clientWidth();
2200         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
2201         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2202         m_hBar->setProportion(clientWidth, m_scrollSize.width());
2203     }
2204     if (m_vBar) {
2205         int clientHeight = box->clientHeight();
2206         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
2207         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2208         m_vBar->setProportion(clientHeight, m_scrollSize.height());
2209     }
2210  
2211     RenderView* view = renderer()->view();
2212     view->disableLayoutState();
2213     scrollToOffset(scrollXOffset(), scrollYOffset());
2214     view->enableLayoutState();
2215  
2216     if (renderer()->node() && renderer()->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
2217         updateOverflowStatus(horizontalOverflow, verticalOverflow);
2218 }
2219
2220 void RenderLayer::paintOverflowControls(GraphicsContext* context, int tx, int ty, const IntRect& damageRect, bool paintingOverlayControls)
2221 {
2222     // Don't do anything if we have no overflow.
2223     if (!renderer()->hasOverflowClip())
2224         return;
2225
2226     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
2227     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
2228     // will be false, and we should just tell the root layer that there are overlay scrollbars
2229     // that need to be painted. That will cause the second pass through the layer tree to run,
2230     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
2231     // second pass doesn't need to re-enter the RenderTree to get it right.
2232     if (hasOverlayScrollbars() && !paintingOverlayControls) {
2233         RenderView* renderView = renderer()->view();
2234         renderView->layer()->setContainsDirtyOverlayScrollbars(true);
2235         m_cachedOverlayScrollbarOffset = IntPoint(tx, ty);
2236         renderView->frameView()->setContainsScrollableAreaWithOverlayScrollbars(true);
2237         return;
2238     }
2239
2240     // This check is required to avoid painting custom CSS scrollbars twice.
2241     if (paintingOverlayControls && !hasOverlayScrollbars())
2242         return;
2243
2244     int offsetX = tx;
2245     int offsetY = ty;
2246     if (paintingOverlayControls) {
2247         offsetX = m_cachedOverlayScrollbarOffset.x();
2248         offsetY = m_cachedOverlayScrollbarOffset.y();
2249     }
2250
2251     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
2252     // widgets can move without layout occurring (most notably when you scroll a document that
2253     // contains fixed positioned elements).
2254     positionOverflowControls(offsetX, offsetY);
2255
2256     // Now that we're sure the scrollbars are in the right place, paint them.
2257     if (m_hBar
2258 #if USE(ACCELERATED_COMPOSITING)
2259         && !layerForHorizontalScrollbar()
2260 #endif
2261               )
2262         m_hBar->paint(context, damageRect);
2263     if (m_vBar
2264 #if USE(ACCELERATED_COMPOSITING)
2265         && !layerForVerticalScrollbar()
2266 #endif
2267               )
2268         m_vBar->paint(context, damageRect);
2269
2270 #if USE(ACCELERATED_COMPOSITING)
2271     if (layerForScrollCorner())
2272         return;
2273 #endif
2274
2275     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
2276     // edge of the box.
2277     paintScrollCorner(context, offsetX, offsetY, damageRect);
2278     
2279     // Paint our resizer last, since it sits on top of the scroll corner.
2280     paintResizer(context, offsetX, offsetY, damageRect);
2281 }
2282
2283 void RenderLayer::paintScrollCorner(GraphicsContext* context, int tx, int ty, const IntRect& damageRect)
2284 {
2285     RenderBox* box = renderBox();
2286     ASSERT(box);
2287
2288     IntRect cornerRect = scrollCornerRect();
2289     IntRect absRect = IntRect(cornerRect.x() + tx, cornerRect.y() + ty, cornerRect.width(), cornerRect.height());
2290     if (!absRect.intersects(damageRect))
2291         return;
2292
2293     if (context->updatingControlTints()) {
2294         updateScrollCornerStyle();
2295         return;
2296     }
2297
2298     if (m_scrollCorner) {
2299         m_scrollCorner->paintIntoRect(context, LayerOffset(tx, ty), absRect);
2300         return;
2301     }
2302
2303     // We don't want to paint white if we have overlay scrollbars, since we need
2304     // to see what is behind it.
2305     if (!hasOverlayScrollbars())
2306         context->fillRect(absRect, Color::white, box->style()->colorSpace());
2307 }
2308
2309 void RenderLayer::paintResizer(GraphicsContext* context, int tx, int ty, const IntRect& damageRect)
2310 {
2311     if (renderer()->style()->resize() == RESIZE_NONE)
2312         return;
2313
2314     RenderBox* box = renderBox();
2315     ASSERT(box);
2316
2317     IntRect cornerRect = resizerCornerRect(this, box->borderBoxRect());
2318     IntRect absRect = IntRect(cornerRect.x() + tx, cornerRect.y() + ty, cornerRect.width(), cornerRect.height());
2319     if (!absRect.intersects(damageRect))
2320         return;
2321
2322     if (context->updatingControlTints()) {
2323         updateResizerStyle();
2324         return;
2325     }
2326     
2327     if (m_resizer) {
2328         m_resizer->paintIntoRect(context, LayerOffset(tx, ty), absRect);
2329         return;
2330     }
2331
2332     // Paint the resizer control.
2333     DEFINE_STATIC_LOCAL(RefPtr<Image>, resizeCornerImage, (Image::loadPlatformResource("textAreaResizeCorner")));
2334     IntPoint imagePoint(absRect.maxX() - resizeCornerImage->width(), absRect.maxY() - resizeCornerImage->height());
2335     context->drawImage(resizeCornerImage.get(), box->style()->colorSpace(), imagePoint);
2336
2337     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
2338     // Clipping will exclude the right and bottom edges of this frame.
2339     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
2340         GraphicsContextStateSaver stateSaver(*context);
2341         context->clip(absRect);
2342         IntRect largerCorner = absRect;
2343         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
2344         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
2345         context->setStrokeThickness(1.0f);
2346         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
2347         context->drawRect(largerCorner);
2348     }
2349 }
2350
2351 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
2352 {
2353     if (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE)
2354         return false;
2355     
2356     RenderBox* box = renderBox();
2357     ASSERT(box);
2358
2359     IntPoint localPoint = absoluteToContents(absolutePoint);
2360
2361     IntRect localBounds(0, 0, box->width(), box->height());
2362     return resizerCornerRect(this, localBounds).contains(localPoint);
2363 }
2364     
2365 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
2366 {
2367     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2368         return false;
2369
2370     RenderBox* box = renderBox();
2371     ASSERT(box);
2372     
2373     IntRect resizeControlRect;
2374     if (renderer()->style()->resize() != RESIZE_NONE) {
2375         resizeControlRect = resizerCornerRect(this, box->borderBoxRect());
2376         if (resizeControlRect.contains(localPoint))
2377             return true;
2378     }
2379
2380     int resizeControlSize = max(resizeControlRect.height(), 0);
2381
2382     if (m_vBar) {
2383         IntRect vBarRect(box->width() - box->borderRight() - m_vBar->width(), 
2384                          box->borderTop(),
2385                          m_vBar->width(),
2386                          box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
2387         if (vBarRect.contains(localPoint)) {
2388             result.setScrollbar(m_vBar.get());
2389             return true;
2390         }
2391     }
2392
2393     resizeControlSize = max(resizeControlRect.width(), 0);
2394     if (m_hBar) {
2395         IntRect hBarRect(box->borderLeft(),
2396                          box->height() - box->borderBottom() - m_hBar->height(),
2397                          box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
2398                          m_hBar->height());
2399         if (hBarRect.contains(localPoint)) {
2400             result.setScrollbar(m_hBar.get());
2401             return true;
2402         }
2403     }
2404
2405     return false;
2406 }
2407
2408 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
2409 {
2410     return ScrollableArea::scroll(direction, granularity, multiplier);
2411 }
2412
2413 void RenderLayer::paint(GraphicsContext* p, const IntRect& damageRect, PaintBehavior paintBehavior, RenderObject *paintingRoot)
2414 {
2415     OverlapTestRequestMap overlapTestRequests;
2416     paintLayer(this, p, damageRect, paintBehavior, paintingRoot, &overlapTestRequests);
2417     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2418     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
2419         it->first->setOverlapTestResult(false);
2420 }
2421
2422 void RenderLayer::paintOverlayScrollbars(GraphicsContext* p, const IntRect& damageRect, PaintBehavior paintBehavior, RenderObject *paintingRoot)
2423 {
2424     if (!m_containsDirtyOverlayScrollbars)
2425         return;
2426     paintLayer(this, p, damageRect, paintBehavior, paintingRoot, 0, PaintLayerHaveTransparency | PaintLayerTemporaryClipRects 
2427                | PaintLayerPaintingOverlayScrollbars);
2428     m_containsDirtyOverlayScrollbars = false;
2429 }
2430
2431 static void setClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
2432 {
2433     if (paintDirtyRect == clipRect)
2434         return;
2435     p->save();
2436     p->clip(clipRect);
2437 }
2438
2439 static void restoreClip(GraphicsContext* p, const IntRect& paintDirtyRect, const IntRect& clipRect)
2440 {
2441     if (paintDirtyRect == clipRect)
2442         return;
2443     p->restore();
2444 }
2445
2446 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
2447 {
2448     Vector<OverlapTestRequestClient*> overlappedRequestClients;
2449     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2450     IntRect boundingBox = layer->boundingBox(rootLayer);
2451     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
2452         if (!boundingBox.intersects(it->second))
2453             continue;
2454
2455         it->first->setOverlapTestResult(true);
2456         overlappedRequestClients.append(it->first);
2457     }
2458     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
2459         overlapTestRequests.remove(overlappedRequestClients[i]);
2460 }
2461
2462 #if USE(ACCELERATED_COMPOSITING)
2463 static bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
2464 {
2465     return paintingReflection && !layer->has3DTransform();
2466 }
2467 #endif
2468
2469 void RenderLayer::paintLayer(RenderLayer* rootLayer, GraphicsContext* p,
2470                         const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2471                         RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2472                         PaintLayerFlags paintFlags)
2473 {
2474 #if USE(ACCELERATED_COMPOSITING)
2475     if (isComposited()) {
2476         // The updatingControlTints() painting pass goes through compositing layers,
2477         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
2478         if (p->updatingControlTints() || (paintBehavior & PaintBehaviorFlattenCompositingLayers))
2479             paintFlags |= PaintLayerTemporaryClipRects;
2480         else if (!backing()->paintingGoesToWindow() && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)) {
2481             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
2482             return;
2483         }
2484     }
2485 #endif
2486
2487     // Avoid painting layers when stylesheets haven't loaded.  This eliminates FOUC.
2488     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2489     // will do a full repaint().
2490     if (renderer()->document()->didLayoutWithPendingStylesheets() && !renderer()->isRenderView() && !renderer()->isRoot())
2491         return;
2492     
2493     // If this layer is totally invisible then there is nothing to paint.
2494     if (!renderer()->opacity())
2495         return;
2496
2497     if (paintsWithTransparency(paintBehavior))
2498         paintFlags |= PaintLayerHaveTransparency;
2499
2500     // Apply a transform if we have one.  A reflection is considered to be a transform, since it is a flip and a translate.
2501     if (paintsWithTransform(paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
2502         TransformationMatrix layerTransform = renderableTransform(paintBehavior);
2503         // If the transform can't be inverted, then don't paint anything.
2504         if (!layerTransform.isInvertible())
2505             return;
2506
2507         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
2508         // layer from the parent now, assuming there is a parent
2509         if (paintFlags & PaintLayerHaveTransparency) {
2510             if (parent())
2511                 parent()->beginTransparencyLayers(p, rootLayer, paintBehavior);
2512             else
2513                 beginTransparencyLayers(p, rootLayer, paintBehavior);
2514         }
2515
2516         // Make sure the parent's clip rects have been calculated.
2517         IntRect clipRect = paintDirtyRect;
2518         if (parent()) {
2519             clipRect = backgroundClipRect(rootLayer, paintFlags & PaintLayerTemporaryClipRects);
2520             clipRect.intersect(paintDirtyRect);
2521         }
2522         
2523         // Push the parent coordinate space's clip.
2524         setClip(p, paintDirtyRect, clipRect);
2525
2526         // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
2527         // This involves subtracting out the position of the layer in our current coordinate space.
2528         int x = 0;
2529         int y = 0;
2530         convertToLayerCoords(rootLayer, x, y);
2531         TransformationMatrix transform(layerTransform);
2532         transform.translateRight(x, y);
2533         
2534         // Apply the transform.
2535         {
2536             GraphicsContextStateSaver stateSaver(*p);
2537             p->concatCTM(transform.toAffineTransform());
2538
2539             // Now do a paint with the root layer shifted to be us.
2540             paintLayer(this, p, transform.inverse().mapRect(paintDirtyRect), paintBehavior, paintingRoot, overlapTestRequests, paintFlags | PaintLayerAppliedTransform);
2541         }        
2542
2543         // Restore the clip.
2544         restoreClip(p, paintDirtyRect, clipRect);
2545         
2546         return;
2547     }
2548
2549     PaintLayerFlags localPaintFlags = paintFlags & ~PaintLayerAppliedTransform;
2550     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
2551
2552     // Paint the reflection first if we have one.
2553     if (m_reflection && !m_paintingInsideReflection) {
2554         // Mark that we are now inside replica painting.
2555         m_paintingInsideReflection = true;
2556         reflectionLayer()->paintLayer(rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags | PaintLayerPaintingReflection);
2557         m_paintingInsideReflection = false;
2558     }
2559
2560     // Calculate the clip rects we should use.
2561     IntRect layerBounds, damageRect, clipRectToApply, outlineRect;
2562     calculateRects(rootLayer, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect, localPaintFlags & PaintLayerTemporaryClipRects);
2563     int x = layerBounds.x();
2564     int y = layerBounds.y();
2565     int tx = x - renderBoxX();
2566     int ty = y - renderBoxY();
2567                              
2568     // Ensure our lists are up-to-date.
2569     updateCompositingAndLayerListsIfNeeded();
2570
2571     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
2572     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
2573     
2574     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
2575     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
2576     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
2577     // so it will be tested against as we descend through the renderers.
2578     RenderObject* paintingRootForRenderer = 0;
2579     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
2580         paintingRootForRenderer = paintingRoot;
2581
2582     if (overlapTestRequests && isSelfPaintingLayer())
2583         performOverlapTests(*overlapTestRequests, rootLayer, this);
2584
2585     bool paintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
2586
2587     // We want to paint our layer, but only if we intersect the damage rect.
2588     bool shouldPaint = intersectsDamageRect(layerBounds, damageRect, rootLayer) && m_hasVisibleContent && isSelfPaintingLayer();
2589     if (shouldPaint && !selectionOnly && !damageRect.isEmpty() && !paintingOverlayScrollbars) {
2590         // Begin transparency layers lazily now that we know we have to paint something.
2591         if (haveTransparency)
2592             beginTransparencyLayers(p, rootLayer, paintBehavior);
2593         
2594         // Paint our background first, before painting any child layers.
2595         // Establish the clip used to paint our background.
2596         setClip(p, paintDirtyRect, damageRect);
2597
2598         // Paint the background.
2599         PaintInfo paintInfo(p, damageRect, PaintPhaseBlockBackground, false, paintingRootForRenderer, 0);
2600         renderer()->paint(paintInfo, tx, ty);
2601
2602         // Restore the clip.
2603         restoreClip(p, paintDirtyRect, damageRect);
2604     }
2605
2606     // Now walk the sorted list of children with negative z-indices.
2607     paintList(m_negZOrderList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2608
2609     // Now establish the appropriate clip and paint our child RenderObjects.
2610     if (shouldPaint && !clipRectToApply.isEmpty() && !paintingOverlayScrollbars) {
2611         // Begin transparency layers lazily now that we know we have to paint something.
2612         if (haveTransparency)
2613             beginTransparencyLayers(p, rootLayer, paintBehavior);
2614
2615         // Set up the clip used when painting our children.
2616         setClip(p, paintDirtyRect, clipRectToApply);
2617         PaintInfo paintInfo(p, clipRectToApply, 
2618                                           selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
2619                                           forceBlackText, paintingRootForRenderer, 0);
2620         renderer()->paint(paintInfo, tx, ty);
2621         if (!selectionOnly) {
2622             paintInfo.phase = PaintPhaseFloat;
2623             renderer()->paint(paintInfo, tx, ty);
2624             paintInfo.phase = PaintPhaseForeground;
2625             paintInfo.overlapTestRequests = overlapTestRequests;
2626             renderer()->paint(paintInfo, tx, ty);
2627             paintInfo.phase = PaintPhaseChildOutlines;
2628             renderer()->paint(paintInfo, tx, ty);
2629         }
2630
2631         // Now restore our clip.
2632         restoreClip(p, paintDirtyRect, clipRectToApply);
2633     }
2634     
2635     if (!outlineRect.isEmpty() && isSelfPaintingLayer() && !paintingOverlayScrollbars) {
2636         // Paint our own outline
2637         PaintInfo paintInfo(p, outlineRect, PaintPhaseSelfOutline, false, paintingRootForRenderer, 0);
2638         setClip(p, paintDirtyRect, outlineRect);
2639         renderer()->paint(paintInfo, tx, ty);
2640         restoreClip(p, paintDirtyRect, outlineRect);
2641     }
2642     
2643     // Paint any child layers that have overflow.
2644     paintList(m_normalFlowList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2645     
2646     // Now walk the sorted list of children with positive z-indices.
2647     paintList(m_posZOrderList, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, localPaintFlags);
2648         
2649     if (renderer()->hasMask() && shouldPaint && !selectionOnly && !damageRect.isEmpty() && !paintingOverlayScrollbars) {
2650         setClip(p, paintDirtyRect, damageRect);
2651
2652         // Paint the mask.
2653         PaintInfo paintInfo(p, damageRect, PaintPhaseMask, false, paintingRootForRenderer, 0);
2654         renderer()->paint(paintInfo, tx, ty);
2655         
2656         // Restore the clip.
2657         restoreClip(p, paintDirtyRect, damageRect);
2658     }
2659
2660     if (paintingOverlayScrollbars) {
2661         setClip(p, paintDirtyRect, damageRect);
2662         paintOverflowControls(p, tx, ty, damageRect, true);
2663         restoreClip(p, paintDirtyRect, damageRect);
2664     }
2665
2666     // End our transparency layer
2667     if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
2668         p->endTransparencyLayer();
2669         p->restore();
2670         m_usedTransparency = false;
2671     }
2672 }
2673
2674 void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* p,
2675                             const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2676                             RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2677                             PaintLayerFlags paintFlags)
2678 {
2679     if (!list)
2680         return;
2681     
2682     for (size_t i = 0; i < list->size(); ++i) {
2683         RenderLayer* childLayer = list->at(i);
2684         if (!childLayer->isPaginated())
2685             childLayer->paintLayer(rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2686         else
2687             paintPaginatedChildLayer(childLayer, rootLayer, p, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2688     }
2689 }
2690
2691 void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
2692                                            const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2693                                            RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2694                                            PaintLayerFlags paintFlags)
2695 {
2696     // We need to do multiple passes, breaking up our child layer into strips.
2697     Vector<RenderLayer*> columnLayers;
2698     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
2699     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
2700         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
2701             columnLayers.append(curr);
2702         if (curr == ancestorLayer)
2703             break;
2704     }
2705
2706     ASSERT(columnLayers.size());
2707     
2708     paintChildLayerIntoColumns(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags, columnLayers, columnLayers.size() - 1);
2709 }
2710
2711 void RenderLayer::paintChildLayerIntoColumns(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
2712                                              const IntRect& paintDirtyRect, PaintBehavior paintBehavior,
2713                                              RenderObject* paintingRoot, OverlapTestRequestMap* overlapTestRequests,
2714                                              PaintLayerFlags paintFlags, const Vector<RenderLayer*>& columnLayers, size_t colIndex)
2715 {
2716     RenderBlock* columnBlock = toRenderBlock(columnLayers[colIndex]->renderer());
2717
2718     ASSERT(columnBlock && columnBlock->hasColumns());
2719     if (!columnBlock || !columnBlock->hasColumns())
2720         return;
2721     
2722     int layerX = 0;
2723     int layerY = 0;
2724     columnBlock->layer()->convertToLayerCoords(rootLayer, layerX, layerY);
2725     
2726     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
2727
2728     ColumnInfo* colInfo = columnBlock->columnInfo();
2729     unsigned colCount = columnBlock->columnCount(colInfo);
2730     int currLogicalTopOffset = 0;
2731     for (unsigned i = 0; i < colCount; i++) {
2732         // For each rect, we clip to the rect, and then we adjust our coords.
2733         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
2734         columnBlock->flipForWritingMode(colRect);
2735         int logicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - columnBlock->logicalLeftOffsetForContent();
2736         IntSize offset = isHorizontal ? IntSize(logicalLeftOffset, currLogicalTopOffset) : IntSize(currLogicalTopOffset, logicalLeftOffset);
2737
2738         colRect.move(layerX, layerY);
2739
2740         IntRect localDirtyRect(paintDirtyRect);
2741         localDirtyRect.intersect(colRect);
2742         
2743         if (!localDirtyRect.isEmpty()) {
2744             GraphicsContextStateSaver stateSaver(*context);
2745             
2746             // Each strip pushes a clip, since column boxes are specified as being
2747             // like overflow:hidden.
2748             context->clip(colRect);
2749
2750             if (!colIndex) {
2751                 // Apply a translation transform to change where the layer paints.
2752                 TransformationMatrix oldTransform;
2753                 bool oldHasTransform = childLayer->transform();
2754                 if (oldHasTransform)
2755                     oldTransform = *childLayer->transform();
2756                 TransformationMatrix newTransform(oldTransform);
2757                 newTransform.translateRight(offset.width(), offset.height());
2758                 
2759                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
2760                 childLayer->paintLayer(rootLayer, context, localDirtyRect, paintBehavior, paintingRoot, overlapTestRequests, paintFlags);
2761                 if (oldHasTransform)
2762                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
2763                 else
2764                     childLayer->m_transform.clear();
2765             } else {
2766                 // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
2767                 // This involves subtracting out the position of the layer in our current coordinate space.
2768                 int childX = 0;
2769                 int childY = 0;
2770                 columnLayers[colIndex - 1]->convertToLayerCoords(rootLayer, childX, childY);
2771                 TransformationMatrix transform;
2772                 transform.translateRight(childX + offset.width(), childY + offset.height());
2773                 
2774                 // Apply the transform.
2775                 context->concatCTM(transform.toAffineTransform());
2776
2777                 // Now do a paint with the root layer shifted to be the next multicol block.
2778                 paintChildLayerIntoColumns(childLayer, columnLayers[colIndex - 1], context, transform.inverse().mapRect(localDirtyRect), paintBehavior, 
2779                                            paintingRoot, overlapTestRequests, paintFlags, 
2780                                            columnLayers, colIndex - 1);
2781             }
2782         }
2783
2784         // Move to the next position.
2785         int blockDelta = isHorizontal ? colRect.height() : colRect.width();
2786         if (columnBlock->style()->isFlippedBlocksWritingMode())
2787             currLogicalTopOffset += blockDelta;
2788         else
2789             currLogicalTopOffset -= blockDelta;
2790     }
2791 }
2792
2793 static inline IntRect frameVisibleRect(RenderObject* renderer)
2794 {
2795     FrameView* frameView = renderer->document()->view();
2796     if (!frameView)
2797         return IntRect();
2798
2799     return frameView->visibleContentRect();
2800 }
2801
2802 bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
2803 {
2804     renderer()->document()->updateLayout();
2805     
2806     IntRect hitTestArea = renderer()->view()->documentRect();
2807     if (!request.ignoreClipping())
2808         hitTestArea.intersect(frameVisibleRect(renderer()));
2809
2810     RenderLayer* insideLayer = hitTestLayer(this, 0, request, result, hitTestArea, result.point(), false);
2811     if (!insideLayer) {
2812         // We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down, 
2813         // return ourselves. We do this so mouse events continue getting delivered after a drag has 
2814         // exited the WebView, and so hit testing over a scrollbar hits the content document.
2815         if ((request.active() || request.mouseUp()) && renderer()->isRenderView()) {
2816             renderer()->updateHitTestResult(result, result.point());
2817             insideLayer = this;
2818         }
2819     }
2820
2821     // Now determine if the result is inside an anchor - if the urlElement isn't already set.
2822     Node* node = result.innerNode();
2823     if (node && !result.URLElement())
2824         result.setURLElement(static_cast<Element*>(node->enclosingLinkEventParentOrSelf()));
2825
2826     // Next set up the correct :hover/:active state along the new chain.
2827     updateHoverActiveState(request, result);
2828     
2829     // Now return whether we were inside this layer (this will always be true for the root
2830     // layer).
2831     return insideLayer;
2832 }
2833
2834 Node* RenderLayer::enclosingElement() const
2835 {
2836     for (RenderObject* r = renderer(); r; r = r->parent()) {
2837         if (Node* e = r->node())
2838             return e;
2839     }
2840     ASSERT_NOT_REACHED();
2841     return 0;
2842 }
2843
2844 // Compute the z-offset of the point in the transformState.
2845 // This is effectively projecting a ray normal to the plane of ancestor, finding where that
2846 // ray intersects target, and computing the z delta between those two points.
2847 static double computeZOffset(const HitTestingTransformState& transformState)
2848 {
2849     // We got an affine transform, so no z-offset
2850     if (transformState.m_accumulatedTransform.isAffine())
2851         return 0;
2852
2853     // Flatten the point into the target plane
2854     FloatPoint targetPoint = transformState.mappedPoint();
2855     
2856     // Now map the point back through the transform, which computes Z.
2857     FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
2858     return backmappedPoint.z();
2859 }
2860
2861 PassRefPtr<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
2862                                         const IntRect& hitTestRect, const IntPoint& hitTestPoint,
2863                                         const HitTestingTransformState* containerTransformState) const
2864 {
2865     RefPtr<HitTestingTransformState> transformState;
2866     int offsetX = 0;
2867     int offsetY = 0;
2868     if (containerTransformState) {
2869         // If we're already computing transform state, then it's relative to the container (which we know is non-null).
2870         transformState = HitTestingTransformState::create(*containerTransformState);
2871         convertToLayerCoords(containerLayer, offsetX, offsetY);
2872     } else {
2873         // If this is the first time we need to make transform state, then base it off of hitTestPoint,
2874         // which is relative to rootLayer.
2875         transformState = HitTestingTransformState::create(hitTestPoint, FloatQuad(hitTestRect));
2876         convertToLayerCoords(rootLayer, offsetX, offsetY);
2877     }
2878     
2879     RenderObject* containerRenderer = containerLayer ? containerLayer->renderer() : 0;
2880     if (renderer()->shouldUseTransformFromContainer(containerRenderer)) {
2881         TransformationMatrix containerTransform;
2882         renderer()->getTransformFromContainer(containerRenderer, IntSize(offsetX, offsetY), containerTransform);
2883         transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
2884     } else {
2885         transformState->translate(offsetX, offsetY, HitTestingTransformState::AccumulateTransform);
2886     }
2887     
2888     return transformState;
2889 }
2890
2891
2892 static bool isHitCandidate(const RenderLayer* hitLayer, bool canDepthSort, double* zOffset, const HitTestingTransformState* transformState)
2893 {
2894     if (!hitLayer)
2895         return false;
2896
2897     // The hit layer is depth-sorting with other layers, so just say that it was hit.
2898     if (canDepthSort)
2899         return true;
2900     
2901     // We need to look at z-depth to decide if this layer was hit.
2902     if (zOffset) {
2903         ASSERT(transformState);
2904         // This is actually computing our z, but that's OK because the hitLayer is coplanar with us.
2905         double childZOffset = computeZOffset(*transformState);
2906         if (childZOffset > *zOffset) {
2907             *zOffset = childZOffset;
2908             return true;
2909         }
2910         return false;
2911     }
2912
2913     return true;
2914 }
2915
2916 // hitTestPoint and hitTestRect are relative to rootLayer.
2917 // A 'flattening' layer is one preserves3D() == false.
2918 // transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
2919 // transformState.m_lastPlanarPoint is the hitTestPoint in the plane of the containing flattening layer.
2920 // transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
2921 // 
2922 // If zOffset is non-null (which indicates that the caller wants z offset information), 
2923 //  *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
2924 RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
2925                                        const IntRect& hitTestRect, const IntPoint& hitTestPoint, bool appliedTransform,
2926                                        const HitTestingTransformState* transformState, double* zOffset)
2927 {
2928     // The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
2929
2930     bool useTemporaryClipRects = false;
2931 #if USE(ACCELERATED_COMPOSITING)
2932     useTemporaryClipRects = compositor()->inCompositingMode();
2933 #endif
2934     useTemporaryClipRects |= renderer()->view()->frameView()->containsScrollableAreaWithOverlayScrollbars();
2935
2936     IntRect hitTestArea = result.rectForPoint(hitTestPoint);
2937
2938     // Apply a transform if we have one.
2939     if (transform() && !appliedTransform) {
2940         // Make sure the parent's clip rects have been calculated.
2941         if (parent()) {
2942             IntRect clipRect = backgroundClipRect(rootLayer, useTemporaryClipRects, IncludeOverlayScrollbarSize);
2943             // Go ahead and test the enclosing clip now.
2944             if (!clipRect.intersects(hitTestArea))
2945                 return 0;
2946         }
2947
2948         // Create a transform state to accumulate this transform.
2949         RefPtr<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
2950
2951         // If the transform can't be inverted, then don't hit test this layer at all.
2952         if (!newTransformState->m_accumulatedTransform.isInvertible())
2953             return 0;
2954
2955         // Compute the point and the hit test rect in the coords of this layer by using the values
2956         // from the transformState, which store the point and quad in the coords of the last flattened
2957         // layer, and the accumulated transform which lets up map through preserve-3d layers.
2958         //
2959         // We can't just map hitTestPoint and hitTestRect because they may have been flattened (losing z)
2960         // by our container.
2961         IntPoint localPoint = roundedIntPoint(newTransformState->mappedPoint());
2962         IntRect localHitTestRect;
2963 #if USE(ACCELERATED_COMPOSITING)
2964         if (isComposited()) {
2965             // It doesn't make sense to project hitTestRect into the plane of this layer, so use the same bounds we use for painting.
2966             localHitTestRect = backing()->compositedBounds();
2967         } else
2968 #endif
2969             localHitTestRect = newTransformState->mappedQuad().enclosingBoundingBox();
2970
2971         // Now do a hit test with the root layer shifted to be us.
2972         return hitTestLayer(this, containerLayer, request, result, localHitTestRect, localPoint, true, newTransformState.get(), zOffset);
2973     }
2974
2975     // Ensure our lists and 3d status are up-to-date.
2976     updateCompositingAndLayerListsIfNeeded();
2977     update3DTransformedDescendantStatus();
2978     
2979     RefPtr<HitTestingTransformState> localTransformState;
2980     if (appliedTransform) {
2981         // We computed the correct state in the caller (above code), so just reference it.
2982         ASSERT(transformState);
2983         localTransformState = const_cast<HitTestingTransformState*>(transformState);
2984     } else if (transformState || m_has3DTransformedDescendant || preserves3D()) {
2985         // We need transform state for the first time, or to offset the container state, so create it here.
2986         localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
2987     }
2988
2989     // Check for hit test on backface if backface-visibility is 'hidden'
2990     if (localTransformState && renderer()->style()->backfaceVisibility() == BackfaceVisibilityHidden) {
2991         TransformationMatrix invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
2992         // If the z-vector of the matrix is negative, the back is facing towards the viewer.
2993         if (invertedMatrix.m33() < 0)
2994             return 0;
2995     }
2996
2997     RefPtr<HitTestingTransformState> unflattenedTransformState = localTransformState;
2998     if (localTransformState && !preserves3D()) {
2999         // Keep a copy of the pre-flattening state, for computing z-offsets for the container
3000         unflattenedTransformState = HitTestingTransformState::create(*localTransformState);
3001         // This layer is flattening, so flatten the state passed to descendants.
3002         localTransformState->flatten();
3003     }
3004     
3005     // Calculate the clip rects we should use.
3006     IntRect layerBounds;
3007     IntRect bgRect;
3008     IntRect fgRect;
3009     IntRect outlineRect;
3010     calculateRects(rootLayer, hitTestRect, layerBounds, bgRect, fgRect, outlineRect, useTemporaryClipRects, IncludeOverlayScrollbarSize);
3011     
3012     // The following are used for keeping track of the z-depth of the hit point of 3d-transformed
3013     // descendants.
3014     double localZOffset = -numeric_limits<double>::infinity();
3015     double* zOffsetForDescendantsPtr = 0;
3016     double* zOffsetForContentsPtr = 0;
3017     
3018     bool depthSortDescendants = false;
3019     if (preserves3D()) {
3020         depthSortDescendants = true;
3021         // Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
3022         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3023         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3024     } else if (m_has3DTransformedDescendant) {
3025         // Flattening layer with 3d children; use a local zOffset pointer to depth-test children and foreground.
3026         depthSortDescendants = true;
3027         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3028         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3029     } else if (zOffset) {
3030         zOffsetForDescendantsPtr = 0;
3031         // Container needs us to give back a z offset for the hit layer.
3032         zOffsetForContentsPtr = zOffset;
3033     }
3034     
3035     // This variable tracks which layer the mouse ends up being inside. 
3036     RenderLayer* candidateLayer = 0;
3037
3038     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
3039     RenderLayer* hitLayer = hitTestList(m_posZOrderList, rootLayer, request, result, hitTestRect, hitTestPoint,
3040                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3041     if (hitLayer) {
3042         if (!depthSortDescendants)
3043             return hitLayer;
3044         candidateLayer = hitLayer;
3045     }
3046
3047     // Now check our overflow objects.
3048     hitLayer = hitTestList(m_normalFlowList, rootLayer, request, result, hitTestRect, hitTestPoint,
3049                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3050     if (hitLayer) {
3051         if (!depthSortDescendants)
3052             return hitLayer;
3053         candidateLayer = hitLayer;
3054     }
3055
3056     // Next we want to see if the mouse pos is inside the child RenderObjects of the layer.
3057     if (fgRect.intersects(hitTestArea) && isSelfPaintingLayer()) {
3058         // Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
3059         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3060         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestDescendants) &&
3061             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3062             if (result.isRectBasedTest())
3063                 result.append(tempResult);
3064             else
3065                 result = tempResult;
3066             if (!depthSortDescendants)
3067                 return this;
3068             // Foreground can depth-sort with descendant layers, so keep this as a candidate.
3069             candidateLayer = this;
3070         } else if (result.isRectBasedTest())
3071             result.append(tempResult);
3072     }
3073
3074     // Now check our negative z-index children.
3075     hitLayer = hitTestList(m_negZOrderList, rootLayer, request, result, hitTestRect, hitTestPoint,
3076                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3077     if (hitLayer) {
3078         if (!depthSortDescendants)
3079             return hitLayer;
3080         candidateLayer = hitLayer;
3081     }
3082
3083     // If we found a layer, return. Child layers, and foreground always render in front of background.
3084     if (candidateLayer)
3085         return candidateLayer;
3086
3087     if (bgRect.intersects(hitTestArea) && isSelfPaintingLayer()) {
3088         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3089         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestSelf) &&
3090             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3091             if (result.isRectBasedTest())
3092                 result.append(tempResult);
3093             else
3094                 result = tempResult;
3095             return this;
3096         } else if (result.isRectBasedTest())
3097             result.append(tempResult);
3098     }
3099     
3100     return 0;
3101 }
3102
3103 bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const IntRect& layerBounds, const IntPoint& hitTestPoint, HitTestFilter hitTestFilter) const
3104 {
3105     if (!renderer()->hitTest(request, result, hitTestPoint,
3106                             layerBounds.x() - renderBoxX(),
3107                             layerBounds.y() - renderBoxY(), 
3108                             hitTestFilter)) {
3109         // It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
3110         // a rect-based test.
3111         ASSERT(!result.innerNode() || (result.isRectBasedTest() && result.rectBasedTestResult().size()));
3112         return false;
3113     }
3114
3115     // For positioned generated content, we might still not have a
3116     // node by the time we get to the layer level, since none of
3117     // the content in the layer has an element. So just walk up
3118     // the tree.
3119     if (!result.innerNode() || !result.innerNonSharedNode()) {
3120         Node* e = enclosingElement();
3121         if (!result.innerNode())
3122             result.setInnerNode(e);
3123         if (!result.innerNonSharedNode())
3124             result.setInnerNonSharedNode(e);
3125     }
3126         
3127     return true;
3128 }
3129
3130 RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
3131                                       const HitTestRequest& request, HitTestResult& result,
3132                                       const IntRect& hitTestRect, const IntPoint& hitTestPoint,
3133                                       const HitTestingTransformState* transformState, 
3134                                       double* zOffsetForDescendants, double* zOffset,
3135                                       const HitTestingTransformState* unflattenedTransformState,
3136                                       bool depthSortDescendants)
3137 {
3138     if (!list)
3139         return 0;
3140     
3141     RenderLayer* resultLayer = 0;
3142     for (int i = list->size() - 1; i >= 0; --i) {
3143         RenderLayer* childLayer = list->at(i);
3144         RenderLayer* hitLayer = 0;
3145         HitTestResult tempResult(result.point(), result.topPadding(), result.rightPadding(), result.bottomPadding(), result.leftPadding());
3146         if (childLayer->isPaginated())
3147             hitLayer = hitTestPaginatedChildLayer(childLayer, rootLayer, request, tempResult, hitTestRect, hitTestPoint, transformState, zOffsetForDescendants);
3148         else
3149             hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestPoint, false, transformState, zOffsetForDescendants);
3150
3151         // If it a rect-based test, we can safely append the temporary result since it might had hit
3152         // nodes but not necesserily had hitLayer set.
3153         if (result.isRectBasedTest())
3154             result.append(tempResult);
3155
3156         if (isHitCandidate(hitLayer, depthSortDescendants, zOffset, unflattenedTransformState)) {
3157             resultLayer = hitLayer;
3158             if (!result.isRectBasedTest())
3159                 result = tempResult;
3160             if (!depthSortDescendants)
3161                 break;
3162         }
3163     }
3164     
3165     return resultLayer;
3166 }
3167
3168 RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3169                                                      const IntRect& hitTestRect, const IntPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset)
3170 {
3171     Vector<RenderLayer*> columnLayers;
3172     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3173     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3174         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3175             columnLayers.append(curr);
3176         if (curr == ancestorLayer)
3177             break;
3178     }
3179
3180     ASSERT(columnLayers.size());
3181     return hitTestChildLayerColumns(childLayer, rootLayer, request, result, hitTestRect, hitTestPoint, transformState, zOffset,
3182                                     columnLayers, columnLayers.size() - 1);
3183 }
3184
3185 RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3186                                                    const IntRect& hitTestRect, const IntPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset,
3187                                                    const Vector<RenderLayer*>& columnLayers, size_t columnIndex)
3188 {
3189     RenderBlock* columnBlock = toRenderBlock(columnLayers[columnIndex]->renderer());
3190
3191     ASSERT(columnBlock && columnBlock->hasColumns());
3192     if (!columnBlock || !columnBlock->hasColumns())
3193         return 0;
3194     
3195     int layerX = 0;
3196     int layerY = 0;
3197     columnBlock->layer()->convertToLayerCoords(rootLayer, layerX, layerY);
3198     
3199     ColumnInfo* colInfo = columnBlock->columnInfo();
3200     int colCount = columnBlock->columnCount(colInfo);
3201     
3202     // We have to go backwards from the last column to the first.
3203     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3204     int logicalLeft = columnBlock->logicalLeftOffsetForContent();
3205     int currLogicalTopOffset = 0;
3206     int i;
3207     for (i = 0; i < colCount; i++) {
3208         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
3209         int blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3210         if (columnBlock->style()->isFlippedBlocksWritingMode())
3211             currLogicalTopOffset += blockDelta;
3212         else
3213             currLogicalTopOffset -= blockDelta;
3214     }
3215     for (i = colCount - 1; i >= 0; i--) {
3216         // For each rect, we clip to the rect, and then we adjust our coords.
3217         IntRect colRect = columnBlock->columnRectAt(colInfo, i);
3218         columnBlock->flipForWritingMode(colRect);
3219         int currLogicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - logicalLeft;
3220         int blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3221         if (columnBlock->style()->isFlippedBlocksWritingMode())
3222             currLogicalTopOffset -= blockDelta;
3223         else
3224             currLogicalTopOffset += blockDelta;
3225         colRect.move(layerX, layerY);
3226
3227         IntRect localClipRect(hitTestRect);
3228         localClipRect.intersect(colRect);
3229         
3230         IntSize offset = isHorizontal ? IntSize(currLogicalLeftOffset, currLogicalTopOffset) : IntSize(currLogicalTopOffset, currLogicalLeftOffset);
3231
3232         if (!localClipRect.isEmpty() && localClipRect.intersects(result.rectForPoint(hitTestPoint))) {
3233             RenderLayer* hitLayer = 0;
3234             if (!columnIndex) {
3235                 // Apply a translation transform to change where the layer paints.
3236                 TransformationMatrix oldTransform;
3237                 bool oldHasTransform = childLayer->transform();
3238                 if (oldHasTransform)
3239                     oldTransform = *childLayer->transform();
3240                 TransformationMatrix newTransform(oldTransform);
3241                 newTransform.translateRight(offset.width(), offset.height());
3242                 
3243                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3244                 hitLayer = childLayer->hitTestLayer(rootLayer, columnLayers[0], request, result, localClipRect, hitTestPoint, false, transformState, zOffset);
3245                 if (oldHasTransform)
3246                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3247                 else
3248                     childLayer->m_transform.clear();
3249             } else {
3250                 // Adjust the transform such that the renderer's upper left corner will be at (0,0) in user space.
3251                 // This involves subtracting out the position of the layer in our current coordinate space.
3252                 RenderLayer* nextLayer = columnLayers[columnIndex - 1];
3253                 RefPtr<HitTestingTransformState> newTransformState = nextLayer->createLocalTransformState(rootLayer, nextLayer, localClipRect, hitTestPoint, transformState);
3254                 newTransformState->translate(offset.width(), offset.height(), HitTestingTransformState::AccumulateTransform);
3255                 IntPoint localPoint = roundedIntPoint(newTransformState->mappedPoint());
3256                 IntRect localHitTestRect = newTransformState->mappedQuad().enclosingBoundingBox();
3257                 newTransformState->flatten();
3258
3259                 hitLayer = hitTestChildLayerColumns(childLayer, columnLayers[columnIndex - 1], request, result, localHitTestRect, localPoint,
3260                                                     newTransformState.get(), zOffset, columnLayers, columnIndex - 1);
3261             }
3262
3263             if (hitLayer)
3264                 return hitLayer;
3265         }
3266     }
3267
3268     return 0;
3269 }
3270
3271 void RenderLayer::updateClipRects(const RenderLayer* rootLayer, OverlayScrollbarSizeRelevancy relevancy)
3272 {
3273     if (m_clipRects) {
3274         ASSERT(rootLayer == m_clipRectsRoot);
3275         return; // We have the correct cached value.
3276     }
3277     
3278     // For transformed layers, the root layer was shifted to be us, so there is no need to
3279     // examine the parent.  We want to cache clip rects with us as the root.
3280     RenderLayer* parentLayer = rootLayer != this ? parent() : 0;
3281     if (parentLayer)
3282         parentLayer->updateClipRects(rootLayer, relevancy);
3283
3284     ClipRects clipRects;
3285     calculateClipRects(rootLayer, clipRects, true, relevancy);
3286
3287     if (parentLayer && parentLayer->clipRects() && clipRects == *parentLayer->clipRects())
3288         m_clipRects = parentLayer->clipRects();
3289     else
3290         m_clipRects = new (renderer()->renderArena()) ClipRects(clipRects);
3291     m_clipRects->ref();
3292 #ifndef NDEBUG
3293     m_clipRectsRoot = rootLayer;
3294 #endif
3295 }
3296
3297 void RenderLayer::calculateClipRects(const RenderLayer* rootLayer, ClipRects& clipRects, bool useCached, OverlayScrollbarSizeRelevancy relevancy) const
3298 {
3299     if (!parent()) {
3300         // The root layer's clip rect is always infinite.
3301         clipRects.reset(PaintInfo::infiniteRect());
3302         return;
3303     }
3304
3305     // For transformed layers, the root layer was shifted to be us, so there is no need to
3306     // examine the parent.  We want to cache clip rects with us as the root.
3307     RenderLayer* parentLayer = rootLayer != this ? parent() : 0;
3308     
3309     // Ensure that our parent's clip has been calculated so that we can examine the values.
3310     if (parentLayer) {
3311         if (useCached && parentLayer->clipRects())
3312             clipRects = *parentLayer->clipRects();
3313         else
3314             parentLayer->calculateClipRects(rootLayer, clipRects);
3315     }
3316     else
3317         clipRects.reset(PaintInfo::infiniteRect());
3318
3319     // A fixed object is essentially the root of its containing block hierarchy, so when
3320     // we encounter such an object, we reset our clip rects to the fixedClipRect.
3321     if (renderer()->style()->position() == FixedPosition) {
3322         clipRects.setPosClipRect(clipRects.fixedClipRect());
3323         clipRects.setOverflowClipRect(clipRects.fixedClipRect());
3324         clipRects.setFixed(true);
3325     }
3326     else if (renderer()->style()->position() == RelativePosition)
3327         clipRects.setPosClipRect(clipRects.overflowClipRect());
3328     else if (renderer()->style()->position() == AbsolutePosition)
3329         clipRects.setOverflowClipRect(clipRects.posClipRect());
3330     
3331     // Update the clip rects that will be passed to child layers.
3332     if (renderer()->hasOverflowClip() || renderer()->hasClip()) {
3333         // This layer establishes a clip of some kind.
3334         int x = 0;
3335         int y = 0;
3336         convertToLayerCoords(rootLayer, x, y);
3337         RenderView* view = renderer()->view();
3338         ASSERT(view);
3339         if (view && clipRects.fixed() && rootLayer->renderer() == view) {
3340             x -= view->frameView()->scrollXForFixedPosition();
3341             y -= view->frameView()->scrollYForFixedPosition();
3342         }
3343         
3344         if (renderer()->hasOverflowClip()) {
3345             IntRect newOverflowClip = toRenderBox(renderer())->overflowClipRect(x, y, relevancy);
3346             clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
3347             if (renderer()->isPositioned() || renderer()->isRelPositioned())
3348                 clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
3349         }
3350         if (renderer()->hasClip()) {
3351             IntRect newPosClip = toRenderBox(renderer())->clipRect(x, y);
3352             clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
3353             clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
3354             clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
3355         }
3356     }
3357 }
3358
3359 void RenderLayer::parentClipRects(const RenderLayer* rootLayer, ClipRects& clipRects, bool temporaryClipRects, OverlayScrollbarSizeRelevancy relevancy) const
3360 {
3361     ASSERT(parent());
3362     if (temporaryClipRects) {
3363         parent()->calculateClipRects(rootLayer, clipRects, false, relevancy);
3364         return;
3365     }
3366
3367     parent()->updateClipRects(rootLayer, relevancy);
3368     clipRects = *parent()->clipRects();
3369 }
3370
3371 IntRect RenderLayer::backgroundClipRect(const RenderLayer* rootLayer, bool temporaryClipRects, OverlayScrollbarSizeRelevancy relevancy) const
3372 {
3373     IntRect backgroundRect;
3374     if (parent()) {
3375         ClipRects parentRects;
3376         parentClipRects(rootLayer, parentRects, temporaryClipRects, relevancy);
3377         backgroundRect = renderer()->style()->position() == FixedPosition ? parentRects.fixedClipRect() :
3378                          (renderer()->isPositioned() ? parentRects.posClipRect() : 
3379                                                        parentRects.overflowClipRect());
3380         RenderView* view = renderer()->view();
3381         ASSERT(view);
3382         if (view && parentRects.fixed() && rootLayer->renderer() == view)
3383             backgroundRect.move(view->frameView()->scrollXForFixedPosition(), view->frameView()->scrollYForFixedPosition());
3384     }
3385     return backgroundRect;
3386 }
3387
3388 void RenderLayer::calculateRects(const RenderLayer* rootLayer, const IntRect& paintDirtyRect, IntRect& layerBounds,
3389                                  IntRect& backgroundRect, IntRect& foregroundRect, IntRect& outlineRect, bool temporaryClipRects,
3390                                  OverlayScrollbarSizeRelevancy relevancy) const
3391 {
3392     if (rootLayer != this && parent()) {
3393         backgroundRect = backgroundClipRect(rootLayer, temporaryClipRects, relevancy);
3394         backgroundRect.intersect(paintDirtyRect);
3395     } else
3396         backgroundRect = paintDirtyRect;
3397
3398     foregroundRect = backgroundRect;
3399     outlineRect = backgroundRect;
3400     
3401     int x = 0;
3402     int y = 0;
3403     convertToLayerCoords(rootLayer, x, y);
3404     layerBounds = IntRect(x, y, width(), height());
3405     
3406     // Update the clip rects that will be passed to child layers.
3407     if (renderer()->hasOverflowClip() || renderer()->hasClip()) {
3408         // This layer establishes a clip of some kind.
3409         if (renderer()->hasOverflowClip())
3410             foregroundRect.intersect(toRenderBox(renderer())->overflowClipRect(x, y, relevancy));
3411         if (renderer()->hasClip()) {
3412             // Clip applies to *us* as well, so go ahead and update the damageRect.
3413             IntRect newPosClip = toRenderBox(renderer())->clipRect(x, y);
3414             backgroundRect.intersect(newPosClip);
3415             foregroundRect.intersect(newPosClip);
3416             outlineRect.intersect(newPosClip);
3417         }
3418
3419         // If we establish a clip at all, then go ahead and make sure our background
3420         // rect is intersected with our layer's bounds.
3421         // FIXME: This could be changed to just use generic visual overflow.
3422         // See https://bugs.webkit.org/show_bug.cgi?id=37467 for more information.
3423         if (const ShadowData* boxShadow = renderer()->style()->boxShadow()) {
3424             IntRect overflow = layerBounds;
3425             do {
3426                 if (boxShadow->style() == Normal) {
3427                     IntRect shadowRect = layerBounds;
3428                     shadowRect.move(boxShadow->x(), boxShadow->y());
3429                     shadowRect.inflate(boxShadow->blur() + boxShadow->spread());
3430                     overflow.unite(shadowRect);
3431                 }
3432
3433                 boxShadow = boxShadow->next();
3434             } while (boxShadow);
3435             backgroundRect.intersect(overflow);
3436         } else
3437             backgroundRect.intersect(layerBounds);
3438     }
3439 }
3440
3441 IntRect RenderLayer::childrenClipRect() const
3442 {
3443     RenderView* renderView = renderer()->view();
3444     RenderLayer* clippingRootLayer = clippingRoot();
3445     IntRect layerBounds, backgroundRect, foregroundRect, outlineRect;
3446     calculateRects(clippingRootLayer, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
3447     return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(foregroundRect)).enclosingBoundingBox();
3448 }
3449
3450 IntRect RenderLayer::selfClipRect() const
3451 {
3452     RenderView* renderView = renderer()->view();
3453     RenderLayer* clippingRootLayer = clippingRoot();
3454     IntRect layerBounds, backgroundRect, foregroundRect, outlineRect;
3455     calculateRects(clippingRootLayer, renderView->documentRect(), layerBounds, backgroundRect, foregroundRect, outlineRect);
3456     return clippingRootLayer->renderer()->localToAbsoluteQuad(FloatQuad(backgroundRect)).enclosingBoundingBox();
3457 }
3458
3459 void RenderLayer::addBlockSelectionGapsBounds(const IntRect& bounds)
3460 {
3461     m_blockSelectionGapsBounds.unite(bounds);
3462 }
3463
3464 void RenderLayer::clearBlockSelectionGapsBounds()
3465 {
3466     m_blockSelectionGapsBounds = IntRect();
3467     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3468         child->clearBlockSelectionGapsBounds();
3469 }
3470
3471 void RenderLayer::repaintBlockSelectionGaps()
3472 {
3473     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3474         child->repaintBlockSelectionGaps();
3475
3476     if (m_blockSelectionGapsBounds.isEmpty())
3477         return;
3478
3479     IntRect rect = m_blockSelectionGapsBounds;
3480     rect.move(-scrolledContentOffset());
3481     if (renderer()->hasOverflowClip())
3482         rect.intersect(toRenderBox(renderer())->overflowClipRect(0, 0));
3483     if (renderer()->hasClip())
3484         rect.intersect(toRenderBox(renderer())->clipRect(0, 0));
3485     if (!rect.isEmpty())
3486         renderer()->repaintRectangle(rect);
3487 }
3488
3489 bool RenderLayer::intersectsDamageRect(const IntRect& layerBounds, const IntRect& damageRect, const RenderLayer* rootLayer) const
3490 {
3491     // Always examine the canvas and the root.
3492     // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
3493     // paints the root's background.
3494     if (renderer()->isRenderView() || renderer()->isRoot())
3495         return true;
3496
3497     // If we aren't an inline flow, and our layer bounds do intersect the damage rect, then we 
3498     // can go ahead and return true.
3499     RenderView* view = renderer()->view();
3500     ASSERT(view);
3501     if (view && !renderer()->isRenderInline()) {
3502         IntRect b = layerBounds;
3503         b.inflate(view->maximalOutlineSize());
3504         if (b.intersects(damageRect))
3505             return true;
3506     }
3507         
3508     // Otherwise we need to compute the bounding box of this single layer and see if it intersects
3509     // the damage rect.
3510     return boundingBox(rootLayer).intersects(damageRect);
3511 }
3512
3513 IntRect RenderLayer::localBoundingBox() const
3514 {
3515     // There are three special cases we need to consider.
3516     // (1) Inline Flows.  For inline flows we will create a bounding box that fully encompasses all of the lines occupied by the
3517     // inline.  In other words, if some <span> wraps to three lines, we'll create a bounding box that fully encloses the
3518     // line boxes of all three lines (including overflow on those lines).
3519     // (2) Left/Top Overflow.  The width/height of layers already includes right/bottom overflow.  However, in the case of left/top
3520     // overflow, we have to create a bounding box that will extend to include this overflow.
3521     // (3) Floats.  When a layer has overhanging floats that it paints, we need to make sure to include these overhanging floats
3522     // as part of our bounding box.  We do this because we are the responsible layer for both hit testing and painting those
3523     // floats.
3524     IntRect result;
3525     if (renderer()->isRenderInline())
3526         result = toRenderInline(renderer())->linesVisualOverflowBoundingBox();
3527     else if (renderer()->isTableRow()) {
3528         // Our bounding box is just the union of all of our cells' border/overflow rects.
3529         for (RenderObject* child = renderer()->firstChild(); child; child = child->nextSibling()) {
3530             if (child->isTableCell()) {
3531                 IntRect bbox = toRenderBox(child)->borderBoxRect();
3532                 result.unite(bbox);
3533                 IntRect overflowRect = renderBox()->visualOverflowRect();
3534                 if (bbox != overflowRect)
3535                     result.unite(overflowRect);
3536             }
3537         }
3538     } else {
3539         RenderBox* box = renderBox();
3540         ASSERT(box);
3541         if (box->hasMask())
3542             result = box->maskClipRect();
3543         else {
3544             IntRect bbox = box->borderBoxRect();
3545             result = bbox;
3546             IntRect overflowRect = box->visualOverflowRect();
3547             if (bbox != overflowRect)
3548                 result.unite(overflowRect);
3549         }
3550     }
3551
3552     RenderView* view = renderer()->view();
3553     ASSERT(view);
3554     if (view)
3555         result.inflate(view->maximalOutlineSize()); // Used to apply a fudge factor to dirty-rect checks on blocks/tables.
3556
3557     return result;
3558 }
3559
3560 IntRect RenderLayer::boundingBox(const RenderLayer* ancestorLayer) const
3561 {    
3562     IntRect result = localBoundingBox();
3563     if (renderer()->isBox())
3564         renderBox()->flipForWritingMode(result);
3565     else
3566         renderer()->containingBlock()->flipForWritingMode(result);
3567     int deltaX = 0, deltaY = 0;
3568     convertToLayerCoords(ancestorLayer, deltaX, deltaY);
3569     result.move(deltaX, deltaY);
3570     return result;
3571 }
3572
3573 IntRect RenderLayer::absoluteBoundingBox() const
3574 {
3575     return boundingBox(root());
3576 }
3577
3578 void RenderLayer::clearClipRectsIncludingDescendants()
3579 {
3580     if (!m_clipRects)
3581         return;
3582
3583     clearClipRects();
3584     
3585     for (RenderLayer* l = firstChild(); l; l = l->nextSibling())
3586         l->clearClipRectsIncludingDescendants();
3587 }
3588
3589 void RenderLayer::clearClipRects()
3590 {
3591     if (m_clipRects) {
3592         m_clipRects->deref(renderer()->renderArena());
3593         m_clipRects = 0;
3594 #ifndef NDEBUG
3595         m_clipRectsRoot = 0;
3596 #endif    
3597     }
3598 }
3599
3600 #if USE(ACCELERATED_COMPOSITING)
3601 RenderLayerBacking* RenderLayer::ensureBacking()
3602 {
3603     if (!m_backing)
3604         m_backing = adoptPtr(new RenderLayerBacking(this));
3605     return m_backing.get();
3606 }
3607
3608 void RenderLayer::clearBacking()
3609 {
3610     m_backing.clear();
3611 }
3612
3613 bool RenderLayer::hasCompositedMask() const
3614 {
3615     return m_backing && m_backing->hasMaskLayer();
3616 }
3617
3618 GraphicsLayer* RenderLayer::layerForHorizontalScrollbar() const
3619 {
3620     return m_backing ? m_backing->layerForHorizontalScrollbar() : 0;
3621 }
3622
3623 GraphicsLayer* RenderLayer::layerForVerticalScrollbar() const
3624 {
3625     return m_backing ? m_backing->layerForVerticalScrollbar() : 0;
3626 }
3627
3628 GraphicsLayer* RenderLayer::layerForScrollCorner() const
3629 {
3630     return m_backing ? m_backing->layerForScrollCorner() : 0;
3631 }
3632 #endif
3633
3634 bool RenderLayer::paintsWithTransform(PaintBehavior paintBehavior) const
3635 {
3636 #if USE(ACCELERATED_COMPOSITING)
3637     bool paintsToWindow = !isComposited() || backing()->paintingGoesToWindow();
3638 #else
3639     bool paintsToWindow = true;
3640 #endif    
3641     return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || paintsToWindow);
3642 }
3643
3644 void RenderLayer::setParent(RenderLayer* parent)
3645 {
3646     if (parent == m_parent)
3647         return;
3648
3649 #if USE(ACCELERATED_COMPOSITING)
3650     if (m_parent && !renderer()->documentBeingDestroyed())
3651         compositor()->layerWillBeRemoved(m_parent, this);
3652 #endif
3653     
3654     m_parent = parent;
3655     
3656 #if USE(ACCELERATED_COMPOSITING)
3657     if (m_parent && !renderer()->documentBeingDestroyed())
3658         compositor()->layerWasAdded(m_parent, this);
3659 #endif
3660 }
3661
3662 static RenderObject* commonAncestor(RenderObject* obj1, RenderObject* obj2)
3663 {
3664     if (!obj1 || !obj2)
3665         return 0;
3666
3667     for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor())
3668         for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor())
3669             if (currObj1 == currObj2)
3670                 return currObj1;
3671
3672     return 0;
3673 }
3674
3675 void RenderLayer::updateHoverActiveState(const HitTestRequest& request, HitTestResult& result)
3676 {
3677     // We don't update :hover/:active state when the result is marked as readOnly.
3678     if (request.readOnly())
3679         return;
3680
3681     Document* doc = renderer()->document();
3682
3683     Node* activeNode = doc->activeNode();
3684     if (activeNode && !request.active()) {
3685         // We are clearing the :active chain because the mouse has been released.
3686         for (RenderObject* curr = activeNode->renderer(); curr; curr = curr->parent()) {
3687             if (curr->node() && !curr->isText())
3688                 curr->node()->clearInActiveChain();
3689         }
3690         doc->setActiveNode(0);
3691     } else {
3692         Node* newActiveNode = result.innerNode();
3693         if (!activeNode && newActiveNode && request.active()) {
3694             // We are setting the :active chain and freezing it. If future moves happen, they
3695             // will need to reference this chain.
3696             for (RenderObject* curr = newActiveNode->renderer(); curr; curr = curr->parent()) {
3697                 if (curr->node() && !curr->isText()) {
3698                     curr->node()->setInActiveChain();
3699                 }
3700             }
3701             doc->setActiveNode(newActiveNode);
3702         }
3703     }
3704
3705     // If the mouse is down and if this is a mouse move event, we want to restrict changes in 
3706     // :hover/:active to only apply to elements that are in the :active chain that we froze
3707     // at the time the mouse went down.
3708     bool mustBeInActiveChain = request.active() && request.mouseMove();
3709
3710     // Check to see if the hovered node has changed.  If not, then we don't need to
3711     // do anything.  
3712     RefPtr<Node> oldHoverNode = doc->hoverNode();
3713     Node* newHoverNode = result.innerNode();
3714
3715     // Update our current hover node.
3716     doc->setHoverNode(newHoverNode);
3717
3718     // We have two different objects.  Fetch their renderers.
3719     RenderObject* oldHoverObj = oldHoverNode ? oldHoverNode->renderer() : 0;
3720     RenderObject* newHoverObj = newHoverNode ? newHoverNode->renderer() : 0;
3721     
3722     // Locate the common ancestor render object for the two renderers.
3723     RenderObject* ancestor = commonAncestor(oldHoverObj, newHoverObj);
3724
3725     Vector<RefPtr<Node>, 32> nodesToRemoveFromChain;
3726     Vector<RefPtr<Node>, 32> nodesToAddToChain;
3727
3728     if (oldHoverObj != newHoverObj) {
3729         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
3730         for (RenderObject* curr = oldHoverObj; curr && curr != ancestor; curr = curr->hoverAncestor()) {
3731             if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
3732                 nodesToRemoveFromChain.append(curr->node());
3733         }
3734     }
3735
3736     // Now set the hover state for our new object up to the root.
3737     for (RenderObject* curr = newHoverObj; curr; curr = curr->hoverAncestor()) {
3738         if (curr->node() && !curr->isText() && (!mustBeInActiveChain || curr->node()->inActiveChain()))
3739             nodesToAddToChain.append(curr->node());
3740     }
3741
3742     size_t removeCount = nodesToRemoveFromChain.size();
3743     for (size_t i = 0; i < removeCount; ++i) {
3744         nodesToRemoveFromChain[i]->setActive(false);
3745         nodesToRemoveFromChain[i]->setHovered(false);
3746     }
3747
3748     size_t addCount = nodesToAddToChain.size();
3749     for (size_t i = 0; i < addCount; ++i) {
3750         nodesToAddToChain[i]->setActive(request.active());
3751         nodesToAddToChain[i]->setHovered(true);
3752     }
3753 }
3754
3755 // Helper for the sorting of layers by z-index.
3756 static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
3757 {
3758     return first->zIndex() < second->zIndex();
3759 }
3760
3761 void RenderLayer::dirtyZOrderLists()
3762 {
3763     if (m_posZOrderList)
3764         m_posZOrderList->clear();
3765     if (m_negZOrderList)
3766         m_negZOrderList->clear();
3767     m_zOrderListsDirty = true;
3768
3769 #if USE(ACCELERATED_COMPOSITING)
3770     if (!renderer()->documentBeingDestroyed())
3771         compositor()->setCompositingLayersNeedRebuild();
3772 #endif
3773 }
3774
3775 void RenderLayer::dirtyStackingContextZOrderLists()
3776 {
3777     RenderLayer* sc = stackingContext();
3778     if (sc)
3779         sc->dirtyZOrderLists();
3780 }
3781
3782 void RenderLayer::dirtyNormalFlowList()
3783 {
3784     if (m_normalFlowList)
3785         m_normalFlowList->clear();
3786     m_normalFlowListDirty = true;
3787
3788 #if USE(ACCELERATED_COMPOSITING)
3789     if (!renderer()->documentBeingDestroyed())
3790         compositor()->setCompositingLayersNeedRebuild();
3791 #endif
3792 }
3793
3794 void RenderLayer::updateZOrderLists()
3795 {
3796     if (!isStackingContext() || !m_zOrderListsDirty)
3797         return;
3798
3799     for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
3800         if (!m_reflection || reflectionLayer() != child)
3801             child->collectLayers(m_posZOrderList, m_negZOrderList);
3802
3803     // Sort the two lists.
3804     if (m_posZOrderList)
3805         std::stable_sort(m_posZOrderList->begin(), m_posZOrderList->end(), compareZIndex);
3806
3807     if (m_negZOrderList)
3808         std::stable_sort(m_negZOrderList->begin(), m_negZOrderList->end(), compareZIndex);
3809
3810     m_zOrderListsDirty = false;
3811 }
3812
3813 void RenderLayer::updateNormalFlowList()
3814 {
3815     if (!m_normalFlowListDirty)
3816         return;
3817         
3818     for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
3819         // Ignore non-overflow layers and reflections.
3820         if (child->isNormalFlowOnly() && (!m_reflection || reflectionLayer() != child)) {
3821             if (!m_normalFlowList)
3822                 m_normalFlowList = new Vector<RenderLayer*>;
3823             m_normalFlowList->append(child);
3824         }
3825     }
3826     
3827     m_normalFlowListDirty = false;
3828 }
3829
3830 void RenderLayer::collectLayers(Vector<RenderLayer*>*& posBuffer, Vector<RenderLayer*>*& negBuffer)
3831 {
3832     updateVisibilityStatus();
3833
3834     // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
3835     if ((m_hasVisibleContent || (m_hasVisibleDescendant && isStackingContext())) && !isNormalFlowOnly()) {
3836         // Determine which buffer the child should be in.
3837         Vector<RenderLayer*>*& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
3838
3839         // Create the buffer if it doesn't exist yet.
3840         if (!buffer)
3841             buffer = new Vector<RenderLayer*>;
3842         
3843         // Append ourselves at the end of the appropriate buffer.
3844         buffer->append(this);
3845     }
3846
3847     // Recur into our children to collect more layers, but only if we don't establish
3848     // a stacking context.
3849     if (m_hasVisibleDescendant && !isStackingContext()) {
3850         for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
3851             // Ignore reflections.
3852             if (!m_reflection || reflectionLayer() != child)
3853                 child->collectLayers(posBuffer, negBuffer);