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