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