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