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