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