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