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