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