[CSS Filters] Blur filter is not repainted correctly when applied on a parent of...
[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 #if ENABLE(DASHBOARD_SUPPORT)
2538         // Force an update since we know the scrollbars have changed things.
2539         if (renderer()->document()->hasDashboardRegions())
2540             renderer()->document()->setDashboardRegionsDirty(true);
2541 #endif
2542
2543         renderer()->repaint();
2544
2545         if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
2546             if (!m_inOverflowRelayout) {
2547                 // Our proprietary overflow: overlay value doesn't trigger a layout.
2548                 m_inOverflowRelayout = true;
2549                 renderer()->setNeedsLayout(true, MarkOnlyThis);
2550                 if (renderer()->isRenderBlock()) {
2551                     RenderBlock* block = toRenderBlock(renderer());
2552                     block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
2553                     block->layoutBlock(true);
2554                 } else
2555                     renderer()->layout();
2556                 m_inOverflowRelayout = false;
2557             }
2558         }
2559     }
2560
2561     // Set up the range (and page step/line step).
2562     if (m_hBar) {
2563         int clientWidth = box->pixelSnappedClientWidth();
2564         int pageStep = max(max<int>(clientWidth * Scrollbar::minFractionToStepWhenPaging(), clientWidth - Scrollbar::maxOverlapBetweenPages()), 1);
2565         m_hBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2566         m_hBar->setProportion(clientWidth, m_scrollSize.width());
2567     }
2568     if (m_vBar) {
2569         int clientHeight = box->pixelSnappedClientHeight();
2570         int pageStep = max(max<int>(clientHeight * Scrollbar::minFractionToStepWhenPaging(), clientHeight - Scrollbar::maxOverlapBetweenPages()), 1);
2571         m_vBar->setSteps(Scrollbar::pixelsPerLineStep(), pageStep);
2572         m_vBar->setProportion(clientHeight, m_scrollSize.height());
2573     }
2574
2575     updateScrollableAreaSet((hasHorizontalOverflow || hasVerticalOverflow) && scrollsOverflow());
2576 }
2577
2578 void RenderLayer::updateScrollInfoAfterLayout()
2579 {
2580     RenderBox* box = renderBox();
2581     if (!box)
2582         return;
2583
2584     m_scrollDimensionsDirty = true;
2585     IntSize originalScrollOffset = scrollOffset();
2586
2587     computeScrollDimensions();
2588
2589     if (box->style()->overflowX() != OMARQUEE) {
2590         // Layout may cause us to be at an invalid scroll position. In this case we need
2591         // to pull our scroll offsets back to the max (or push them up to the min).
2592         IntSize clampedScrollOffset = clampScrollOffset(scrollOffset());
2593         if (clampedScrollOffset != scrollOffset())
2594             scrollToOffset(clampedScrollOffset);
2595     }
2596
2597     updateScrollbarsAfterLayout();
2598
2599     if (originalScrollOffset != scrollOffset())
2600         scrollToOffsetWithoutAnimation(toPoint(scrollOffset()));
2601 }
2602
2603 void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
2604 {
2605     // Don't do anything if we have no overflow.
2606     if (!renderer()->hasOverflowClip())
2607         return;
2608
2609     // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
2610     // on top of everything else. If this is the normal painting pass, paintingOverlayControls
2611     // will be false, and we should just tell the root layer that there are overlay scrollbars
2612     // that need to be painted. That will cause the second pass through the layer tree to run,
2613     // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the 
2614     // second pass doesn't need to re-enter the RenderTree to get it right.
2615     if (hasOverlayScrollbars() && !paintingOverlayControls) {
2616         m_cachedOverlayScrollbarOffset = paintOffset;
2617 #if USE(ACCELERATED_COMPOSITING)
2618         // It's not necessary to do the second pass if the scrollbars paint into layers.
2619         if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
2620             return;
2621 #endif
2622         RenderView* renderView = renderer()->view();
2623         renderView->layer()->setContainsDirtyOverlayScrollbars(true);
2624         renderView->frameView()->setContainsScrollableAreaWithOverlayScrollbars(true);
2625         return;
2626     }
2627
2628     // This check is required to avoid painting custom CSS scrollbars twice.
2629     if (paintingOverlayControls && !hasOverlayScrollbars())
2630         return;
2631
2632     IntPoint adjustedPaintOffset = paintOffset;
2633     if (paintingOverlayControls)
2634         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
2635
2636     // Move the scrollbar widgets if necessary.  We normally move and resize widgets during layout, but sometimes
2637     // widgets can move without layout occurring (most notably when you scroll a document that
2638     // contains fixed positioned elements).
2639     positionOverflowControls(toSize(adjustedPaintOffset));
2640
2641     // Now that we're sure the scrollbars are in the right place, paint them.
2642     if (m_hBar
2643 #if USE(ACCELERATED_COMPOSITING)
2644         && !layerForHorizontalScrollbar()
2645 #endif
2646               )
2647         m_hBar->paint(context, damageRect);
2648     if (m_vBar
2649 #if USE(ACCELERATED_COMPOSITING)
2650         && !layerForVerticalScrollbar()
2651 #endif
2652               )
2653         m_vBar->paint(context, damageRect);
2654
2655 #if USE(ACCELERATED_COMPOSITING)
2656     if (layerForScrollCorner())
2657         return;
2658 #endif
2659
2660     // We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
2661     // edge of the box.
2662     paintScrollCorner(context, adjustedPaintOffset, damageRect);
2663     
2664     // Paint our resizer last, since it sits on top of the scroll corner.
2665     paintResizer(context, adjustedPaintOffset, damageRect);
2666 }
2667
2668 void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2669 {
2670     RenderBox* box = renderBox();
2671     ASSERT(box);
2672
2673     IntRect absRect = scrollCornerRect();
2674     absRect.moveBy(paintOffset);
2675     if (!absRect.intersects(damageRect))
2676         return;
2677
2678     if (context->updatingControlTints()) {
2679         updateScrollCornerStyle();
2680         return;
2681     }
2682
2683     if (m_scrollCorner) {
2684         m_scrollCorner->paintIntoRect(context, paintOffset, absRect);
2685         return;
2686     }
2687
2688     // We don't want to paint white if we have overlay scrollbars, since we need
2689     // to see what is behind it.
2690     if (!hasOverlayScrollbars())
2691         context->fillRect(absRect, Color::white, box->style()->colorSpace());
2692 }
2693
2694 void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
2695 {
2696     float deviceScaleFactor = WebCore::deviceScaleFactor(renderer()->frame());
2697
2698     RefPtr<Image> resizeCornerImage;
2699     IntSize cornerResizerSize;
2700     if (deviceScaleFactor >= 2) {
2701         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
2702         resizeCornerImage = resizeCornerImageHiRes;
2703         cornerResizerSize = resizeCornerImage->size();
2704         cornerResizerSize.scale(0.5f);
2705     } else {
2706         DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
2707         resizeCornerImage = resizeCornerImageLoRes;
2708         cornerResizerSize = resizeCornerImage->size();
2709     }
2710
2711     if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
2712         context->save();
2713         context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
2714         context->scale(FloatSize(-1.0, 1.0));
2715         context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), IntRect(IntPoint(), cornerResizerSize));
2716         context->restore();
2717         return;
2718     }
2719     IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
2720     context->drawImage(resizeCornerImage.get(), renderer()->style()->colorSpace(), imageRect);
2721 }
2722
2723 void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
2724 {
2725     if (renderer()->style()->resize() == RESIZE_NONE)
2726         return;
2727
2728     RenderBox* box = renderBox();
2729     ASSERT(box);
2730
2731     IntRect absRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2732     absRect.moveBy(paintOffset);
2733     if (!absRect.intersects(damageRect))
2734         return;
2735
2736     if (context->updatingControlTints()) {
2737         updateResizerStyle();
2738         return;
2739     }
2740     
2741     if (m_resizer) {
2742         m_resizer->paintIntoRect(context, paintOffset, absRect);
2743         return;
2744     }
2745
2746     drawPlatformResizerImage(context, absRect);
2747
2748     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
2749     // Clipping will exclude the right and bottom edges of this frame.
2750     if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
2751         GraphicsContextStateSaver stateSaver(*context);
2752         context->clip(absRect);
2753         IntRect largerCorner = absRect;
2754         largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
2755         context->setStrokeColor(Color(makeRGB(217, 217, 217)), ColorSpaceDeviceRGB);
2756         context->setStrokeThickness(1.0f);
2757         context->setFillColor(Color::transparent, ColorSpaceDeviceRGB);
2758         context->drawRect(largerCorner);
2759     }
2760 }
2761
2762 bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint) const
2763 {
2764     if (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE)
2765         return false;
2766     
2767     RenderBox* box = renderBox();
2768     ASSERT(box);
2769
2770     IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
2771
2772     IntRect localBounds(0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
2773     return resizerCornerRect(this, localBounds).contains(localPoint);
2774 }
2775     
2776 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
2777 {
2778     if (!m_hBar && !m_vBar && (!renderer()->hasOverflowClip() || renderer()->style()->resize() == RESIZE_NONE))
2779         return false;
2780
2781     RenderBox* box = renderBox();
2782     ASSERT(box);
2783     
2784     IntRect resizeControlRect;
2785     if (renderer()->style()->resize() != RESIZE_NONE) {
2786         resizeControlRect = resizerCornerRect(this, box->pixelSnappedBorderBoxRect());
2787         if (resizeControlRect.contains(localPoint))
2788             return true;
2789     }
2790
2791     int resizeControlSize = max(resizeControlRect.height(), 0);
2792
2793     if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
2794         LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
2795                             box->borderTop(),
2796                             m_vBar->width(),
2797                             box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
2798         if (vBarRect.contains(localPoint)) {
2799             result.setScrollbar(m_vBar.get());
2800             return true;
2801         }
2802     }
2803
2804     resizeControlSize = max(resizeControlRect.width(), 0);
2805     if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
2806         LayoutRect hBarRect(horizontalScrollbarStart(0),
2807                             box->height() - box->borderBottom() - m_hBar->height(),
2808                             box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
2809                             m_hBar->height());
2810         if (hBarRect.contains(localPoint)) {
2811             result.setScrollbar(m_hBar.get());
2812             return true;
2813         }
2814     }
2815
2816     return false;
2817 }
2818
2819 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
2820 {
2821     return ScrollableArea::scroll(direction, granularity, multiplier);
2822 }
2823
2824 void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
2825 {
2826     OverlapTestRequestMap overlapTestRequests;
2827     paintLayer(this, context, damageRect, paintBehavior, paintingRoot, region, &overlapTestRequests, paintFlags);
2828     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2829     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it)
2830         it->first->setOverlapTestResult(false);
2831 }
2832
2833 void RenderLayer::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot)
2834 {
2835     if (!m_containsDirtyOverlayScrollbars)
2836         return;
2837     paintLayer(this, context, damageRect, paintBehavior, paintingRoot, 0, 0, PaintLayerHaveTransparency | PaintLayerTemporaryClipRects 
2838                | PaintLayerPaintingOverlayScrollbars);
2839     m_containsDirtyOverlayScrollbars = false;
2840 }
2841
2842 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2843 static bool inContainingBlockChain(RenderLayer* startLayer, RenderLayer* endLayer)
2844 {
2845     if (startLayer == endLayer)
2846         return true;
2847     
2848     RenderView* view = startLayer->renderer()->view();
2849     for (RenderBlock* currentBlock = startLayer->renderer()->containingBlock(); currentBlock && currentBlock != view; currentBlock = currentBlock->containingBlock()) {
2850         if (currentBlock->layer() == endLayer)
2851             return true;
2852     }
2853     
2854     return false;
2855 }
2856 #endif
2857
2858 void RenderLayer::clipToRect(RenderLayer* rootLayer, GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect,
2859                              BorderRadiusClippingRule rule)
2860 {
2861     if (clipRect.rect() == paintDirtyRect)
2862         return;
2863     context->save();
2864     context->clip(pixelSnappedIntRect(clipRect.rect()));
2865     
2866     if (!clipRect.hasRadius())
2867         return;
2868
2869 #ifndef DISABLE_ROUNDED_CORNER_CLIPPING
2870     // If the clip rect has been tainted by a border radius, then we have to walk up our layer chain applying the clips from
2871     // any layers with overflow. The condition for being able to apply these clips is that the overflow object be in our
2872     // containing block chain so we check that also.
2873     for (RenderLayer* layer = rule == IncludeSelfForBorderRadius ? this : parent(); layer; layer = layer->parent()) {
2874         if (layer->renderer()->hasOverflowClip() && layer->renderer()->style()->hasBorderRadius() && inContainingBlockChain(this, layer)) {
2875                 LayoutPoint delta;
2876                 layer->convertToLayerCoords(rootLayer, delta);
2877                 context->addRoundedRectClip(layer->renderer()->style()->getRoundedInnerBorderFor(LayoutRect(delta, layer->size())));
2878         }
2879
2880         if (layer == rootLayer)
2881             break;
2882     }
2883 #endif
2884 }
2885
2886 void RenderLayer::restoreClip(GraphicsContext* context, const LayoutRect& paintDirtyRect, const ClipRect& clipRect)
2887 {
2888     if (clipRect.rect() == paintDirtyRect)
2889         return;
2890     context->restore();
2891 }
2892
2893 static void performOverlapTests(OverlapTestRequestMap& overlapTestRequests, const RenderLayer* rootLayer, const RenderLayer* layer)
2894 {
2895     Vector<OverlapTestRequestClient*> overlappedRequestClients;
2896     OverlapTestRequestMap::iterator end = overlapTestRequests.end();
2897     LayoutRect boundingBox = layer->boundingBox(rootLayer);
2898     for (OverlapTestRequestMap::iterator it = overlapTestRequests.begin(); it != end; ++it) {
2899         if (!boundingBox.intersects(it->second))
2900             continue;
2901
2902         it->first->setOverlapTestResult(true);
2903         overlappedRequestClients.append(it->first);
2904     }
2905     for (size_t i = 0; i < overlappedRequestClients.size(); ++i)
2906         overlapTestRequests.remove(overlappedRequestClients[i]);
2907 }
2908
2909 #if USE(ACCELERATED_COMPOSITING)
2910 static bool shouldDoSoftwarePaint(const RenderLayer* layer, bool paintingReflection)
2911 {
2912     return paintingReflection && !layer->has3DTransform();
2913 }
2914 #endif
2915     
2916 static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
2917 {
2918     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
2919     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
2920     // will do a full repaint().
2921     if (layer->renderer()->document()->didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer()->isRoot())
2922         return true;
2923
2924     // Avoid painting all layers if the document is in a state where visual updates aren't allowed.
2925     // A full repaint will occur in Document::implicitClose() if painting is suppressed here.
2926     if (!layer->renderer()->document()->visualUpdatesAllowed())
2927         return true;
2928
2929     return false;
2930 }
2931
2932
2933 void RenderLayer::paintLayer(RenderLayer* rootLayer, GraphicsContext* context,
2934                         const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
2935                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
2936                         PaintLayerFlags paintFlags)
2937 {
2938 #if USE(ACCELERATED_COMPOSITING)
2939     if (isComposited()) {
2940         // The updatingControlTints() painting pass goes through compositing layers,
2941         // but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
2942         if (context->updatingControlTints() || (paintBehavior & PaintBehaviorFlattenCompositingLayers))
2943             paintFlags |= PaintLayerTemporaryClipRects;
2944         else if (!backing()->paintsIntoWindow() && !backing()->paintsIntoCompositedAncestor() && !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection) && !(rootLayer->containsDirtyOverlayScrollbars() && (paintFlags & PaintLayerPaintingOverlayScrollbars))) {
2945             // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
2946             return;
2947         }
2948     }
2949 #endif
2950
2951     // Non self-painting leaf layers don't need to be painted as their renderer() should properly paint itself.
2952     if (!isSelfPaintingLayer() && !hasSelfPaintingLayerDescendant())
2953         return;
2954
2955     if (shouldSuppressPaintingLayer(this))
2956         return;
2957     
2958     // If this layer is totally invisible then there is nothing to paint.
2959     if (!renderer()->opacity())
2960         return;
2961
2962     if (paintsWithTransparency(paintBehavior))
2963         paintFlags |= PaintLayerHaveTransparency;
2964
2965     // PaintLayerAppliedTransform is used in RenderReplica, to avoid applying the transform twice.
2966     if (paintsWithTransform(paintBehavior) && !(paintFlags & PaintLayerAppliedTransform)) {
2967         TransformationMatrix layerTransform = renderableTransform(paintBehavior);
2968         // If the transform can't be inverted, then don't paint anything.
2969         if (!layerTransform.isInvertible())
2970             return;
2971
2972         // If we have a transparency layer enclosing us and we are the root of a transform, then we need to establish the transparency
2973         // layer from the parent now, assuming there is a parent
2974         if (paintFlags & PaintLayerHaveTransparency) {
2975             if (parent())
2976                 parent()->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
2977             else
2978                 beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
2979         }
2980
2981         // Make sure the parent's clip rects have been calculated.
2982         ClipRect clipRect = paintDirtyRect;
2983         if (parent()) {
2984             clipRect = backgroundClipRect(rootLayer, region, (paintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects);
2985             clipRect.intersect(paintDirtyRect);
2986         
2987             // Push the parent coordinate space's clip.
2988             parent()->clipToRect(rootLayer, context, paintDirtyRect, clipRect);
2989         }
2990
2991         // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
2992         // This involves subtracting out the position of the layer in our current coordinate space.
2993         LayoutPoint delta;
2994         convertToLayerCoords(rootLayer, delta);
2995         TransformationMatrix transform(layerTransform);
2996         transform.translateRight(delta.x(), delta.y());
2997         
2998         // Apply the transform.
2999         {
3000             GraphicsContextStateSaver stateSaver(*context);
3001             context->concatCTM(transform.toAffineTransform());
3002
3003             // Now do a paint with the root layer shifted to be us.
3004             paintLayerContentsAndReflection(this, context, transform.inverse().mapRect(paintDirtyRect), paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3005         }        
3006
3007         // Restore the clip.
3008         if (parent())
3009             parent()->restoreClip(context, paintDirtyRect, clipRect);
3010
3011         return;
3012     }
3013     
3014     paintLayerContentsAndReflection(rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3015 }
3016
3017 void RenderLayer::paintLayerContentsAndReflection(RenderLayer* rootLayer, GraphicsContext* context,
3018                         const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3019                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3020                         PaintLayerFlags paintFlags)
3021 {
3022     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3023
3024     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3025
3026     // Paint the reflection first if we have one.
3027     if (m_reflection && !m_paintingInsideReflection) {
3028         // Mark that we are now inside replica painting.
3029         m_paintingInsideReflection = true;
3030         reflectionLayer()->paintLayer(rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags | PaintLayerPaintingReflection);
3031         m_paintingInsideReflection = false;
3032     }
3033
3034     localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
3035     paintLayerContents(rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3036 }
3037
3038 void RenderLayer::paintLayerContents(RenderLayer* rootLayer, GraphicsContext* context, 
3039                         const LayoutRect& parentPaintDirtyRect, PaintBehavior paintBehavior,
3040                         RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3041                         PaintLayerFlags paintFlags)
3042 {
3043     ASSERT(isSelfPaintingLayer() || hasSelfPaintingLayerDescendant());
3044
3045     PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
3046     bool haveTransparency = localPaintFlags & PaintLayerHaveTransparency;
3047     bool isSelfPaintingLayer = this->isSelfPaintingLayer();
3048     bool isPaintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
3049     // Outline always needs to be painted even if we have no visible content.
3050     bool shouldPaintOutline = isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3051     bool shouldPaintContent = m_hasVisibleContent && isSelfPaintingLayer && !isPaintingOverlayScrollbars;
3052
3053     // Calculate the clip rects we should use only when we need them.
3054     LayoutRect layerBounds;
3055     ClipRect damageRect, clipRectToApply, outlineRect;
3056     LayoutPoint paintOffset;
3057     LayoutRect paintDirtyRect = parentPaintDirtyRect;
3058     
3059     bool useClipRect = true;
3060     GraphicsContext* transparencyLayerContext = context;
3061     
3062     // Ensure our lists are up-to-date.
3063     updateLayerListsIfNeeded();
3064
3065 #if ENABLE(CSS_FILTERS)
3066     FilterEffectRendererHelper filterPainter(filterRenderer() && paintsWithFilters());
3067     if (filterPainter.haveFilterEffect() && !context->paintingDisabled()) {
3068         LayoutPoint rootLayerOffset;
3069         convertToLayerCoords(rootLayer, rootLayerOffset);
3070         RenderLayerFilterInfo* filterInfo = this->filterInfo();
3071         ASSERT(filterInfo);
3072         LayoutRect filterRepaintRect = filterInfo->dirtySourceRect();
3073         filterRepaintRect.move(rootLayerOffset.x(), rootLayerOffset.y());
3074         if (filterPainter.prepareFilterEffect(this, calculateLayerBounds(this, rootLayer, 0), parentPaintDirtyRect, filterRepaintRect)) {
3075             // Now we know for sure, that the source image will be updated, so we can revert our tracking repaint rect back to zero.
3076             filterInfo->resetDirtySourceRect();
3077
3078             // Rewire the old context to a memory buffer, so that we can capture the contents of the layer.
3079             // NOTE: We saved the old context in the "transparencyLayerContext" local variable, to be able to start a transparency layer
3080             // on the original context and avoid duplicating "beginFilterEffect" after each transpareny layer call. Also, note that 
3081             // beginTransparencyLayers will only create a single lazy transparency layer, even though it is called twice in this method.
3082             context = filterPainter.beginFilterEffect(context);
3083
3084             // Check that we didn't fail to allocate the graphics context for the offscreen buffer.
3085             if (filterPainter.hasStartedFilterEffect()) {
3086                 paintDirtyRect = filterPainter.repaintRect();
3087                 // If the filter needs the full source image, we need to avoid using the clip rectangles.
3088                 // Otherwise, if for example this layer has overflow:hidden, a drop shadow will not compute correctly.
3089                 // Note that we will still apply the clipping on the final rendering of the filter.
3090                 useClipRect = !filterRenderer()->hasFilterThatMovesPixels();
3091             }
3092         }
3093     }
3094 #endif
3095     
3096     if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
3097         calculateRects(rootLayer, region, (localPaintFlags & PaintLayerTemporaryClipRects) ? TemporaryClipRects : PaintingClipRects, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
3098         paintOffset = toPoint(layerBounds.location() - renderBoxLocation());
3099     }
3100
3101     bool forceBlackText = paintBehavior & PaintBehaviorForceBlackText;
3102     bool selectionOnly  = paintBehavior & PaintBehaviorSelectionOnly;
3103     
3104     // If this layer's renderer is a child of the paintingRoot, we render unconditionally, which
3105     // is done by passing a nil paintingRoot down to our renderer (as if no paintingRoot was ever set).
3106     // Else, our renderer tree may or may not contain the painting root, so we pass that root along
3107     // so it will be tested against as we descend through the renderers.
3108     RenderObject* paintingRootForRenderer = 0;
3109     if (paintingRoot && !renderer()->isDescendantOf(paintingRoot))
3110         paintingRootForRenderer = paintingRoot;
3111
3112     if (overlapTestRequests && isSelfPaintingLayer)
3113         performOverlapTests(*overlapTestRequests, rootLayer, this);
3114
3115     // We want to paint our layer, but only if we intersect the damage rect.
3116     shouldPaintContent &= intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
3117     
3118     if (localPaintFlags & PaintLayerPaintingCompositingBackgroundPhase) {
3119         if (shouldPaintContent && !selectionOnly) {
3120             // Begin transparency layers lazily now that we know we have to paint something.
3121             if (haveTransparency)
3122                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3123         
3124             if (useClipRect) {
3125                 // Paint our background first, before painting any child layers.
3126                 // Establish the clip used to paint our background.
3127                 clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Background painting will handle clipping to self.
3128             }
3129             
3130             // Paint the background.
3131             PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseBlockBackground, false, paintingRootForRenderer, region, 0);
3132             renderer()->paint(paintInfo, paintOffset);
3133
3134             if (useClipRect) {
3135                 // Restore the clip.
3136                 restoreClip(context, paintDirtyRect, damageRect);
3137             }
3138         }
3139
3140         // Now walk the sorted list of children with negative z-indices.
3141         paintList(negZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3142     }
3143     
3144     if (localPaintFlags & PaintLayerPaintingCompositingForegroundPhase) {
3145         // Now establish the appropriate clip and paint our child RenderObjects.
3146         if (shouldPaintContent && !clipRectToApply.isEmpty()) {
3147             // Begin transparency layers lazily now that we know we have to paint something.
3148             if (haveTransparency)
3149                 beginTransparencyLayers(transparencyLayerContext, rootLayer, paintDirtyRect, paintBehavior);
3150
3151             if (useClipRect) {
3152                 // Set up the clip used when painting our children.
3153                 clipToRect(rootLayer, context, paintDirtyRect, clipRectToApply);
3154             }
3155             
3156             PaintInfo paintInfo(context, pixelSnappedIntRect(clipRectToApply.rect()),
3157                                 selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds,
3158                                 forceBlackText, paintingRootForRenderer, region, 0);
3159             renderer()->paint(paintInfo, paintOffset);
3160             if (!selectionOnly) {
3161                 paintInfo.phase = PaintPhaseFloat;
3162                 renderer()->paint(paintInfo, paintOffset);
3163                 paintInfo.phase = PaintPhaseForeground;
3164                 paintInfo.overlapTestRequests = overlapTestRequests;
3165                 renderer()->paint(paintInfo, paintOffset);
3166                 paintInfo.phase = PaintPhaseChildOutlines;
3167                 renderer()->paint(paintInfo, paintOffset);
3168             }
3169
3170             if (useClipRect) {
3171                 // Now restore our clip.
3172                 restoreClip(context, paintDirtyRect, clipRectToApply);
3173             }
3174         }
3175
3176         if (shouldPaintOutline && !outlineRect.isEmpty()) {
3177             // Paint our own outline
3178             PaintInfo paintInfo(context, pixelSnappedIntRect(outlineRect.rect()), PaintPhaseSelfOutline, false, paintingRootForRenderer, region, 0);
3179             clipToRect(rootLayer, context, paintDirtyRect, outlineRect, DoNotIncludeSelfForBorderRadius);
3180             renderer()->paint(paintInfo, paintOffset);
3181             restoreClip(context, paintDirtyRect, outlineRect);
3182         }
3183     
3184         // Paint any child layers that have overflow.
3185         paintList(m_normalFlowList, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3186     
3187         // Now walk the sorted list of children with positive z-indices.
3188         paintList(posZOrderList(), rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, localPaintFlags);
3189     }
3190     
3191     if ((localPaintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && renderer()->hasMask() && !selectionOnly) {
3192         if (useClipRect)
3193             clipToRect(rootLayer, context, paintDirtyRect, damageRect, DoNotIncludeSelfForBorderRadius); // Mask painting will handle clipping to self.
3194
3195         // Paint the mask.
3196         PaintInfo paintInfo(context, pixelSnappedIntRect(damageRect.rect()), PaintPhaseMask, false, paintingRootForRenderer, region, 0);
3197         renderer()->paint(paintInfo, paintOffset);
3198         
3199         if (useClipRect) {
3200             // Restore the clip.
3201             restoreClip(context, paintDirtyRect, damageRect);
3202         }
3203     }
3204
3205     if (isPaintingOverlayScrollbars) {
3206         clipToRect(rootLayer, context, paintDirtyRect, damageRect);
3207         paintOverflowControls(context, roundedIntPoint(paintOffset), pixelSnappedIntRect(damageRect.rect()), true);
3208         restoreClip(context, paintDirtyRect, damageRect);
3209     }
3210
3211 #if ENABLE(CSS_FILTERS)
3212     if (filterPainter.hasStartedFilterEffect()) {
3213         // Apply the correct clipping (ie. overflow: hidden).
3214         clipToRect(rootLayer, transparencyLayerContext, paintDirtyRect, damageRect);
3215         context = filterPainter.applyFilterEffect();
3216         restoreClip(transparencyLayerContext, paintDirtyRect, damageRect);
3217     }
3218 #endif
3219
3220     // Make sure that we now use the original transparency context.
3221     ASSERT(transparencyLayerContext == context);
3222     
3223     // End our transparency layer
3224     if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
3225         context->endTransparencyLayer();
3226         context->restore();
3227         m_usedTransparency = false;
3228     }
3229 }
3230
3231 void RenderLayer::paintList(Vector<RenderLayer*>* list, RenderLayer* rootLayer, GraphicsContext* context,
3232                             const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3233                             RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3234                             PaintLayerFlags paintFlags)
3235 {
3236     if (!list)
3237         return;
3238
3239     if (!hasSelfPaintingLayerDescendant())
3240         return;
3241
3242 #if !ASSERT_DISABLED
3243     LayerListMutationDetector mutationChecker(this);
3244 #endif
3245
3246     for (size_t i = 0; i < list->size(); ++i) {
3247         RenderLayer* childLayer = list->at(i);
3248         if (!childLayer->isPaginated())
3249             childLayer->paintLayer(rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3250         else
3251             paintPaginatedChildLayer(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3252     }
3253 }
3254
3255 void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3256                                            const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3257                                            RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3258                                            PaintLayerFlags paintFlags)
3259 {
3260     // We need to do multiple passes, breaking up our child layer into strips.
3261     Vector<RenderLayer*> columnLayers;
3262     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3263     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3264         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3265             columnLayers.append(curr);
3266         if (curr == ancestorLayer)
3267             break;
3268     }
3269
3270     // It is possible for paintLayer() to be called after the child layer ceases to be paginated but before
3271     // updateLayerPositions() is called and resets the isPaginated() flag, see <rdar://problem/10098679>.
3272     // If this is the case, just bail out, since the upcoming call to updateLayerPositions() will repaint the layer.
3273     if (!columnLayers.size())
3274         return;
3275
3276     paintChildLayerIntoColumns(childLayer, rootLayer, context, paintDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags, columnLayers, columnLayers.size() - 1);
3277 }
3278
3279 void RenderLayer::paintChildLayerIntoColumns(RenderLayer* childLayer, RenderLayer* rootLayer, GraphicsContext* context,
3280                                              const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior,
3281                                              RenderObject* paintingRoot, RenderRegion* region, OverlapTestRequestMap* overlapTestRequests,
3282                                              PaintLayerFlags paintFlags, const Vector<RenderLayer*>& columnLayers, size_t colIndex)
3283 {
3284     RenderBlock* columnBlock = toRenderBlock(columnLayers[colIndex]->renderer());
3285
3286     ASSERT(columnBlock && columnBlock->hasColumns());
3287     if (!columnBlock || !columnBlock->hasColumns())
3288         return;
3289     
3290     LayoutPoint layerOffset;
3291     // FIXME: It looks suspicious to call convertToLayerCoords here
3292     // as canUseConvertToLayerCoords is true for this layer.
3293     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3294     
3295     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3296
3297     ColumnInfo* colInfo = columnBlock->columnInfo();
3298     unsigned colCount = columnBlock->columnCount(colInfo);
3299     LayoutUnit currLogicalTopOffset = 0;
3300     for (unsigned i = 0; i < colCount; i++) {
3301         // For each rect, we clip to the rect, and then we adjust our coords.
3302         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3303         columnBlock->flipForWritingMode(colRect);
3304         LayoutUnit logicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - columnBlock->logicalLeftOffsetForContent();
3305         LayoutSize offset;
3306         if (isHorizontal) {
3307             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3308                 offset = LayoutSize(logicalLeftOffset, currLogicalTopOffset);
3309             else
3310                 offset = LayoutSize(0, colRect.y() + currLogicalTopOffset - columnBlock->borderTop() - columnBlock->paddingTop());
3311         } else {
3312             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3313                 offset = LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3314             else
3315                 offset = LayoutSize(colRect.x() + currLogicalTopOffset - columnBlock->borderLeft() - columnBlock->paddingLeft(), 0);
3316         }
3317
3318         colRect.moveBy(layerOffset);
3319
3320         LayoutRect localDirtyRect(paintDirtyRect);
3321         localDirtyRect.intersect(colRect);
3322         
3323         if (!localDirtyRect.isEmpty()) {
3324             GraphicsContextStateSaver stateSaver(*context);
3325             
3326             // Each strip pushes a clip, since column boxes are specified as being
3327             // like overflow:hidden.
3328             context->clip(pixelSnappedIntRect(colRect));
3329
3330             if (!colIndex) {
3331                 // Apply a translation transform to change where the layer paints.
3332                 TransformationMatrix oldTransform;
3333                 bool oldHasTransform = childLayer->transform();
3334                 if (oldHasTransform)
3335                     oldTransform = *childLayer->transform();
3336                 TransformationMatrix newTransform(oldTransform);
3337                 newTransform.translateRight(roundToInt(offset.width()), roundToInt(offset.height()));
3338                 
3339                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3340                 childLayer->paintLayer(rootLayer, context, localDirtyRect, paintBehavior, paintingRoot, region, overlapTestRequests, paintFlags);
3341                 if (oldHasTransform)
3342                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3343                 else
3344                     childLayer->m_transform.clear();
3345             } else {
3346                 // Adjust the transform such that the renderer's upper left corner will paint at (0,0) in user space.
3347                 // This involves subtracting out the position of the layer in our current coordinate space.
3348                 LayoutPoint childOffset;
3349                 columnLayers[colIndex - 1]->convertToLayerCoords(rootLayer, childOffset);
3350                 TransformationMatrix transform;
3351                 transform.translateRight(roundToInt(childOffset.x() + offset.width()), roundToInt(childOffset.y() + offset.height()));
3352                 
3353                 // Apply the transform.
3354                 context->concatCTM(transform.toAffineTransform());
3355
3356                 // Now do a paint with the root layer shifted to be the next multicol block.
3357                 paintChildLayerIntoColumns(childLayer, columnLayers[colIndex - 1], context, transform.inverse().mapRect(localDirtyRect), paintBehavior, 
3358                                            paintingRoot, region, overlapTestRequests, paintFlags, 
3359                                            columnLayers, colIndex - 1);
3360             }
3361         }
3362
3363         // Move to the next position.
3364         LayoutUnit blockDelta = isHorizontal ? colRect.height() : colRect.width();
3365         if (columnBlock->style()->isFlippedBlocksWritingMode())
3366             currLogicalTopOffset += blockDelta;
3367         else
3368             currLogicalTopOffset -= blockDelta;
3369     }
3370 }
3371
3372 static inline LayoutRect frameVisibleRect(RenderObject* renderer)
3373 {
3374     FrameView* frameView = renderer->document()->view();
3375     if (!frameView)
3376         return LayoutRect();
3377
3378     return frameView->visibleContentRect();
3379 }
3380
3381 bool RenderLayer::hitTest(const HitTestRequest& request, HitTestResult& result)
3382 {
3383     renderer()->document()->updateLayout();
3384     
3385     LayoutRect hitTestArea = renderer()->isRenderFlowThread() ? toRenderFlowThread(renderer())->borderBoxRect() : renderer()->view()->documentRect();
3386     if (!request.ignoreClipping())
3387         hitTestArea.intersect(frameVisibleRect(renderer()));
3388
3389     RenderLayer* insideLayer = hitTestLayer(this, 0, request, result, hitTestArea, result.hitTestPoint(), false);
3390     if (!insideLayer) {
3391         // We didn't hit any layer. If we are the root layer and the mouse is -- or just was -- down, 
3392         // return ourselves. We do this so mouse events continue getting delivered after a drag has 
3393         // exited the WebView, and so hit testing over a scrollbar hits the content document.
3394         if ((request.active() || request.release()) && isRootLayer()) {
3395             renderer()->updateHitTestResult(result, result.point());
3396             insideLayer = this;
3397         }
3398     }
3399
3400     // Now determine if the result is inside an anchor - if the urlElement isn't already set.
3401     Node* node = result.innerNode();
3402     if (node && !result.URLElement())
3403         result.setURLElement(static_cast<Element*>(node->enclosingLinkEventParentOrSelf()));
3404
3405     // Next set up the correct :hover/:active state along the new chain.
3406     updateHoverActiveState(request, result);
3407     
3408     // Now return whether we were inside this layer (this will always be true for the root
3409     // layer).
3410     return insideLayer;
3411 }
3412
3413 Node* RenderLayer::enclosingElement() const
3414 {
3415     for (RenderObject* r = renderer(); r; r = r->parent()) {
3416         if (Node* e = r->node())
3417             return e;
3418     }
3419     ASSERT_NOT_REACHED();
3420     return 0;
3421 }
3422
3423 // Compute the z-offset of the point in the transformState.
3424 // This is effectively projecting a ray normal to the plane of ancestor, finding where that
3425 // ray intersects target, and computing the z delta between those two points.
3426 static double computeZOffset(const HitTestingTransformState& transformState)
3427 {
3428     // We got an affine transform, so no z-offset
3429     if (transformState.m_accumulatedTransform.isAffine())
3430         return 0;
3431
3432     // Flatten the point into the target plane
3433     FloatPoint targetPoint = transformState.mappedPoint();
3434     
3435     // Now map the point back through the transform, which computes Z.
3436     FloatPoint3D backmappedPoint = transformState.m_accumulatedTransform.mapPoint(FloatPoint3D(targetPoint));
3437     return backmappedPoint.z();
3438 }
3439
3440 PassRefPtr<HitTestingTransformState> RenderLayer::createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer,
3441                                         const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3442                                         const HitTestingTransformState* containerTransformState) const
3443 {
3444     RefPtr<HitTestingTransformState> transformState;
3445     LayoutPoint offset;
3446     if (containerTransformState) {
3447         // If we're already computing transform state, then it's relative to the container (which we know is non-null).
3448         transformState = HitTestingTransformState::create(*containerTransformState);
3449         convertToLayerCoords(containerLayer, offset);
3450     } else {
3451         // If this is the first time we need to make transform state, then base it off of hitTestPoint,
3452         // which is relative to rootLayer.
3453         transformState = HitTestingTransformState::create(hitTestPoint.point(), FloatQuad(hitTestRect));
3454         convertToLayerCoords(rootLayer, offset);
3455     }
3456     
3457     RenderObject* containerRenderer = containerLayer ? containerLayer->renderer() : 0;
3458     if (renderer()->shouldUseTransformFromContainer(containerRenderer)) {
3459         TransformationMatrix containerTransform;
3460         renderer()->getTransformFromContainer(containerRenderer, toLayoutSize(offset), containerTransform);
3461         transformState->applyTransform(containerTransform, HitTestingTransformState::AccumulateTransform);
3462     } else {
3463         transformState->translate(offset.x(), offset.y(), HitTestingTransformState::AccumulateTransform);
3464     }
3465     
3466     return transformState;
3467 }
3468
3469
3470 static bool isHitCandidate(const RenderLayer* hitLayer, bool canDepthSort, double* zOffset, const HitTestingTransformState* transformState)
3471 {
3472     if (!hitLayer)
3473         return false;
3474
3475     // The hit layer is depth-sorting with other layers, so just say that it was hit.
3476     if (canDepthSort)
3477         return true;
3478     
3479     // We need to look at z-depth to decide if this layer was hit.
3480     if (zOffset) {
3481         ASSERT(transformState);
3482         // This is actually computing our z, but that's OK because the hitLayer is coplanar with us.
3483         double childZOffset = computeZOffset(*transformState);
3484         if (childZOffset > *zOffset) {
3485             *zOffset = childZOffset;
3486             return true;
3487         }
3488         return false;
3489     }
3490
3491     return true;
3492 }
3493
3494 // hitTestPoint and hitTestRect are relative to rootLayer.
3495 // A 'flattening' layer is one preserves3D() == false.
3496 // transformState.m_accumulatedTransform holds the transform from the containing flattening layer.
3497 // transformState.m_lastPlanarPoint is the hitTestPoint in the plane of the containing flattening layer.
3498 // transformState.m_lastPlanarQuad is the hitTestRect as a quad in the plane of the containing flattening layer.
3499 // 
3500 // If zOffset is non-null (which indicates that the caller wants z offset information), 
3501 //  *zOffset on return is the z offset of the hit point relative to the containing flattening layer.
3502 RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
3503                                        const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, bool appliedTransform,
3504                                        const HitTestingTransformState* transformState, double* zOffset)
3505 {
3506     // The natural thing would be to keep HitTestingTransformState on the stack, but it's big, so we heap-allocate.
3507
3508     bool useTemporaryClipRects = renderer()->view()->frameView()->containsScrollableAreaWithOverlayScrollbars();
3509
3510     // Apply a transform if we have one.
3511     if (transform() && !appliedTransform) {
3512         // Make sure the parent's clip rects have been calculated.
3513         if (parent()) {
3514             ClipRect clipRect = backgroundClipRect(rootLayer, result.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, IncludeOverlayScrollbarSize);
3515             // Go ahead and test the enclosing clip now.
3516             if (!clipRect.intersects(hitTestPoint))
3517                 return 0;
3518         }
3519
3520         // Create a transform state to accumulate this transform.
3521         RefPtr<HitTestingTransformState> newTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3522
3523         // If the transform can't be inverted, then don't hit test this layer at all.
3524         if (!newTransformState->m_accumulatedTransform.isInvertible())
3525             return 0;
3526
3527         // Compute the point and the hit test rect in the coords of this layer by using the values
3528         // from the transformState, which store the point and quad in the coords of the last flattened
3529         // layer, and the accumulated transform which lets up map through preserve-3d layers.
3530         //
3531         // We can't just map hitTestPoint and hitTestRect because they may have been flattened (losing z)
3532         // by our container.
3533         LayoutPoint localPoint = roundedLayoutPoint(newTransformState->mappedPoint());
3534         LayoutRect localHitTestRect = newTransformState->boundsOfMappedQuad();
3535         HitTestPoint newHitTestPoint(result.hitTestPoint());
3536         newHitTestPoint.setPoint(localPoint);
3537
3538         // Now do a hit test with the root layer shifted to be us.
3539         return hitTestLayer(this, containerLayer, request, result, localHitTestRect, newHitTestPoint, true, newTransformState.get(), zOffset);
3540     }
3541
3542     // Ensure our lists and 3d status are up-to-date.
3543     updateCompositingAndLayerListsIfNeeded();
3544     update3DTransformedDescendantStatus();
3545
3546     RefPtr<HitTestingTransformState> localTransformState;
3547     if (appliedTransform) {
3548         // We computed the correct state in the caller (above code), so just reference it.
3549         ASSERT(transformState);
3550         localTransformState = const_cast<HitTestingTransformState*>(transformState);
3551     } else if (transformState || m_has3DTransformedDescendant || preserves3D()) {
3552         // We need transform state for the first time, or to offset the container state, so create it here.
3553         localTransformState = createLocalTransformState(rootLayer, containerLayer, hitTestRect, hitTestPoint, transformState);
3554     }
3555
3556     // Check for hit test on backface if backface-visibility is 'hidden'
3557     if (localTransformState && renderer()->style()->backfaceVisibility() == BackfaceVisibilityHidden) {
3558         TransformationMatrix invertedMatrix = localTransformState->m_accumulatedTransform.inverse();
3559         // If the z-vector of the matrix is negative, the back is facing towards the viewer.
3560         if (invertedMatrix.m33() < 0)
3561             return 0;
3562     }
3563
3564     RefPtr<HitTestingTransformState> unflattenedTransformState = localTransformState;
3565     if (localTransformState && !preserves3D()) {
3566         // Keep a copy of the pre-flattening state, for computing z-offsets for the container
3567         unflattenedTransformState = HitTestingTransformState::create(*localTransformState);
3568         // This layer is flattening, so flatten the state passed to descendants.
3569         localTransformState->flatten();
3570     }
3571     
3572     // Calculate the clip rects we should use.
3573     LayoutRect layerBounds;
3574     ClipRect bgRect;
3575     ClipRect fgRect;
3576     ClipRect outlineRect;
3577     calculateRects(rootLayer, result.region(), useTemporaryClipRects ? TemporaryClipRects : RootRelativeClipRects, hitTestRect, layerBounds, bgRect, fgRect, outlineRect, IncludeOverlayScrollbarSize);
3578     
3579     // The following are used for keeping track of the z-depth of the hit point of 3d-transformed
3580     // descendants.
3581     double localZOffset = -numeric_limits<double>::infinity();
3582     double* zOffsetForDescendantsPtr = 0;
3583     double* zOffsetForContentsPtr = 0;
3584     
3585     bool depthSortDescendants = false;
3586     if (preserves3D()) {
3587         depthSortDescendants = true;
3588         // Our layers can depth-test with our container, so share the z depth pointer with the container, if it passed one down.
3589         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3590         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3591     } else if (m_has3DTransformedDescendant) {
3592         // Flattening layer with 3d children; use a local zOffset pointer to depth-test children and foreground.
3593         depthSortDescendants = true;
3594         zOffsetForDescendantsPtr = zOffset ? zOffset : &localZOffset;
3595         zOffsetForContentsPtr = zOffset ? zOffset : &localZOffset;
3596     } else if (zOffset) {
3597         zOffsetForDescendantsPtr = 0;
3598         // Container needs us to give back a z offset for the hit layer.
3599         zOffsetForContentsPtr = zOffset;
3600     }
3601
3602     // This variable tracks which layer the mouse ends up being inside.
3603     RenderLayer* candidateLayer = 0;
3604
3605     // Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
3606     RenderLayer* hitLayer = hitTestList(posZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3607                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3608     if (hitLayer) {
3609         if (!depthSortDescendants)
3610             return hitLayer;
3611         candidateLayer = hitLayer;
3612     }
3613
3614     // Now check our overflow objects.
3615     hitLayer = hitTestList(m_normalFlowList, rootLayer, request, result, hitTestRect, hitTestPoint,
3616                            localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3617     if (hitLayer) {
3618         if (!depthSortDescendants)
3619             return hitLayer;
3620         candidateLayer = hitLayer;
3621     }
3622
3623     // Next we want to see if the mouse pos is inside the child RenderObjects of the layer.
3624     if (fgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3625         // Hit test with a temporary HitTestResult, because we only want to commit to 'result' if we know we're frontmost.
3626         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3627         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestDescendants) &&
3628             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3629             if (result.isRectBasedTest())
3630                 result.append(tempResult);
3631             else
3632                 result = tempResult;
3633             if (!depthSortDescendants)
3634                 return this;
3635             // Foreground can depth-sort with descendant layers, so keep this as a candidate.
3636             candidateLayer = this;
3637         } else if (result.isRectBasedTest())
3638             result.append(tempResult);
3639     }
3640
3641     // Now check our negative z-index children.
3642     hitLayer = hitTestList(negZOrderList(), rootLayer, request, result, hitTestRect, hitTestPoint,
3643                                         localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
3644     if (hitLayer) {
3645         if (!depthSortDescendants)
3646             return hitLayer;
3647         candidateLayer = hitLayer;
3648     }
3649
3650     // If we found a layer, return. Child layers, and foreground always render in front of background.
3651     if (candidateLayer)
3652         return candidateLayer;
3653
3654     if (bgRect.intersects(hitTestPoint) && isSelfPaintingLayer()) {
3655         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3656         if (hitTestContents(request, tempResult, layerBounds, hitTestPoint, HitTestSelf) &&
3657             isHitCandidate(this, false, zOffsetForContentsPtr, unflattenedTransformState.get())) {
3658             if (result.isRectBasedTest())
3659                 result.append(tempResult);
3660             else
3661                 result = tempResult;
3662             return this;
3663         } else if (result.isRectBasedTest())
3664             result.append(tempResult);
3665     }
3666
3667     return 0;
3668 }
3669
3670 bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult& result, const LayoutRect& layerBounds, const HitTestPoint& hitTestPoint, HitTestFilter hitTestFilter) const
3671 {
3672     if (!renderer()->hitTest(request, result, hitTestPoint,
3673                             toLayoutPoint(layerBounds.location() - renderBoxLocation()),
3674                             hitTestFilter)) {
3675         // It's wrong to set innerNode, but then claim that you didn't hit anything, unless it is
3676         // a rect-based test.
3677         ASSERT(!result.innerNode() || (result.isRectBasedTest() && result.rectBasedTestResult().size()));
3678         return false;
3679     }
3680
3681     // For positioned generated content, we might still not have a
3682     // node by the time we get to the layer level, since none of
3683     // the content in the layer has an element. So just walk up
3684     // the tree.
3685     if (!result.innerNode() || !result.innerNonSharedNode()) {
3686         Node* e = enclosingElement();
3687         if (!result.innerNode())
3688             result.setInnerNode(e);
3689         if (!result.innerNonSharedNode())
3690             result.setInnerNonSharedNode(e);
3691     }
3692         
3693     return true;
3694 }
3695
3696 RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
3697                                       const HitTestRequest& request, HitTestResult& result,
3698                                       const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint,
3699                                       const HitTestingTransformState* transformState, 
3700                                       double* zOffsetForDescendants, double* zOffset,
3701                                       const HitTestingTransformState* unflattenedTransformState,
3702                                       bool depthSortDescendants)
3703 {
3704     if (!list)
3705         return 0;
3706     
3707     RenderLayer* resultLayer = 0;
3708     for (int i = list->size() - 1; i >= 0; --i) {
3709         RenderLayer* childLayer = list->at(i);
3710         RenderLayer* hitLayer = 0;
3711         HitTestResult tempResult(result.hitTestPoint(), result.shadowContentFilterPolicy());
3712         if (childLayer->isPaginated())
3713             hitLayer = hitTestPaginatedChildLayer(childLayer, rootLayer, request, tempResult, hitTestRect, hitTestPoint, transformState, zOffsetForDescendants);
3714         else
3715             hitLayer = childLayer->hitTestLayer(rootLayer, this, request, tempResult, hitTestRect, hitTestPoint, false, transformState, zOffsetForDescendants);
3716
3717         // If it a rect-based test, we can safely append the temporary result since it might had hit
3718         // nodes but not necesserily had hitLayer set.
3719         if (result.isRectBasedTest())
3720             result.append(tempResult);
3721
3722         if (isHitCandidate(hitLayer, depthSortDescendants, zOffset, unflattenedTransformState)) {
3723             resultLayer = hitLayer;
3724             if (!result.isRectBasedTest())
3725                 result = tempResult;
3726             if (!depthSortDescendants)
3727                 break;
3728         }
3729     }
3730
3731     return resultLayer;
3732 }
3733
3734 RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3735                                                      const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset)
3736 {
3737     Vector<RenderLayer*> columnLayers;
3738     RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : stackingContext();
3739     for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
3740         if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
3741             columnLayers.append(curr);
3742         if (curr == ancestorLayer)
3743             break;
3744     }
3745
3746     ASSERT(columnLayers.size());
3747     return hitTestChildLayerColumns(childLayer, rootLayer, request, result, hitTestRect, hitTestPoint, transformState, zOffset,
3748                                     columnLayers, columnLayers.size() - 1);
3749 }
3750
3751 RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
3752                                                    const LayoutRect& hitTestRect, const HitTestPoint& hitTestPoint, const HitTestingTransformState* transformState, double* zOffset,
3753                                                    const Vector<RenderLayer*>& columnLayers, size_t columnIndex)
3754 {
3755     RenderBlock* columnBlock = toRenderBlock(columnLayers[columnIndex]->renderer());
3756
3757     ASSERT(columnBlock && columnBlock->hasColumns());
3758     if (!columnBlock || !columnBlock->hasColumns())
3759         return 0;
3760
3761     LayoutPoint layerOffset;
3762     columnBlock->layer()->convertToLayerCoords(rootLayer, layerOffset);
3763
3764     ColumnInfo* colInfo = columnBlock->columnInfo();
3765     int colCount = columnBlock->columnCount(colInfo);
3766
3767     // We have to go backwards from the last column to the first.
3768     bool isHorizontal = columnBlock->style()->isHorizontalWritingMode();
3769     LayoutUnit logicalLeft = columnBlock->logicalLeftOffsetForContent();
3770     LayoutUnit currLogicalTopOffset = 0;
3771     int i;
3772     for (i = 0; i < colCount; i++) {
3773         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3774         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3775         if (columnBlock->style()->isFlippedBlocksWritingMode())
3776             currLogicalTopOffset += blockDelta;
3777         else
3778             currLogicalTopOffset -= blockDelta;
3779     }
3780     for (i = colCount - 1; i >= 0; i--) {
3781         // For each rect, we clip to the rect, and then we adjust our coords.
3782         LayoutRect colRect = columnBlock->columnRectAt(colInfo, i);
3783         columnBlock->flipForWritingMode(colRect);
3784         LayoutUnit currLogicalLeftOffset = (isHorizontal ? colRect.x() : colRect.y()) - logicalLeft;
3785         LayoutUnit blockDelta =  (isHorizontal ? colRect.height() : colRect.width());
3786         if (columnBlock->style()->isFlippedBlocksWritingMode())
3787             currLogicalTopOffset -= blockDelta;
3788         else
3789             currLogicalTopOffset += blockDelta;
3790
3791         LayoutSize offset;
3792         if (isHorizontal) {
3793             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3794                 offset = LayoutSize(currLogicalLeftOffset, currLogicalTopOffset);
3795             else
3796                 offset = LayoutSize(0, colRect.y() + currLogicalTopOffset - columnBlock->borderTop() - columnBlock->paddingTop());
3797         } else {
3798             if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3799                 offset = LayoutSize(currLogicalTopOffset, currLogicalLeftOffset);
3800             else
3801                 offset = LayoutSize(colRect.x() + currLogicalTopOffset - columnBlock->borderLeft() - columnBlock->paddingLeft(), 0);
3802         }
3803
3804         colRect.moveBy(layerOffset);
3805
3806         LayoutRect localClipRect(hitTestRect);
3807         localClipRect.intersect(colRect);
3808
3809         if (!localClipRect.isEmpty() && hitTestPoint.intersects(localClipRect)) {
3810             RenderLayer* hitLayer = 0;
3811             if (!columnIndex) {
3812                 // Apply a translation transform to change where the layer paints.
3813                 TransformationMatrix oldTransform;
3814                 bool oldHasTransform = childLayer->transform();
3815                 if (oldHasTransform)
3816                     oldTransform = *childLayer->transform();
3817                 TransformationMatrix newTransform(oldTransform);
3818                 newTransform.translateRight(offset.width(), offset.height());
3819
3820                 childLayer->m_transform = adoptPtr(new TransformationMatrix(newTransform));
3821                 hitLayer = childLayer->hitTestLayer(rootLayer, columnLayers[0], request, result, localClipRect, hitTestPoint, false, transformState, zOffset);
3822                 if (oldHasTransform)
3823                     childLayer->m_transform = adoptPtr(new TransformationMatrix(oldTransform));
3824                 else
3825                     childLayer->m_transform.clear();
3826             } else {
3827                 // Adjust the transform such that the renderer's upper left corner will be at (0,0) in user space.
3828                 // This involves subtracting out the position of the layer in our current coordinate space.
3829                 RenderLayer* nextLayer = columnLayers[columnIndex - 1];
3830                 RefPtr<HitTestingTransformState> newTransformState = nextLayer->createLocalTransformState(rootLayer, nextLayer, localClipRect, hitTestPoint, transformState);
3831                 newTransformState->translate(offset.width(), offset.height(), HitTestingTransformState::AccumulateTransform);
3832                 LayoutPoint localPoint = roundedLayoutPoint(newTransformState->mappedPoint());
3833                 LayoutRect localHitTestRect = newTransformState->mappedQuad().enclosingBoundingBox();
3834                 HitTestPoint newHitTestPoint(result.hitTestPoint());
3835                 newHitTestPoint.setPoint(localPoint);
3836                 newTransformState->flatten();
3837
3838                 hitLayer = hitTestChildLayerColumns(childLayer, columnLayers[columnIndex - 1], request, result, localHitTestRect, newHitTestPoint,
3839                                                     newTransformState.get(), zOffset, columnLayers, columnIndex - 1);
3840             }
3841
3842             if (hitLayer)
3843                 return hitLayer;
3844         }