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