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