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