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