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