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