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