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