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