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