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